Search code examples
listerlangelementedit

How to change an element in a list in erlang


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.


Solution

  • 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?