用Red语言创建地图功能 [英] Creating map function in Red language
问题描述
如何在以下位置创建地图,红色语言.它应该以一个块和一个函数作为参数,并将发送的函数应用于该块的每个成员.我尝试了以下代码:
How can I create map, a higher order function, in Red language. It should take a block and a function as arguments and apply the sent function to each member of block. I tried following code:
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
但是它不起作用-它只是发送回原始块,而没有对其进行更改或给出任何错误消息.该如何纠正?
But it is not working - it simply sends back the original block without changing it or giving any error message. How can this be corrected?
推荐答案
在Rebol中,您具有夹层功能 apply
In Rebol you have the mezzanine function apply
>> 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
请参见适用来源.
只要Red没有本机应用,就可以编写自己的映射函数,例如
As long as Red has no native apply you can write your own mapping function e.g
mapfn: function[blk sfn][
outblk: copy []
foreach i blk[
append outblk sfn copy i
]
outblk
]
使用:functionname获取功能
Get the function with :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"]
>>
例如,无法复制所有数据类型的另一种更好的方法是
An alternative and better way as you can not copy all datatypes is e.g.
mapfn: function[blk sfn][
collect [
foreach i blk[
keep sfn i
]
]
]
,如果不希望,则以这种方式调用该函数
and call the function this way if no do not want to modify the original
mapfn newblk: copy/deep myblk :reverse
这篇关于用Red语言创建地图功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!