Quote Wikipedia:
A combinator is a higher-order function that uses only the application application and the previously defined combinators to determine the result from its arguments.
What does it mean? This means that the combinator is a function (the output is determined solely by its input), the input of which includes the function as an argument.
What do these functions look like and what are they used for? Here are some examples:
(fog)(x) = f(g(x))
Here o is a combinator that takes 2 functions, f and g , and returns as a result its function, the composition of f with g , namely fog .
Combinators can be used to hide logic. Let's say we have a NumberUndefined data NumberUndefined , where NumberUndefined can take a numeric value Num x or an Undefined value, where x a is Number . Now we want to build addition, subtraction, multiplication and division for this new numerical type. The semantics are the same as for Number , except that if Undefined is an input, the output must also be Undefined , and when divided by 0 output is also Undefined .
You can write tedious code, as shown below:
Undefined +' num = Undefined num +' Undefined = Undefined (Num x) +' (Num y) = Num (x + y) Undefined -' num = Undefined num -' Undefined = Undefined (Num x) -' (Num y) = Num (x - y) Undefined *' num = Undefined num *' Undefined = Undefined (Num x) *' (Num y) = Num (x * y) Undefined /' num = Undefined num /' Undefined = Undefined (Num x) /' (Num y) = if y == 0 then Undefined else Num (x / y)
Note that all have the same logic with respect to Undefined input values. Only division does a little more. The solution is to extract the logic by making it a combinator.
comb (~) Undefined num = Undefined comb (~) num Undefined = Undefined comb (~) (Num x) (Num y) = Num (x ~ y) x +' y = comb (+) xy x -' y = comb (-) xy x *' y = comb (*) xy x /' y = if y == Num 0 then Undefined else comb (/) xy
This can be generalized to the so-called Maybe monad, which programmers use in functional languages ββsuch as Haskell, but I wonβt go there.
Thomas Eding Feb 06 '10 at 23:45 2010-02-06 23:45
source share