Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a function with arguments from a list

Tags:

scala

Is there a way to call a function with arguments from a list? The equivalent in Python is sum(*args).

// Scala

def sum(x: Int, y: Int) = x + y
val args = List(1, 4)

sum.???(args)      // equivalent to sum(1, 4)

sum(args: _*) wouldn't work here. Don't offer change the declaration of the function anyhow. I'm acquainted with a function with repeated parameters def sum(args: Int*).

like image 246
Graduate Avatar asked Sep 29 '13 13:09

Graduate


People also ask

Can we pass a list an argument in a function?

You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.

How do you pass a list of arguments to a function in Python?

In Python, you can unpack list , tuple , dict (dictionary) and pass its elements to function as arguments by adding * to list or tuple and ** to dictionary when calling function.

How do I call a function from a list in Python?

In the line: def wrapper(func, *args): The * next to args means "take the rest of the parameters given and put them in a list called args ". The * next to args here means "take this list called args and 'unwrap' it into the rest of the parameters.

How do you pass list values to a function?

You have to explicitly copy the list. You can either do that outside the function or inside the function, but you have to do it. The terms "by value" and "by reference" aren't used often in Python, because they tend to be misleading to people coming from other languages.


1 Answers

Well, you can write

sum(args(0), args(1))

But I assume you want this to work for any list length? Then you would go for fold or reduce:

args.reduce(sum)  // args must be non empty!

(0 /: args)(sum)  // aka args.foldLeft(0)(sum)

These methods assume a pair-wise reduction of the list. For example, foldLeft[B](init: B)(fun: (B, A) => B): B reduces a list of elements of type A to a single element of type B. In this example, A = B = Int. It starts with the initial value init. Since you want to sum, the sum of an empty list would be zero. It then calls the function with the current accumulator (the running sum) and each successive element of the list.

So it's like

var result = 0
result = sum(result, 1)
result = sum(result, 4)
...

The reduce method assumes that the list is non-empty and requires that the element type doesn't change (the function must map from two Ints to an Int).

like image 125
0__ Avatar answered Oct 15 '22 21:10

0__