以下是一个简单的Erlang入门程序示例,包含基础语法和运行说明:
1. Hello World 程序
erlang
-module(hello). % 模块声明(必须与文件名相同)
-export([start/0]). % 导出函数
start() ->
io:format(, Erlang World!~n % ~n 表示换行
2. 编译运行步骤
1. 保存为 `hello.erl`
2. 编译:
bash
erlc hello.erl # 生成 hello.beam
3. 运行:
bash
erl -noshell -s hello start -s init stop
输出结果:`Hello, Erlang World!`
3. 带参数的函数
erlang
-module(greet).
-export([say/1]). % 导出带1个参数的函数
say(Name) ->
io:format(, ~s!~nName]). % ~s 格式化字符串
运行示例:
erlang
1> greet:say(, Alice!
4. 进程通信示例
erlang
-module(process_demo).
-export([run/0]).
run() ->
Pid = spawn(fun() -> receiver() end), % 创建进程
Pid ! {self(), Hello Process % 发送消息
receive
Response -> io:format(Received: ~p~nResponse])
end.
receiver() ->
receive
{From, Msg} ->
io:format(Process got: ~s~n [Msg]),
From ! % 回复消息
end.
关键语法说明
1. 变量:首字母大写(如 `X`, `Result`)
2. 函数:`函数名(参数) -> ... end`
3. 模式匹配:`=` 不是赋值而是模式匹配
4. 进程通信:`!` 发送消息,`receive` 接收消息
5. 原子:小写字母开头(如 `ok`, `error`)
建议从Erlang交互环境学习:
bash
erl # 启动交互环境
1> c(hello). % 编译模块
2> hello:start(). % 执行函数
3656

被折叠的 条评论
为什么被折叠?



