为什么这不起作用:
iex(2)> Enum.map(["the", "huge", "elephant"], String.length)
** (UndefinedFunctionError) function String.length/0 is undefined or private.
Run Code Online (Sandbox Code Playgroud)
但这样做:
iex(2)> Enum.map(["the", "huge", "elephant"], fn x -> String.length(x) end)
[3, 4, 8]
Run Code Online (Sandbox Code Playgroud)
我的意思是,String.length是一个函数,对吗?就像我的匿名包装一样?或者是根据错误消息的某种范围问题?
我对另一种功能(ish)语言的唯一体验是R,这样可以正常工作:
> sapply(c("the", "huge", "elephant"), nchar)
the huge elephant
3 4 8
> sapply(c("the", "huge", "elephant"), function(x) nchar(x))
the huge elephant
3 4 8
Run Code Online (Sandbox Code Playgroud)
String.length
是一个函数,但是当Elixir允许调用没有括号的函数时,你实际上并没有在键入时返回函数String.length
,而是使用0参数调用该函数的结果.你必须使用&module.function/arity
语法:
iex(1)> Enum.map(["the", "huge", "elephant"], &String.length/1)
[3, 4, 8]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
100 次 |
最近记录: |