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*)
.
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.
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.
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.
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.
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 Int
s to an Int
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With