Erlang getting error ** 1: syntax error before: '->' **

14,400

Solution 1

You can't define functions in the shell using the same syntax as in an erl file.

You can define fun's though.

Syntax in the shell needs to be:

Sum = fun([], _) -> 0; ([H | T], F) -> H + F(T, F) end,
Sum([1,2,3], Sum).

Note that recursive anonymous functions (which this is) are defined in an ugly way. You basically have to pass the function as an argument to itself.

Solution 2

The straight answer is that in a module definition file you have attributes, like -module()., -export(). etc, and function definitions, while in the shell you enter expressions to be evaluated. A function definition is not an expression.

If you want to define a local, temporary function in the shell you need to use fun's as @DanielLuna has shown. These are really anonymous unnamed functions so calling themselves recursively is a pain, which is not specific to Erlang but common to all anonymous functions.

N.B.

Sum = fun([], _) -> 0; ([H | T], F) -> H + F(T, F) end.

in shell does NOT define a function called Sum but defines an anonymous function and binds the variable Sum to it.

This is also why the only thing you can do in a module is define functions and not expressions to be evaluated when the module is loaded.

Solution 3

Or use the lists:foldl/2 function. This is copied directly from the Erlang Reference Manual.

1> lists:foldl(fun(X, Sum) -> X + Sum end, 0, [1,2,3,4,5]).
15
Share:
14,400

Related videos on Youtube

pranjal
Author by

pranjal

Creating asynchronous back-end system for GoIbibo.

Updated on July 17, 2020

Comments

  • pranjal
    pranjal over 3 years

    I have started some hands on in Erlang and I am getting : ** 1: syntax error before: '->' ** whenever i am declaring any function for eg. to calculate sum of a list (this is experimental, of cource there is Built In Function for find sum of a list).

    sum([]) -> 0;
    sum([H | T]) -> H + sum(T).
    

    in erl shell (v 5.5.5).

    Thanks in advance

  • Manoj Govindan
    Manoj Govindan about 13 years
    aka: want functions in shell? Have fun!
  • pranjal
    pranjal about 13 years
    Thanks, I got to the right way of declaring module and exporting functions.
  • margaretkru
    margaretkru about 3 years
    10 years later and this is still so difficult to find and understand why it doesn't work.

Related