Erlang语言学习入门
学习资料:
- 官方Doc:http://www.erlang.org/doc.html
- 写的特别详细: http://www.cnblogs.com/zhengsyao/ (强推,写得很详细)
- 系统技术研究:http://blog.yufeng.info/
- 庄周梦蝶erlang板块:http://www.blogjava.net/killme2008/category/20770.html
- 博客园的一位大牛:http://www.cnblogs.com/lulu/category/559387.html
- 另外一位:http://wqtn22.iteye.com
Erlang语言简单示例
1. hello,world
创建文件hello.erl,编辑如下:
-module(hello). -export([start/0]). start()-> io:format("hello world~n").
在终端输入erl,进入erlang命令行,运行c(hello),即可调用程序
2. 多个参数情况
参考官网,创建tut2.erl,编辑如下:
-module(tut2). -export([convert/2]). convert(M,inch) -> M/2.54; convert(N,centimenter) -> N*2.54.
3. 调用多个函数
创建tut5.erl,编辑如下:
-module(tut5). % -exoport([format_temps/1]). -export([format_temps/1]). format_temps([]) -> ok; format_temps([City | Rest]) -> print_temp(convert_to_celsius(City)), format_temps(Rest). convert_to_celsius({Name,{c,Temp}}) -> {Name,{c,Temp}}; convert_to_celsius({Name,{f,Temp}}) -> {Name,{c,(Temp -5)*5/9}}. print_temp({Name,{c,Temp}}) -> io:format("~-15w ~w c~n",[Name,Temp]).
运行结果如下:
4. map和func的运用
利用func,并基于内建函数进行排序,编辑如下:
-module(tut13). -export([convert_list_to_c/1]). convert_to_c({Name,{f,Temp}}) -> {Name,{c,trunc((Temp-32)*5)}}; convert_to_c({Name,{c,Temp}}) -> {Name,{c,Temp}}. convert_list_to_c(List) -> New_List = lists:map(fun convert_to_c/1,List), lists:sort(fun({_,{c,Temp1}},{_,{c,Temp2}}) -> Temp1 < Temp2 end,New_List).
6. spawn的简单实用
调用spawn运用erlang的并发,编辑如下:
参考:
- http://www.erlang.org/course/concurrent_programming.html#top
- http://www.erlang.org/doc/getting_started/conc_prog.html#id67324
- http://www.blogjava.net/killme2008/archive/2007/06/14/124355.html
-module(tut14).
-export([start/0,say_something/2]).
say_something(What,0) ->
done;
say_something(What,Times) ->
io:format("~p~n",[What]),
say_something(What,Times - 1).
start() ->
spawn(tut14,say_something,[hello,3]),
spawn(tut14,say_something,[goodbye,5])
7.erlang的消息通信,基于!
-module(tut15).
-export([start/0,ping/2,pong/0]).
ping(0,Pong_Pid) ->
Pong_Pid ! finished,
io:format("ping finished~n",[]);
ping(N,Pong_Pid) ->
Pong_Pid!{ping,self()},
receive
pong ->
io:format("Ping recieved pong!~n",[])
end,
ping(N-1,Pong_Pid).
pong() ->
receive
finished ->
io:format("Pong finished!~n",[]);
{ping,Ping_Pid} ->
io:format("Pong recieved ping!~n",[]),
Ping_Pid ! pong,
pong()
end.
start() ->
Pong_Pid = spawn(tut15,pong,[]),
spawn(tut15,ping,[3,Pong_Pid]).
未完,待续!