[erlang-questions] Lists in recursion

Jesper Louis Andersen jesper.louis.andersen@REDACTED
Fri Mar 27 14:00:25 CET 2015

On Fri, Mar 27, 2015 at 1:42 PM, harsha sri <harsha.pic@REDACTED> wrote:

> Is it possible to add dynamically add elements to List in recursion?

There is some indication, you may want to spend time with a good book on
Erlang. For instance learnyousomeerlang.com or perhaps Joe Armstrong's book
on Erlang. I'm not entirely sure what you want to do, but I can explain to
you what happens in the system for the lines below.

> ex: List = [1,2,3]
This will create a list [1,2,3] and bind that list to the name List.

> lists:foreach...
calling, for instance, lists:foreach(fun(Item) -> io:format("~B~n", [Item])
end, List) will not be able to change List. 'foreach/2' is executed for its
side-effect only, in this case printing elements. You can use a map/2:
List2 = lists:map(fun(Item) -> Item + 3 end, List), but this will

* Add three to each element of the list and bind the result to List2, i.e.,
List2 = [4,5,6]
* Not be able to add or remove elements from L
* Not change L in any way. The language uses persistent data structures,
not ephemeral data structures.

> .....
> List = [4 | List]

The expression [4 | List] evaluates to [4,1,2,3] because it prepends
(cons'es) 4 in front of the list. If you write

List = [4 | List]

then the Erlang semantics are:

* build up the list [4 | List] --> [4,1,2,3]
* Since 'List' is already bound, assert that the current contents of the
list is [4,1,2,3]. But List is already bound to [1,2,3], so the assertion
is failing.
* Crash the program with a badmatch error since the assertion is a failure

Finally i am expecting in List: [1,2,3,4]

One way to solve this is to append two lists: List ++ [4]. This will build
the single-element list [4] and then append it as a new suffix. If you want
to give it a name, it has to be one that hasn't been used already in the
scope, e.g.,

NewList = List ++ [4].

For small lists, this is a viable strategy. For large lists, append can end
up being costly in execution speed, but I'd focus on solving problems first
and then worrying about performance later. Especially when you are trying
to learn what is going on in the first place.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20150327/ac61f164/attachment.htm>

More information about the erlang-questions mailing list