匿名函数简写 [英] Anonymous function shorthand
问题描述
关于使用短符号 #(..) 的匿名函数,我有些不明白
There's something I don't understand about anonymous functions using the short notation #(..)
以下工作:
REPL> ((fn [s] s) "Eh")
"Eh"
但这不会:
REPL> (#(%) "Eh")
这有效:
REPL> (#(str %) "Eh")
"Eh"
我不明白的是为什么 (#(%) "Eh") 不起作用,同时我不需要使用 str 在 ((fn [s] s) "Eh")
What I don't understand is why (#(%) "Eh") doesn't work and at the same time I don't need to use str in ((fn [s] s) "Eh")
它们都是匿名函数,而且它们都采用一个参数.为什么速记符号需要函数而其他符号不需要?
They're both anonymous functions and they both take, here, one parameter. Why does the shorthand notation need a function while the other notation doesn't?
推荐答案
#(...)
是
(fn [arg1 arg2 ...] (...))
(其中 argN 的数量取决于您在体内有多少 %N).所以当你写:
(where the number of argN depends on how many %N you have in the body). So when you write:
#(%)
翻译成:
(fn [arg1] (arg1))
请注意,这与您的第一个匿名函数不同,例如:
Notice that this is different from your first anonymous function, which is like:
(fn [arg1] arg1)
您的版本将 arg1 作为值返回,来自扩展速记的版本尝试将其作为函数调用.由于字符串不是有效函数,您会收到错误消息.
Your version returns arg1 as a value, the version that comes from expanding the shorthand tries to call it as a function. You get an error because a string is not a valid function.
由于简写在正文周围提供了一组括号,因此它只能用于执行单个函数调用或特殊形式.
Since the shorthand supplies a set of parentheses around the body, it can only be used to execute a single function call or special form.
这篇关于匿名函数简写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!