Witness: algorithm for finding factorial of a number.
fact(0) -> 1; fact(N) -> N * fact(N - 1).
That of finding all permutations of a given string. "abc" -> ["abc", "acb", "bac", "bca", "cab", "cba"]
:
perms([]) -> [[]]; perms(L) -> [[H|T] || H < - L, T <- perms(L--[H])].
That of getting the ‘next’ iteration of any string. next("a") -> "b". next("z") -> "aa". next("az") -> "ba"
:
next(L) -> lists:reverse(incr(lists:reverse(L))). incr(L) when L =:= [] -> [$a]; incr([H|T]) when H =:= $z -> [$a|incr(T)]; incr([H|T]) -> [H + 1|T].
Deliciously, all these are also (with the addition of a module
and export
line) complete and valid erlang programs.
Stay tuned. I’m loving erlang.
Leave a Reply