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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With