Is there something in Julia similar to the as-patterns in Haskell?

Hello,
In Haskell we can write an argument of a function as pair@(x,y). That means that pair is the pair with the two elements x and y. Is there something similar in Julia? For example if I have a list of pairs, I would like to do

map(pair@(x,y) -> x+y, my_list_of_pairs)
1 Like

Is this what you mean?

julia> my_list_of_pairs = [1=>2, 3=>4, 5=>6]
3-element Vector{Pair{Int64, Int64}}:
 1 => 2
 3 => 4
 5 => 6

julia> map(((x,y),) -> x+y, my_list_of_pairs)
3-element Vector{Int64}:
  3
  7
 11
2 Likes

Thanks. No, by “pair” I mean a 2-tuple, e.g. [(1,2), (3,4), (5,6)].

That same code will still work.

Ah yes it works, thanks. Why this notation ((x,y),)?

A single argument function would be: (p,) -> p[1]+p[2]. If we then replace p by (x,y) that means x, y = p, i.e. it iterates over the input argument and assigns to x and y.

It is also possible to extract elements from a struct with a similar syntax. For example:

julia> my_list_of_numbers = [1+2im, 3+4im, 5+6im]
3-element Vector{Complex{Int64}}:
 1 + 2im
 3 + 4im
 5 + 6im

julia> map(((;re, im),) -> re+im, my_list_of_numbers)
3-element Vector{Int64}:
  3
  7
 11

The above works because Complex has the field names re and im.

2 Likes

Nice. And in the same spirit, can we do something like [x+y for pair@(x,y) in list_of_pairs]?

Sure. Just get rid of the pair@.

julia> [x+y for (x,y) in my_list_of_pairs]
3-element Vector{Int64}:
  3
  7
 11
2 Likes

This general concept is known as “destructuring”. See here: Functions · The Julia Language.

You seem happy with the solution, but I was wondering if there is some miscommunication going on. Specifically, do you really want or need as patterns? Your example doesn’t actually use pair in the function, so it seems like an example of a case where the as pattern isn’t needed and isn’t used. As opposed to some other non-Julia/non-Haskell snippet like:

map(pair@(x,y) -> x+pair[2], my_list_of_pairs)

where you would be using the binding to pair established by the as pattern. I don’t think there is anything like an as pattern in Julia or provided in any package I know of. However MLStyle.jl is definitely worth checking out for fancy pattern matching.

Indeed, in Haskell you can use pair as well.