Learn HASKELL with Real Code Examples
Updated Nov 18, 2025
Code Sample Descriptions
1
Haskell Pure Functions
-- Define a custom data type
data Shape = Circle Float | Rectangle Float Float
-- Calculate area using pattern matching
area :: Shape -> Float
area (Circle r) = pi * r * r
area (Rectangle w h) = w * h
-- Higher-order functions
quicksort :: (Ord a) => [a] -> [a]
quicksort [] = []
quicksort (x:xs) =
let smaller = quicksort [a | a <- xs, a <= x]
bigger = quicksort [a | a <- xs, a > x]
in smaller ++ [x] ++ bigger
-- List operations
fibonacci :: [Integer]
fibonacci = 0 : 1 : zipWith (+) fibonacci (tail fibonacci)
-- Main function
main :: IO ()
main = do
let shapes = [Circle 5.0, Rectangle 3.0 4.0, Circle 2.5]
let areas = map area shapes
putStrLn $ "Areas: " ++ show areas
putStrLn $ "First 10 fibonacci: " ++ show (take 10 fibonacci)
putStrLn $ "Sorted [3,1,4,1,5,9]: " ++ show (quicksort [3,1,4,1,5,9])
Demonstrates Haskell's pure functions, pattern matching, and list operations.
2
Haskell Factorial and Recursion
factorial :: Integer -> Integer
factorial 0 = 1
factorial n = n * factorial (n - 1)
main :: IO ()
main = print (factorial 5)
Computing factorial using recursion.
3
Haskell Map and Filter
numbers = [1..10]
squaredEvens = map (^2) (filter even numbers)
main = print squaredEvens
Demonstrates map and filter over lists.
4
Haskell Maybe Type
safeHead :: [a] -> Maybe a
safeHead [] = Nothing
safeHead (x:_) = Just x
main = print (safeHead [1,2,3])
Using Maybe type to handle optional values.
5
Haskell Zip and List Comprehension
xs = [1,2,3]
ys = [4,5,6]
sums = [x + y | (x,y) <- zip xs ys]
main = print sums
Combining lists using zip and list comprehensions.
6
Haskell Higher-Order Functions
numbers = [1..5]
double = map (*2) numbers
sumNumbers = foldr (+) 0 numbers
main = do
print double
print sumNumbers
Using higher-order functions like map, filter, and foldr.
7
Haskell Pattern Matching on Tuples
addPair :: (Int, Int) -> Int
addPair (x, y) = x + y
main = print (addPair (3, 7))
Using pattern matching to destructure tuples.
8
Haskell Recursion with Guards
absVal :: Int -> Int
absVal x
| x < 0 = -x
| otherwise = x
main = print (absVal (-10))
Recursive function with guards to compute absolute value.
9
Haskell Infinite Lists
naturals = [1..]
firstTen = take 10 naturals
main = print firstTen
Working with infinite lists and take function.
10
Haskell Function Composition
increment x = x + 1
double x = x * 2
combined = double . increment
main = print (combined 3) -- Output: 8
Using function composition to combine functions.