Alex Rivera | Logout

How to change an element in a list in erlang

Asked 2011-01-23T19:45:22.027
12

I have a list which I have used the function lists:nth() on to return the value of an element at a certain index. Does anyone know how I can edit this value?

EDIT: Here is a bit more information.

Say I had a list L which represents a line of a text based grid

L = [H,H,H,H,H].

And I want to access a specified element say for example the third one and change it to E. Then if I was to use the list L again it would be

[H,H,E,H,H]

I hope this makes more sense.

Thank you.

Edit
Report

1 Answer

19

A list is immutable, so you can't "change" an item in a list. If you really want to replace an item at a given position, you should append the list before the element with the (changed) element and the remaining list:

1> L=[1,2,3,4,5].
[1,2,3,4,5]
2> lists:sublist(L,2) ++ [lists:nth(3,L)*100] ++ lists:nthtail(3,L).
[1,2,300,4,5]

EDIT: The scenario is a bit unusual, though... Do you have a specific problem at hand? Perhaps it can be expressed better with e.g. a lists:map?

answered 2011-01-23T19:58:07.023

Your Answer