2017-10-15 90 views
0

如何使用紅色語言創建map高階函數。它應該將塊和函數作爲參數,並將發送的函數應用於塊的每個成員。我試過下面的代碼:用紅色語言創建地圖功能

Red [] 
mapfn: function[blk sfn][ 
    outblk: copy [] 
    foreach i blk[ 
     append outblk (sfn i) ] 
    outblk ] 

; to test: 
myblk: [" this " " is " " a " " line " "for" " testing " " only "] 
probe mapfn myblk 'reverse 
probe mapfn myblk 'trim 

但它不工作 - 它只是發回原始塊而不改變它或給出任何錯誤消息。這怎麼可以糾正?

回答

0

在雷博爾你有夾層功能申請

>> help apply 
USAGE: 
    APPLY func block /only 

DESCRIPTION: 
    Apply a function to a reduced block of arguments. 
    APPLY is a function value. 

ARGUMENTS: 
    func -- Function value to apply (Type: any-function) 
    block -- Block of args, reduced first (unless /only) (Type: block) 

REFINEMENTS: 
    /only -- Use arg values as-is, do not reduce the block 

(SPECIAL ATTRIBUTES) 
    throw 

源應用

只要紅已經沒有原生應用,你可以編寫自己的映射的功能,例如

mapfn: function[blk sfn][ 
    outblk: copy [] 
    foreach i blk[ 
     append outblk sfn copy i 
    ] 
    outblk 
] 

與獲取的功能:functionname

>> myblk: [" this " " is " " a " " line " "for" " testing " " only "] 
== [" this " " is " " a " " line " "for" " testing " " only "] 
>> probe mapfn myblk :reverse 
[" siht " " si " " a " " enil " "rof" " gnitset " " ylno "] 
== [" siht " " si " " a " " enil " "rof" " gnitset " " ylno "] 
>> probe mapfn myblk :trim 
["this" "is" "a" "line" "for" "testing" "only"] 
== ["this" "is" "a" "line" "for" "testing" "only"] 
>> 

的替代,正如你不能複製更好的辦法所有的數據類型都是例如

mapfn: function[blk sfn][ 
    collect [ 
     foreach i blk[ 
      keep sfn i 
     ] 
    ] 
] 

並調用該函數,如果沒有不想修改原始

mapfn newblk: copy/deep myblk :reverse 
+0

爲什麼修剪也呈現出逆轉的字符串這樣? – rnso

+0

我改變了答案。 **反向**和**修剪**在原始系列上工作並進行更改。所以你必須使用你工作的系列的副本。 – sqlab