Erlang程序设计(第2版)源代码和课后练习答案(第一章-第四章)
github地址ch02-Erlang速览Hello Wrold$ erlEshell V12.0.3(abort with ^G)1> c(hello). # 编译{ok,hello}2> hello:start().Hello worldok$ erlc hello.erl$ erl -noshell -s hello start -s init stopHello world文件
·
ch02-Erlang速览
Hello Wrold
$ erl
Eshell V12.0.3 (abort with ^G)
1> c(hello). # 编译
{ok,hello}
2> hello:start().
Hello world
ok
$ erlc hello.erl
$ erl -noshell -s hello start -s init stop
Hello world
文件服务进程
Eshell V12.0.3 (abort with ^G)
1> c(afile_server).
{ok,afile_server}
2> FileServer = afile_server:start(".").
<0.86.0>
3> FileServer ! {self(), list_dir}.
{<0.79.0>,list_dir}
4> receive X -> X end.
{<0.86.0>,
{ok,["hello.erl","README.md","afile_server.beam",
"hello.beam","afile_server.erl"]}}
Eshell V12.0.3 (abort with ^G)
1> c(afile_server).
{ok,afile_server}
2> c(afile_client).
{ok,afile_client}
3> FileServer = afile_server:start(".").
<0.91.0>
4> afile_client:get_file(FileServer, "missing").
{error,enoent}
5> afile_client:get_file(FileServer, "afile_server.erl").
{ok,<<"-module(afile_server).\n-export([start/1, loop/1]).\n\nstart(Dir) -> spawn(afile_server, loop, [Dir]).\n\nloop(Di"...>>}
ch03-基本概念
- 变量只能赋值一次
- = 是一个模式匹配操作符
- 变量不可变
- 原子是全局性的
- 没有类型声明
- 元组会在声明时自动创建,不再使用时则被销毁
- 列表里的元素可以是任意类型
ch04-模块与函数
-
当函数包含多个不同的子句,会用第一个与调用参数相匹配的子句开始执行
-
逗号分隔函数调用、数据构造和模式中的参数
-
分号分隔子句,如函数定义,以及case、if、try…catch和receive表达式
-
句号分隔函数整体,以及shell里的表达式
练习
(1)
area({triangle, Length, Width}) -> Length * Width / 2;
area({circle, Radius}) -> 3.14 * Radius * Radius;
area({rectangle, Width, Height}) -> Width * Height;
area({square, Side}) -> Side * Side.
(2)
- 思路是获取tuple的长度,然后从最后面开始构造list
my_tuple_to_list(T) ->
my_tuple_to_list(T, tuple_size(T), []).
my_tuple_to_list(T, Size, L) when Size =:= 0 ->
L;
my_tuple_to_list(T, Size, L) ->
my_tuple_to_list(T, Size-1, [element(Size, T)|L]).
(3)
my_time_func(F) ->
{Hour1, Minute1, Second1} = erlang:time(),
F,
{Hour2, Minute2, Second2} = erlang:time(),
io:format(“runtime:fn”, [((Hour2-Hour1)/3600+(Minute2-Minute1)/60+(Second2-Second1))/1000]).
my_date_string() ->
{Year, Month, Day} = erlang:date(),
{Hour, Minute, Second} = erlang:time(),
io:format(“p年p月p日p时p分p秒~n”, [Year, Month, Day, Hour, Minute, Second]).
(5)
-module(math_functions).
-export([even/1, odd/1]).
even(X) ->
(X rem 2) =:= 0.
odd(X) ->
(X rem 2) =:= 1.
(6)
filter(F, L) ->
[X || X <- L, F(X) =:= true].
测试:
math_functions:filter(fun(X) -> math_functions:even(X) end, [1, 2, 3, 4, 5]).
(7)
split(L) ->
{filter(fun(X) -> even(X) end, L), filter(fun(X) -> odd(X) end, L)}.
测试:
40> math_functions:split([1,2,3,4,5,4]).
{[2,4,4],[1,3,5]}
更多推荐
所有评论(0)