ITeye博客

erlang(初级)

zb_86 · 2009-12-22 12:26 · erlang · 编程语言 · C · C++ · REST · C# · Erlang · Markdown

早就听过erlang,但是今天才有时间开始动手,内心一阵惭愧啊。

介绍和安装,请自己baidu

语法说明: **Shell/语句:**以.结束,不是其它语言一般的;结束 module/function:用任何文本编辑器编辑,如:(文件保存名tut.erl) -module(tut). -export(). -export(). %1表示1个参数,2表示2个参数

double(X) -> 2 * X.

fac(1) -> 1; %;表示该方法未结束,或者说只结束一部分 fac(N) -> N * fac(N - 1).

mult(X, Y) -> X * Y.

在文件保存的目录运行erlang,编译:c(module_name),上例就是c(tut)。返回{ok,module_name}表示成功。然后就可以直接调用module中的function。上例:tut:double(10). Atoms:普通变量以大写字母开头,原子以小写字母开头。原子只是一个名称,没有任何值。作用之一就是作为function的简称或者说组成部分。hello(X, china) ,调用应该是module_name:hello(x, china). 如果执行出现错误,可以用function v/1. 例如v(9).其中9表示出错的shell的number。 Tuples:以{}区分。和其它语言的array一样。尤其是php和perl的。几乎一样。例如:{moscow, {c, -10}} element 1 就是moscow, element 2 就是{c, -10} Lists: 例如: list可以用"|"来分割。例如: = .那么First就是1, TheRest就是 = . E1是1, E2是2, R就是剩下的全部了 String:erlang中没有string,用list来代替,list内容是字符的ascii.例如:list表示"abc"。 所以在Shell中输入. 得到"abc" StandardModules: io: 31>io:format("hello world~n", ). hello world ok 32> io:format("this outputs one Erlang term: ~w~n", ). this outputs one Erlang term: hello ok 33> io:format("this outputs two Erlang terms: ~w~w~n", ). this outputs two Erlang terms: helloworld ok 34> io:format("this outputs two Erlang terms: ~w ~w~n", ). this outputs two Erlang terms: hello world ok

guard:看例子(得到List里面最大数): -module(tut). -export(). list_max() -> list_max(Rest, Head). list_max(, Res) -> Res; list_max(, Result_so_far) when Head > Result_so_far -> % when是一个关键字,说明当条件成立时走这个方法。 这种带有条件的称为guard list_max(Rest, Head);
list_max(, Result_so_far) -> list_max(Rest, Result_so_far).

guard的操作符:< less than, > greater than, == equal, >= greater or equal, =< less or equal, /= not equal

Scope中的变量:同一个Scope中的变量是不可变的,这个其它一些语言(clojure等)类似。 赋值:老规矩,=号。例如: M = 5. {X, Y} = {paris, {f, 28}}.

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。