为什么我在Erlang中定义函数时不能得到语法错误?

cetgtptt  于 2022-12-08  发布在  Erlang
关注(0)|答案(2)|浏览(161)

我正在尝试学习Erlang。我安装了一个运行时,但不能让它工作。下面的代码:

X = 3.

可以运作,但下列陈述式都无法运作:

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

我返回了1: syntax error before: '->'。我尝试了从这个tutorial返回word_count。我得到了同样的错误。
这是怎么了?

ifmq2ha2

ifmq2ha21#

在REPL中,必须使用fun(...) -> ... end

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

如果文件中有代码,请使用c命令:

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

8fq7wneg2#

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].

相关问题