Search code examples
erlangerlang-shell

Erlang code not compiling?


this is code directly from my professor.

-module(m) .
-export([ abc/1 , n/1] ) .

abc(X) ->
Y = spawn_link(m , n , [ self()]) ,
Y ! X ,
receive
Z -> Z 
end .

n(X,X) −> [X] ;
n(X,Y) −> [Y| n(X,Y+Y) ] .
n(Z) −> receive N −> Z ! n(N∗N,N)
end .

is not compiling , this is the error message im getting

m.erl:11: illegal character   
m.erl:12: illegal character   
m.erl:12: syntax error before: '>'   
m.erl:13: illegal character    
m.erl:13: illegal character    
m.erl:13: illegal character    
m.erl:13: syntax error before:N   
m.erl:2: function n/1 undefined     

Solution

  • There are a few things going on:

    • the dash character you're using isn't getting parsed - (so on your line 11 and others there is some non-ascii character that isn't getting parsed)
    • there is no space between Z and the end call, so the first receive block never terminates (and Erlang thinks there is an unbound variable called Zend.

    I cleaned up the code below and it compiles for me. I'd look at your indentation and spacing and maybe try to be more idiomatic with it.

    -module(m).
    -export([ abc/1, n/1]).
    abc(X) ->
            Y = spawn_link(m , n , [ self()]) ,
            Y ! X,
        receive
            Z -> Z
        end.
    
    n(X,X) -> 
        [X];
    n(X,Y) -> 
        [Y|n(X,Y+Y) ].
    n(Z) -> 
        receive 
            N -> Z ! n(N*N,N) 
        end.