Converting Tuple to List Using Shorthand Notation Anonymous Function

Working through Dave's (PragProg) Elixir book. Challenge is to convert pair of tuples to list.

This works

pair = fn {a,b} -> [a,b] end
pair.({1,2}) #=> [1,2]

Now I tried using shorthand notation (I felt something is missing but don't know what it is...for e.g. how do I say I am expecting/sending a tuple)

How can I achieve the same results using shorthand notation?

pair = &([&1,&2]) 
pair.({1,2}) #=> BadArityError 

Tried this

pair = &{[&1,&2]} # but didn't work. I am missing something important

1 Answer

It does not work because the {a, b} is one argument, so it gets passed as &1, there is no &2.

One way to do it that I can think of is to use Tuple.to_list/1 function so it would be like this:

pair = &Tuple.to_list/1
pair.({1,2}) #=> [1,2]

but if this is not what you want, then you could use something like this:

pair = &([elem(&1, 0), elem(&1, 1)])
pair.({1,2}) #=> [1,2]

but this is a simple example that works only with 2 elements tuples but it will let you understand what you are doing wrong.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest