Reputation: 177
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].
Upvotes: 5
Views: 19025
Reputation: 313
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.
Upvotes: 1
Reputation: 30985
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]
.
Upvotes: 9