# ( (x,y) -> x+y ).( [ (1,2), (3,4) ] )

` ( (x,y) -> x+y ).( [ (1,2), (3,4) ] )`

gives an error.
Is it possible to apply a multi-variable anonymous function to a vector of tuples like this ?

You’re getting an error because your anonymous function takes two arguments, whereas each tuple is only a single argument.

You can use this as the anonymous function instead:

``````(x -> x + x)
``````

Or simply use `sum`.

2 Likes

You can use destructuring in the function argument list as follows:

``````julia> ( ((x,y),) -> x+y ).( [ (1,2), (3,4) ] )
2-element Vector{Int64}:
3
7
``````
6 Likes

Thanks. - always have to add that comma and put in another backet 1 Like

Heh, whether you should do this is another matter of course. It’s pretty hard to read 1 Like

can you point out where that is documented?

No. But an anonymous function of a tuple can be applied to a vector of tuples as follows:

``````jula> (((x, y),) -> x + y).([(1, 2), (3, 4)])
2-element Vector{Int64}:
3
7
``````

This is appoximately equivalent to

``````julia> f((x, y)) = x + y
julia> f.([(1, 2), (3, 4)])
2-element Vector{Int64}:
3
7
``````

Note that the comma immediately after `(x, y)` is not necessary in this case, but it is necessary in the case of the anonymous function above.

You can also get the same result with

``````julia> (t -> +(t...)).([(1, 2), (3, 4)])
2-element Vector{Int64}:
3
7
``````

Edit: A few minutes late; Julia’s people are too quick to answer! 2 Likes

It’s a consequence of function argument destructuring, combined with anonymous function syntax. Argument destructuring is documented in

https://docs.julialang.org/en/v1/manual/functions/#Argument-destructuring

5 Likes

Actually argument destructuring is not based on pattern matching, it’s based on iteration. So rather than just working for tuples it works for any iterable which is passed:

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

julia> f(Set([1,2]))
3

julia> f([1,2])
3

julia> f((1,2))
3

``````
4 Likes