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

前端 未结 3 882
轻奢々
轻奢々 2021-02-07 05:59

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

3条回答
  •  被撕碎了的回忆
    2021-02-07 06:09

    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.

提交回复
热议问题