April 2017

You are browsing the site archives for April 2017.

通过一个求和(0~N)程序来对比Erlang的递归和尾递归效率并加深对尾递归的理解。 递归 #! /usr/bin/env escript main([A]) -> N = list_to_integer(A), io:format(“sum 0 – ~w = ~w~n”,[N, sum(N)]). sum(1) -> 1; sum(N) -> N + sum(N-1). 尾递归 #! /usr/bin/env escript main([A]) -> N = list_to_integer(A), io:format(“sum 0 – ~w = ~w~n”,[N, sum(N)]). sum(N) -> sum(N, 0). sum(0, N) -> N; sum(M, N) -> sum(M-1, N+M). 对比 …

Continue reading Erlang的递归

生成斐波那契数列 #! /usr/bin/env escript main([A]) -> I=list_to_integer(A), F=fac_list(I), io:format(“feribo ~w = ~w~n”,[I,F]). element(1) -> 1; element(2) -> 1; element(N) -> element(N-1) + element(N-2). fac_list(N) -> fac_list([], N). fac_list(L, 0) -> L; fac_list(L, N) -> fac_list([element(N)|L], N-1). 运行结果 dingkaideMacBook-Pro:erlang dingkai$ ./feibo 25 feribo 25 = [1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368,75025] 求平均数 #! /usr/bin/env escript %main([L]) -> main([]) -> L = …

Continue reading Erlang入门: 几个简单小程序