Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate vectors or tuples in a function (julia)

Tags:

julia

I want to evaluate a set of vectors (or tuples) in a function $f$ but Julia says me that is imposible.

For example: If I have an array of tuples p=[(1,1), (1,-1), (-1,1), (-1,-1)] and a function f(x,y)=x+y. I would like to calculate f(p[1]) = f(1,1)= 2. But Julia says me that the types are incompatible.

Can you help me please?

like image 924
Tio Miserias Avatar asked Feb 22 '21 19:02

Tio Miserias


3 Answers

You have to splat a tuple like this:

julia> p=[(1,1), (1,-1), (-1,1), (-1,-1)]
4-element Array{Tuple{Int64,Int64},1}:
 (1, 1)
 (1, -1)
 (-1, 1)
 (-1, -1)

julia> f(x,y)=x+y
f (generic function with 1 method)

julia> f(p[1]...)
2

you could also define a higher order function splat that would conveniently wrap any function and perform splatting. It is useful as then you can e.g. broadcast such function:

julia> splat(f) = x -> f(x...)
splat (generic function with 1 method)

julia> splat(f)(p[1])
2

julia> splat(f).(p)
4-element Array{Int64,1}:
  2
  0
  0
 -2

Alternatively you can define your function f like this:

julia> f((x,y),)=x+y
f (generic function with 1 method)

julia> f(p[1])
2

and now you do not have to do splatting.

like image 143
Bogumił Kamiński Avatar answered Oct 18 '22 20:10

Bogumił Kamiński


Just use the ... operator to unpack the tuple as parameters:

julia> f(p[1]...)
2
like image 34
Przemyslaw Szufel Avatar answered Oct 18 '22 20:10

Przemyslaw Szufel


In addition to other answers, if your task allows you, you can just define

julia> f(x) = f(x...)

and use it as

julia> f.(p)
4-element Vector{Int64}:
  2
  0
  0
 -2
like image 21
Andrej Oskin Avatar answered Oct 18 '22 20:10

Andrej Oskin