Reputation: 75
Given the module
-module(p1).
-export([f2/2]).
f2([A, A | B]) -> {A, B};
f2([A, B | _]) -> {A, B};
f2([A]) -> A;
f2(_) -> no_match.
I was asked to try the input value
p1:f2([1,1,[1,1]]).
My answer would be that this input value matches the first function clause of f2, and as such gives us the result:
{1,[1,1]}
But according to the given answer sheet, the answer is
{1,[[1,1]]}
I can't quite get my head around why we get a list within a list, rather than a list in the answer. Would appreciate an explanation for this, thank you.
Upvotes: 0
Views: 74
Reputation: 3584
You should look into how head-tail works in Erlang. Tail is always a list; could be a one element list, could be an empty list, but always a list.
Lets look into example in shell:
2> Fun = fun([H | T]) -> {H, T} end.
#Fun<erl_eval.6.90072148>
3> Fun([a]).
{a,[]}
4> Fun([a,b]).
{a,[b]}
5> Fun([a,[a,b]]).
{a,[[a,b]]}
6> Fun([a,b,c]).
{a,[b,c]}
7> Fun([a,b,c,d]).
{a,[b,c,d]}
So in you case what you are returning is A
which is repeted 1
and B
which is list of all remaining elements. In our case only one element remains, so we return one-element list. And this element is a two-element list, hence list in a list [[1, 1]]
.
Upvotes: 2