Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add element to existing list without creating new variable in erlang?

I have a list contains some elements and now with the help of lists:foreach I am fetching some more records and I want to append each value to my existing list elements without creating new variable as doing in other languages with help of array.

Here is my sample code which I am getting:

exception error: no match of right hand side value [6,7,1].

Sample Code:

listappend() ->
    A = [1,2,3,4,5],
    B = [6,7],
    lists:foreach(fun (ListA) ->
        B = lists:append(B, [ListA])                       
        end, A),
    B.

I want output like,

B = [6,7,1,2,3,4,5].
like image 583
Ajay V Avatar asked Apr 16 '12 06:04

Ajay V


2 Answers

First of all, this feature already exists, so you won't need to implement it yourself. In fact, the list can take two lists as arguments:

1> lists:append([1,2,3,4,5], [6,7]).
[1,2,3,4,5,6,7]

Which is actually implemented as:

2> [1,2,3,4,5] ++ [6,7]. 
[1,2,3,4,5,6,7]

Please bear in mind that the ++ operator will copy the left operand, so this operation can easily lead to quadratic complexity. Said that, you probably want to construct your lists using the "cons" operator (eventually reversing the list at the end of the computation):

3> [1|[2,3,4,5,6,7]].
[1,2,3,4,5,6,7]

In any case, you can have two arguments in your function, which are the two lists to append, instead of defining them in the body of the function. This way, the values of A and B will change every time you call the my_append/2 function.

my_append(A, B) ->
  YOUR_CODE_GOES_HERE

As a note and regarding the actual error you're getting, this is due to the following line:

B = lists:append(B, [ListA])

During each iteration, you're binding a new value to the variable B, which is already bound to the value [6,7].

like image 87
Roberto Aloi Avatar answered Sep 29 '22 07:09

Roberto Aloi


Variables in Erlang are immutable. That means you cannot assign a new value to a variable once it has been bound, and this is why you get the 'no match' error. The old value does simply not match the new value you are trying to assign to the variable. Instead, you can create a new list using e.g lists:append based on the old one. You should probably start by looking at recursion and how you can use it to manipulate lists.

like image 41
Nils Avatar answered Sep 29 '22 06:09

Nils