Lutosław
Lutosław

Reputation: 666

Why cannot do I get syntax errors when trying to define functions in Erlang?

I am try to learn Erlang. I've installed a runtime but cannot get it working. The following code:

X = 3.

works, but none of the following statements work:

 f(X)->X.
 F() ->0.
 F([])->[].

I get back 1: syntax error before: '->'. I tried the word_count from this tutorial. And I get the same error.

What is wrong here?

Upvotes: 1

Views: 204

Answers (2)

Vinod
Vinod

Reputation: 2243

There is difference in sytax when writing functions in Erlang module and Erlang shell (REPL). As P_A mentioned you need to call as F = fun(X) -> X end, F("Echo").

Also note that function names are atoms so has to start with lowercase when you are writing in Erlang module. If you are serious about learning Erlang I would suggest you go through this.

You mentioned that you worked on F#. The basic difference between F# and Erlang in this case is that expression let Lilo = [|5; 3; -3; 0; 0.5|];; Can be written directly in the file and executed. In Erlang it can only be done in Erlang shell and not inside a file. So the expression you are trying should be inside a function inside a module with the same name as file. Consider test.erl file. Any function you export can be called from outside (shell).

-module(test).    
-export([test/0]).    
test() ->
    Lilo = [5, 3, -3, 0, 0.5],
    [X*2 || X <-Lilo].

Upvotes: 1

P_A
P_A

Reputation: 1818

In REPL you have to use fun(...) -> ... end:

1> F = fun(X) -> X end.
#Fun<erl_eval.6.80484245>
2> F(42).
42

If you have code in file use c command:

1> c(word_count).
{ok,word_count}
2> word_count:word_count([]).
0

Upvotes: 1

Related Questions