1. The Easy Part
  2. Higher Order Functions
  3. Types
  4. Lists
  5. Complex Data Objects
  6. File IO
  7. Classes
  8. Monads
  9. List Monads
  10. Shared Transactional Memory

Higher Order Functions

All Functions Have One Arg?

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-}
6foo a b c = a + b * c
7 
8main =
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
[1 of 1] Compiling Main             ( fun.hs, fun.o )
Linking fun ...
$ ./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

fun2.hs
1foo n fun = (fun (n+1))+(fun (n+2))
2 
3main = putStrLn(show(foo 3 (2*)))
$ ghc --make fun2.hs
[1 of 1] Compiling Main             ( fun2.hs, fun2.o )
Linking fun2 ...
$ ./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

fun3.hs
1foo n fun = (fun (n+1))+(fun (n+2))
2 
3main = putStrLn(show(foo 3 (\x -> x*2)))
$ ghc --make fun3.hs
[1 of 1] Compiling Main             ( fun3.hs, fun3.o )
Linking fun3 ...
$ ./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

op.hs
1(<*>) a b = a * b
2 
3brakstar a b = a * b
4 
5main =
6    do
7        putStrLn(show(3 <*> 4))
8        putStrLn(show(2 `brakstar` 5))
9        putStrLn(show(brakstar 9 4))
$ ghc --make op.hs
[1 of 1] Compiling Main             ( op.hs, op.o )
Linking op ...
$ ./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.