5

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?

M-Chen-3
  • 2,036
  • 5
  • 13
  • 34
Tio Miserias
  • 485
  • 2
  • 8

3 Answers3

5

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.

Bogumił Kamiński
  • 66,844
  • 3
  • 80
  • 107
  • [`Base.splat`](https://github.com/JuliaLang/julia/blob/715e6264e33a408a576966dc9ca2a75ddc4cc160/base/operators.jl#L1150) (which is unexported, though). – phipsgabler Feb 23 '21 at 09:36
  • Ah - right. I did not remember what was the conclusion from discussion of adding it to official API. – Bogumił Kamiński Feb 23 '21 at 10:03
4

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

julia> f(p[1]...)
2
Przemyslaw Szufel
  • 40,002
  • 3
  • 32
  • 62
1

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
Andrej Oskin
  • 2,284
  • 14
  • 11