匿名函数简写 [英] Anonymous function shorthand

查看:196
本文介绍了匿名函数简写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有些东西我不明白匿名函数使用短符号#(..)

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"



< t了解是为什么(#(%)Eh)不起作用,同时我不需要使用 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 ...] (...))


b $ b

(其中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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆