Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia: Passing Multiple Arguments to Anonymous Functions

In the Julia Manual under the Anonymous Functions section one of the examples that is offered is (x,y,z)->2x+y-z.

Could someone please show me how one would pass a set of arguments to this function?

Say x=(1,2,3); y=(2,3,4); z=(1,3,5).

like image 269
Francis Smart Avatar asked Dec 26 '22 10:12

Francis Smart


2 Answers

If you define x,y and z to be arrays then you can just call the function and pass them in:

fun = (x,y,z)->2x+y-z
x=[1,2,3]
y=[2,3,4]
z=[1,3,5]
fun(x, y, z)

giving the result:

3-element Array{Int64,1}:
 3
 4
 5

But if you want to do this with tuples, as per your example, you will need to use map:

x=(1,2,3)
y=(2,3,4)
z=(1,3,5)
map(fun, x, y, z)

this gives the same result, but this time as a tuple:

(3, 4, 5)

This is because the *, + and - operators are not defined for tuples so the formula 2x+y-z can't work. Using map gets around this by calling the function multiple times passing in scalars.

like image 60
Andrew Burrows Avatar answered Dec 28 '22 10:12

Andrew Burrows


You have to assign the anonymous function to a variable, in order to call it.

julia> fun = (x,y,z)->2x+y-z
(anonymous function)

julia> fun((1,2,3),(2,3,4),(1,3,5))
ERROR: no method *(Int64, (Int64,Int64,Int64))
 in anonymous at none:1

It does not work, because the tuples you set for x, does not implement the * function.

like image 23
ivarne Avatar answered Dec 28 '22 08:12

ivarne