You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Haskell is a purely functional programming language. It is the language most commonly used to teach functional programming at A-Level. This lesson covers the essential Haskell syntax and features you need for your exam.
-- Simple function
double :: Int -> Int
double x = x * 2
-- Function with two parameters
add :: Int -> Int -> Int
add x y = x + y
-- Using the function
result = double 5 -- 10
sum = add 3 4 -- 7
The first line is the type signature (optional but recommended). The second line is the definition.
-- Takes an Int, returns an Int
square :: Int -> Int
square x = x * x
-- Takes two Ints, returns an Int
multiply :: Int -> Int -> Int
multiply x y = x * y
-- Takes an Int, returns a Bool
isPositive :: Int -> Bool
isPositive x = x > 0
-- Polymorphic: works with any type 'a' that supports equality
isEqual :: Eq a => a -> a -> Bool
isEqual x y = x == y
| Type | Description | Example Values |
|---|---|---|
| Int | Fixed-precision integer | 42, -7, 0 |
| Integer | Arbitrary-precision integer | 999999999999 |
| Float | Single-precision floating point | 3.14, -0.5 |
| Double | Double-precision floating point | 3.14159265 |
| Bool | Boolean | True, False |
| Char | Single character | 'a', 'Z', '3' |
| String | List of characters | "hello" |
| [Int] | List of integers | [1, 2, 3] |
| (Int, String) | Tuple | (42, "hello") |
Guards provide a way to define conditional logic — like if-else chains:
bmiCategory :: Double -> String
bmiCategory bmi
| bmi < 18.5 = "Underweight"
| bmi < 25.0 = "Normal"
| bmi < 30.0 = "Overweight"
| otherwise = "Obese"
Guards are evaluated top to bottom. otherwise is simply defined as True — it is the catch-all case.
Pattern matching is one of Haskell's most powerful features. It allows you to define different behaviour based on the structure of the input:
-- Pattern matching on values
fibonacci :: Int -> Int
fibonacci 0 = 0
fibonacci 1 = 1
fibonacci n = fibonacci (n-1) + fibonacci (n-2)
-- Pattern matching on lists
head' :: [a] -> a
head' [] = error "empty list"
head' (x:_) = x
-- Pattern matching on tuples
fst' :: (a, b) -> a
fst' (x, _) = x
snd' :: (a, b) -> b
snd' (_, y) = y
Patterns are tried in order from top to bottom.
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.