Erlang exception error for no match of right hand side value
Asked Answered
D

1

6

I have this code that is supposed to print the numbers 1 to N-1 in a list, but I in here won't append to the list.

enum(N,[],N) -> [];
enum(N,L,I) ->
  io:format("current number: ~w~n", [I]),
  L = L ++ I,
enum(N,[],I+1).

enumFunc(N) -> enum(N,[],1).

When I run sample:enumFunc(100)., it returns exception error: no match of right hand side value [1]

Please help me solve this. Thanks.

Dwarf answered 23/9, 2018 at 16:34 Comment(0)
C
7

Erlang is a single assignment language. This means that you cannot assign a new value to L if a value has already been assigned to L. When you try to 'assign' a new value via L = L ++ I you are actually preforming a matching operation. The reason you are seeing the no match of right hand side value [1] error is because L does not equal L ++ I because L is already assigned the value of [1] and does not match [1,2]

enum(N,L,N) -> L;
enum(N,L,I) ->
  io:format("current number: ~w~n", [I]),
  L0 = L ++ [I],
  enum(N,L0,I+1).

enumFunc(N) -> enum(N,[],1).
Croatian answered 23/9, 2018 at 16:54 Comment(5)
It returned a Warning: the result of the expression is ignored.Dwarf
Try changing _L1 = L ++ I to _ = L ++ I.Croatian
There are no more errors, but it still doesn't append anything to the list.Dwarf
I've edited my post to show how you can append to the list.Croatian
Worked like a charm. Thanks a lot!Dwarf

© 2022 - 2024 — McMap. All rights reserved.