Recursion

  • Fac

    fac(0) -> 1; fac(N) when N > 0 -> N*fac(N-1).

    tail_fac(N) -> tail_fac(N, 1). tail_fac(0, Fac) -> Fac; tail_fac(N, Fac) when N>0 -> tail_fac(N-1, N*Fac).

  • Len len([]) -> 0; len([_|T]) -> 1 + len(T).

    tail_len(L) -> tail_len(L,0). tail_len([], Acc) -> Acc; tail_len([_|T], Acc) -> tail_len(T,Acc+1).

Higher Order Functions

pass functions from outside a module

fun Module:Function/Arity

map(_, []) -> [];
map(F, [H|T]) -> [F(H)|map(F,T)].
incr(X) -> X + 1.
decr(X) -> X - 1.

1> c(hhfuns).
{ok, hhfuns}
2> L = [1,2,3,4,5].
[1,2,3,4,5]
3> hhfuns:increment(L).
[2,3,4,5,6]
4> hhfuns:decrement(L).
[0,1,2,3,4]
5> hhfuns:map(fun hhfuns:incr/1, L).
[2,3,4,5,6]
6> hhfuns:map(fun hhfuns:decr/1, L).
[0,1,2,3,4]

乌托邦

xl

Stay hungry, Stay foolish.