Search code examples
erlangerl

Erlang exception error for no match of right hand side value


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.


Solution

  • 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).