erlang学习笔记(2)

函数
%###geometry.erl###
-module(geometry).

定义
-export([area/1, function1/2, function2/0, ...]).
area({rectangle, Width, Height}) -> Width * Height;
area({square, X}) -> X * X;
area({circle, R}) -> 3.1415926 * R * R.

编译
c(geometry).

调用
geometry:area({rectangle, 10, 5}).

%??? chapter 3.3

匿名函数fun(X)
Double = fun(X) ->  2 * X end.
Double(2).
%Double(X) == ( fun(X) == 2 * X )
Even = fun(X) -> (X rem 2) =:= 0 end.
Even(5).

Hypot = fun(X, Y) -> math:sqrt(X * X + Y * Y) end.
Hypot(3, 4).

TempConvert = fun({centigrade, TempC}) -> {fahrenheit, 32 + TempC*9/5};
                 ({fahrenheit, TempF}) -> {centigrade, (TempF - 32)*5/9}
              end.

fun()为参数
L = [1,2,3,4].
lists:map(Double, L).
lists:filter(Even, L).

返回fun的函数
%???chapter 3.4.2

For循环
for(Max, Max, F) -> [F(Max)];
for(I, Max, F)   -> [F(I) | for(I+1, Max, F)].

列表解析
lists:map(fun(X) -> 2 * X end, L).
[2 * X || X <- L].

[What || {What, Num} <- L].
[{What, Num - 1} || {What, Num} <- L].

上一篇:构建NetCore应用框架之实战篇系列


下一篇:大话设计模式C++版——简单工厂模式