I want to get all keys from a tuple list, but module Keyword requires the key should be atom, otherwise, it throw error.
Now I use a loop to solve it, and maybe it is not necessary if it already exists. Can it be simplified?
iex(4)> a = [{{1,0,0},1},{{1,0,1},2}]
[{{1, 0, 0}, 1}, {{1, 0, 1}, 2}]
iex(5)> Enum.map(a,fn {key,_} -> key end)
>Solution :
The method you have is perfectly fine and very common.
You could make it slightly briefer with elem/2 and using function capture syntax, but that’s just personal preference:
Enum.map(a, &elem(&1, 0))
You could also use a comprehension:
iex> for {key, _value} <- a, do: key
[{1, 0, 0}, {1, 0, 1}]
If you have nested data, get_in/2 might be useful, but it’s probably overkill in this case.
iex> get_in(a, [Access.all(), Access.elem(0)])
[{1, 0, 0}, {1, 0, 1}]