In Elixir, is there a shorthand way to access tuple items inside shorthand anonymous function notation?

Viewed 371

The most common scenario I encounter this with is with Maps. Here is the full anonymous notation:

Enum.sort(some_map, fn {k1,_v1}, {k2,_v2} -> k1 <= k2 end)

Here is shorthand:

Enum.sort(some_map, &( elem(&1,0) <= elem(&2,0) ))

Scala has this nice nifty notation for tuple items by index. Does Elixir have something similar or are we stuck using Kernel.elem/2 ?

3 Answers

The options have for accessing tuples are Kernel.elem/2, Access.elem/2 and pattern matching. However, the Enum.sort_by/3 function does the job less verbosely than Enum.sort/2.

Enum.sort_by(map, &elem(&1, 1))                # Kernel.elem/2
Enum.sort_by(map, fn {key, _value} -> key end) # pattern matcing

And in case you don't mind the map values, that can be even shorter.

map |> Map.keys() |> Enum.sort()

Is there a shorthand way to access tuple items inside shorthand anonymous function notation?

No.

Are we stuck using Kernel.elem/2 ?

Yes.

Here is the solution I am currently using: Implement an operator.

def tuple ~> index, do: elem(tuple, index)

Then you can easily access with x~>n and make super compact code like this:

data = [{["root", "dir1"], 100}, {["root", "dir2"], 200}]
data |> Enum.map(& {Enum.join(&1~>0, "."), &1~>1}) |> Map.new
Related