Functions

Function Definition and Application

Hamler:

  1. add x y = x + y
  2. add 3 4 -- return 7
  3. factorial 0 = 1
  4. factorial n = n * factorial (n - 1)
  5. factorial 10 -- return 3628800

Erlang:

  1. add(X, Y) -> X + Y.
  2. add(3, 4). %% return 7
  3. factorial(0) -> 1;
  4. factorial(N) -> N * factorial(N - 1).
  5. factorial(10). %% return 3628800

Anonymous Functions

Hamler:

  1. add = \a b -> a + b
  2. curried_add = \a -> \b -> a + b
  3. add 2 3
  4. curried_add 2 3

Erlang:

  1. Add = fun(X, Y) -> X + Y end.
  2. CurriedAdd = fun(X) -> fun(Y) -> X + Y end end.
  3. Add(2,3).
  4. (CurriedAdd(2))(3).

Guards in Function

Hamler:

  1. f :: Integer -> String
  2. f n | n > 0 = "Positive Integer"
  3. | n < 0 = "Negative Integer"
  4. | otherwise = "Zero"

Erlang:

  1. f(N) when N > 0 -> "Positive Integer";
  2. f(N) when N < 0 -> "Negative Integer";
  3. f(_) -> "Zero".