Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

is there function for get all keys from tuple list when key is not atom?

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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}]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading