Higher Order Functions

All Functions Have One Arg?

file: fun.hs
1 -- Single line comments start with -- and go to the line's end
2 {-
3   Multi-line comments
4   look like this.
5 -}
6 foo a b c = a + b * c
7 
8 main =
9     let
10         bar = foo 1 -- creates the function bar b c = 1+b*c
11         baz = bar 2 -- creates the function baz c = 1+2*c
12         res = baz 3 -- computes the result res = 1+2*3
13     in
14         putStrLn(show(res))
> ghc --make fun.hs; ./fun
[1 of 1] Compiling Main             ( fun.hs, fun.o )
Linking fun ...
7

In principle, you can think of all functions in Haskell as taking a single argument. The function baz takes a Num and returns a Num. The function bar takes a Num and returns a function that takes a Num and returns a Num, and so on.


"2*" is a Function

file: fun2.hs
1 foo n fun = (fun (n+1))+(fun (n+2))
2 
3 main = putStrLn(show(foo 3 (2*)))
> ghc --make fun2.hs; ./fun2
[1 of 1] Compiling Main             ( fun2.hs, fun2.o )
Linking fun2 ...
18

Here the function foo takes two arguments. The first is a Num, the second a function that operates on a Num. The function that we supply in our definition of main is (2*), the "multiply by two" function. Cool, eh?


Anonymous Functions

file: fun3.hs
1 foo n fun = (fun (n+1))+(fun (n+2))
2 
3 main = putStrLn(show(foo 3 (\x -> x*2)))
> ghc --make fun3.hs; ./fun3
[1 of 1] Compiling Main             ( fun3.hs, fun3.o )
Linking fun3 ...
18

Here is yet another way to define a function. In this case, it is an anonymous or lambda function. The backslash signifies the beginning of the argument list, then you have an arrow then the function body.


Defining Operators

file: op.hs
1 (<*>) a b = a * b
2 
3 brakstar a b = a * b
4 
5 main =
6     do
7         putStrLn(show(3 <*> 4))
8         putStrLn(show(2 `brakstar` 5))
9         putStrLn(show(brakstar 9 4))
> ghc --make op.hs; ./op
[1 of 1] Compiling Main             ( op.hs, op.o )
Linking op ...
12
10
36

Now it's pretty silly to define your own weird multiplication operator like this, but the point is to show you how to do it. That way, in case of emergency, you'll be able to do it on your own.