将其他参数传递给map()中传递的函数

时间:2021-10-12 16:05:07

I want to pass a function to map() which need to use additional data (for example data passed as arguments to the scala program).

我想将一个函数传递给map(),它需要使用额外的数据(例如作为参数传递给scala程序的数据)。

For example:

I have a list:

我有一个清单:

val myList = List(1,2,3,4,5)

and a multiplier value is passed as command line argument.

并将乘数值作为命令行参数传递。

val multiplier = args(0) // In this example, let it be 2

and I have a function

我有一个功能

def multiply(a: Int, b: Int) = a*b

Now I want to perform map() on my List as below:

现在我想在我的List上执行map(),如下所示:

myList.map(multiply)

Of course this doesn't work because, map expects only one argument (which in this case is element of list).

当然这不起作用,因为map只需要一个参数(在本例中是list的元素)。

Please help me how can pass functions to map which use additional arguments.

请帮助我如何传递函数来映射哪些使用其他参数。

1 个解决方案

#1


You can accomplish this with currying

你可以用currying来做到这一点

def multiply(a: Int)(b: Int) = a*b
myList.map(multiply(multiplier))

Or, if multiply isn't your method:

或者,如果乘法不是您的方法:

val multiplyCurried = Function.curried(multiply _)
myList.map(multiplyCurried(multiplier))

#1


You can accomplish this with currying

你可以用currying来做到这一点

def multiply(a: Int)(b: Int) = a*b
myList.map(multiply(multiplier))

Or, if multiply isn't your method:

或者,如果乘法不是您的方法:

val multiplyCurried = Function.curried(multiply _)
myList.map(multiplyCurried(multiplier))