Reputation: 63
I'm new to Elixir and I'm trying to create a simple anonymous function that concatenates two lists of atoms.
Correctly, the code written is:
concat = fn(x,y) -> x ++ y end
This code works for other data types as well.
My question is, how come the following code doesn't work?
list_concat = fn([:a,:b],[:c,:d]) -> [:a,:b,:c,:d] end
Iex doesn't throw when I write in the function, but if I try to run list_concat
, the following is thrown:
> list_concat.([:true,:false],[:false,:true])
** (FunctionClauseError) no function clause matching in :erl_eval."-inside
an-interpreted-fun-"/2
The following arguments were given to :erl_eval."-inside-an-interpreted-fun-
"/2:
# 1
[true, false]
# 2
[false, true]
Can someone help me figure out what the stack trace means, and why list_concat
isn't a correct solution? Is it something to do with pattern matching? Thanks!
Upvotes: 4
Views: 764
Reputation: 222188
An atom only matches itself. You can only call your list_concat
function with [:a,:b]
and [:c,:d]
as arguments. If you want to bind the variables to any value the user passes, just remove the :
:
iex(1)> list_concat = fn [a, b], [c, d] -> [a, b, c, d] end
#Function<12.99386804/2 in :erl_eval.expr/5>
iex(2)> list_concat.([:true, :false], [:false, :true])
[true, false, false, true]
PS: you don't need to put :
before boolean values. :true
is the same as true
.
Upvotes: 3