Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting tuple to list using shorthand notation anonymous function

Tags:

elixir

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
like image 312
Bala Avatar asked Aug 13 '16 19:08

Bala


1 Answers

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.

like image 128
NoDisplayName Avatar answered Sep 26 '22 00:09

NoDisplayName