Haskell examples

· msp729's blog


I love Haskell. I know many are not blessed with the same quality of taste. This is a display of some Haskell code, for those who have yet to see its beauty.

First: Peano #

 1enum Nat { // Nat can take one of two values:
 2  Zero, // zero
 3  Successor(&Nat) // the successor of a nat
 4}
 5
 6fn add(a: Nat, b: Nat) -> Nat {
 7  match b {
 8    Zero => a, // a + 0 = a
 9    Successor(n) => Successor(add(a,n)) // a + (b + 1) = (a + b) + 1
10  }
11}
1data Nat = Zero | Successor Nat -- Nats are either Zero or a Successor
2
3add :: Nat -> Nat -> Nat
4add a Zero = a -- a + 0 = a
5add a (Successor b) = Successor $ add a b -- a + (b+1)=(a + b)+1

Second: Factorial #

1fn fac(n: u8) -> u64 {
2  if n == 0 {1} // 0! = 1
3  else {n * fac(n-1)} // n! = n * (n-1)!
4}
1fac :: Word8 -> Word64 -- Word means unsigned integer, 8 and 64 are sizes
2fac 0 = 1
3fac n = n * fac (n-1)

Third: Hello World #

1fn hello() {
2  println!("Hello, World!")
3}
1hello :: IO ()
2hello = printLn "Hello, World!"

Fourth: Church numbers, basically impossible to express in Rust, so have Python instead #

1zero = lambda f: lambda x: x
2one = lambda f: lamdba x: f(x)
3two = lambda f: lambda x: f(f(x))
4
5add = lambda c1: lamdba c2: lambda f: lambda x: c1(f)(c2(f)(x)) # that's a lot of lambda
6mul = lambda c1: lambda c2: lambda f: c1(c2(f))
7pow = lambda c1: lambda c2: c2(c1)
 1newtype Church = Church (forall a. (a -> a) -> a -> a)
 2zero, one, two :: Church
 3zero = Church (\f -> id)
 4one = Church id
 5two = Church (\f -> f . f)
 6
 7add, mul, pow :: Church -> Church -> Church
 8add (Church a) (Church b) = Church (\f x -> a f (b f x))
 9mul (Church a) (Church b) = Church (\f -> a (b f))
10pow (Church a) (Church b) = Church (b a)

An alternative Haskell interpretation, closer to pointfree:

 1newtype Church = C (forall a. (a -> a) -> a -> a)
 2zero, one, two :: Church
 3zero = C $ const id
 4one = C id
 5two = C (\f->f.f)
 6
 7apply :: Church -> (a -> a) -> a -> a
 8apply (C n) = n
 9
10add, mul, pow :: Church -> Church -> Church
11add a b = C (\f -> apply a f (apply b f x))
12mul a b = C (\f -> apply a $ apply b f)
13pow a b = C (apply b $ apply a)