[erlang-questions] concentate solution well ??
Richard A. O'Keefe
Mon Feb 2 03:25:27 CET 2015
On 2/02/2015, at 6:27 am, Roelof Wobben <r.wobben@REDACTED> wrote:
> This solution better ?
> concatenate() ->
> concatenate([List] ) ->
> concatenate2(List1, ).
> concatenate2(, List) ->
> concatenate2([Head| Tail], List) ->
> concatenate2(Tail, [Head | List])
No., To be honest, it is a b----y bad solution.
WHERE ARE THE [UNPRINTABLE] COMMENTS?
Because of this thread, I know what concatenate/2
is supposed to do, BUT YOU HAVE NOT TOLD US WHAT
concatenat2/2 IS SUPPOSED TO DO.
In fact concatenate2/2 appears to be reversal,
which is something you definitely do NOT want.
What you have here is
> concatenate([[a,b,c], [1,2,3]]).
The basic scheme for processing lists by recursion is
g([H|T], Context) ->
f(H, g(T, Context), Context);
g(, Context) ->
where g is the function we are trying to define
e is what to do for an empty list
f is what to do for a non-empty list
GIVEN the result of a recursive call on the tail.
e() and f(_,_) do not have to be literal function
calls; they could be any expression.
So we are looking for
You know what concatenate() is, so we're looking for
Now H : list(X)
concatenate (list(list(X)) -> list(X))
so concatenate(T) : list(X)
and you need to find an expression f(A, B)
such that when A and B are lists, so is f(A, B),
and the result has all the elements of A followed
by all the elements of B.
If you really do want a helper function (and there is
a built-in operator that does *precisely* what you
need), start by writing the comment:
% concatenate_helper(A : list(X), B : list(X)) -> R : list(X)
% R is a list containing all the elements of A followed by
% all the elements of B and nothing else.
By this point in the book, if you haven't heard of the built-in
operator that does this, you have probably written your own
function for it already.
More information about the erlang-questions