[erlang-questions] ++ to select the head ( instead of just the tail )

Mark Wagner carnildo@REDACTED
Wed Aug 17 21:39:50 CEST 2011

On Tue, Aug 16, 2011 at 04:23, James Churchman <jameschurchman@REDACTED> wrote:
> The ++ operator is not just a righthand side operator, but can in fact be a lefthand side operator in as far as I can tell just 1 case :
> When you know the head you wish to remove and getting the tail :
> Eg in the shell:
> FullList = "123456".
> "123" ++ Tail = FullList.
> Tail wil now be "456"
> However using it to get the head is not supported :
> FullList = "123456".
> Head ++  "456" = FullList.
> gives : * 1: illegal pattern
> Understandably this second type involves traversing the entire list, where the first does not, but it would still be a nice addition to erlang.
> Was this not added as the first one expands out to simply [$1,$2,$3 | Tail] etc... but the second needs to expand to something more complex like an actual function the way list comprehensions do?

My understanding is that Erlang lists are single-linked lists.  This
means that finding the front element (and by extension, a fixed number
of elements at the front of the list) is an easy operation that runs
in constant time.  Finding the tail element is easy and slow (traverse
the list until you hit the end), but there's no good way to find "the
element before the tail element".  An iterative solution requires
traversing the list again; a recursive solution would require
processing after the recursion step, meaning it can't be
tail-recursive and will require space proportionate to the size of the
list (picture running 'Head ++ "The End"' on a million-byte novel).

Mark Wagner

More information about the erlang-questions mailing list