简体   繁体   English

如何在Elixir for Enum.map中传递arity 2的函数作为参数?

[英]How to pass a function of arity 2 as an argument in Elixir for Enum.map?

Let's say I have something like: 假设我有类似的东西:

    Enum.map(list, fn(x) -> String.duplicate("a", someValue * x) end)

But instead, I'd like to pass the String.duplicate/2 function as an argument in order to simplify my code: 但相反,我想将String.duplicate / 2函数作为参数传递,以简化我的代码:

Enum.map(list, &String.duplicate/2)

I know you can do it for arity 1 functions: 我知道你可以为arity 1功能做到这一点:

Enum.map(list, &String.downcase/1)

Thanks! 谢谢!

You can't pass a function to Enum.map with an arity of 2 as Enum.map calls your function with each element in the list as an argument. 你不能传递一个功能Enum.map为2的元数为Enum.map调用在列表作为参数的每个元素的功能。 If you use another function like Enum.reduce then it expects a function with an arity of 2. 如果你使用像Enum.reduce这样的另一个函数,那么它需要一个arity为2的函数。

This is an example of the String.downcase/1 function being called with each item in the list: 这是使用列表中的每个项调用的String.downcase/1函数的示例:

Enum.map(["FOO", "BAR", "BAZ"], fn(x) -> String.downcase(x) end)
# String.downcase("FOO")
# String.downcase("BAR")
# String.downcase("BAZ")

In your example with duplicate, you are trying to call String.duplicate/2 with a single argument (the string "FOO"). 在您的带有重复的示例中,您尝试使用单个参数(字符串“FOO”)调用String.duplicate/2

You can use the capture syntax to create a function (this is a shorthand way of defining the function you provided): 您可以使用捕获语法来创建函数(这是定义您提供的函数的简写方法):

Enum.map([1,2,3], &String.duplicate("a", &1))

You can also define a named function in your module that only requires one argument, for example: 您还可以在模块中定义一个只需要一个参数的命名函数,例如:

Enum.map([1, 2, 3], &duplicate_foo/1)

def duplicate_foo(times), do: String.duplicate("a", times)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM