Module 01: Introduction to Haskell

In this module you will focus on learning some of the basics of the Haskell programming language. If you already know some Haskell, you should focus on helping your partner(s) understand all the material in this module. However, keep in mind that people learn best by doing, not by being told. The driver should be whoever has the least experience with Haskell.

This file is a “literate Haskell document”: only lines preceded by > and a space (see below) are code; everything else (like this paragraph) is a comment, formatted using Markdown syntax. Literate Haskell documents have an extension of .lhs, whereas non-literate Haskell source files use .hs.

GHCi

Hint: to kill a runaway ghci evaluation, use Ctrl+C.

Basic Haskell declarations

Now consider the following Haskell code.

> i :: Int
> i = -35
> 
> n :: Integer
> n = 25
> 
> c :: Char
> c = 'Z'
> 
> b :: Bool
> b = True
> 
> s :: String
> s = "Hello, world!"
> 
> f :: Integer -> Integer
> f n = 2*n + 1
> 
> g :: Integer -> Integer -> Integer
> g m n = (m - n)*(m + n)
> 
> -- This is a comment
> {- So
>    is
>    this -}
> 
> -- Uncomment me:
> -- i = 12

Arithmetic

(Haskell has floating-point values too, but we won’t use them much in this course.)

Booleans

Of course, be sure to cite any resources you use!

Pairs

Values like (n,c) are called pairs, or more generally, tuples. (Haskell also has 3-tuples, 4-tuples, … but we will not use them.)

Functions

Evaluate the following expressions:

f 6
f 8
g 5 4
g 2 3

A function takes one or more input values and produces a single output value.

Pattern matching

> wub :: Integer -> Integer
> wub 0 = 1
> wub n = n * wub (n-1)
> 
> dub :: Integer -> Integer
> dub 0 = 0
> dub 1 = 1
> dub n = dub (n-1) + dub (n-2)
> 
> flub :: (Integer, Integer) -> Integer
> flub p = fst p + 2 * snd p
> 
> gub :: (Integer, Integer) -> Integer
> gub (x,y) = x + 2*y

Guards

> hailstone :: Integer -> Integer
> hailstone n
>   | even n    = n `div` 2
>   | otherwise = 3*n + 1