erlang(初级)

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

介绍和安装,请自己baidu

语法说明:
[b]Shell/语句:[/b]以.结束,不是其它语言一般的;结束
[b]module/function[/b]:用任何文本编辑器编辑,如:(文件保存名tut.erl)
-module(tut).
-export([double/1]).
-export([fac/1, mult/2]). %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).
[b]Atoms[/b]:普通变量以大写字母开头,原子以小写字母开头。原子只是一个名称,没有任何值。作用之一就是作为function的简称或者说组成部分。hello(X, china) ,调用应该是module_name:hello(x, china).
如果执行出现错误,可以用function v/1. 例如v(9).其中9表示出错的shell的number。
[b]Tuples[/b]:以{}区分。和其它语言的array一样。尤其是php和perl的。几乎一样。例如:{moscow, {c, -10}} element 1 就是moscow, element 2 就是{c, -10}
[b]Lists[/b]: [] 例如:[{moscow, {c, -10}}, {cape_town, {f, 70}},{stockholm,{c, -4}},{paris, {f, 28}}, {london, {f, 36}}]
list可以用"|"来分割。例如:[First |TheRest] = [1,2,3,4,5].那么First就是1, TheRest就是[2,3,4,5]
[E1, E2 | R] = [1,2,3,4,5,6,7]. E1是1, E2是2, R就是剩下的全部了
[b]String[/b]:erlang中没有string,用list来代替,list内容是字符的ascii.例如:list[97,98,99]表示"abc"。 所以在Shell中输入[97,98,99]. 得到"abc"
StandardModules:
io:
31>io:format("hello world~n", []).
hello world
ok
32> io:format("this outputs one Erlang term: ~w~n", [hello]).
this outputs one Erlang term: hello
ok
33> io:format("this outputs two Erlang terms: ~w~w~n", [hello, world]).
this outputs two Erlang terms: helloworld
ok
34> io:format("this outputs two Erlang terms: ~w ~w~n", [hello, world]).
this outputs two Erlang terms: hello world
ok

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

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

[b]Scope中的变量[/b]:同一个Scope中的变量是不可变的,这个其它一些语言(clojure等)类似。
[b]赋值[/b]:老规矩,=号。例如:
M = 5.
{X, Y} = {paris, {f, 28}}.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值