module Intro where import Prelude hiding (foldr, map, filter, reverse, (++), length) -- Pattern matching example: calculating the length of a list -- Also demonstrates recursion -- You can specify the type signature of a function, -- though it's optional and can be inferred by the compiler -- This function works for lists of any type 'a' (polymorphic) length :: [a] -> Int length [] = 0 length (x : xs) = 1 + length xs -- Currying example: a function that concatenates two lists -- In Haskell, functions take one argument and return another -- function if more arguments are needed (++) :: [a] -> [a] -> [a] [] ++ ys = ys (x : xs) ++ ys = x : xs ++ ys -- You can use the (++) function like this: [1,2] ++ [3,4] which -- results in [1,2,3,4] -- Note: The (++) operator is already defined in Prelude, -- this is just for demonstration -- Higher-order function example: -- applying a function to each element of a list map :: (a -> b) -> [a] -> [b] map _ [] = [] map f (x : xs) = f x : map f xs -- You can use the map function like this: -- map (+1) [1,2,3] which results in [2,3,4] -- Here, (+1) is a function that adds 1 to its argument -- and map applies it to each element of the list [1,2,3] -- This demonstrates Haskell's ability to treat functions as -- first-class citizens allowing functions to be passed as -- arguments and returned from other functions -- You can also use lambda expressions for anonymous functions -- Example: map (\x -> x * 2) [1,2,3] -- which results in [2,4,6] -- Here, (\x -> x * 2) is a lambda function that doubles its input filter :: (a -> Bool) -> [a] -> [a] filter _ [] = [] filter p (x : xs) | p x = x : filter p xs | otherwise = filter p xs -- You can use the filter function like this: -- filter even [1,2,3,4] which results in [2,4] -- Here, even is a function that checks if a number is even -- and filter applies it to each element of the list [1,2,3,4] -- to keep only those that satisfy the predicate -- Fold example: summing a list of numbers foldr :: (a -> b -> b) -> b -> [a] -> b foldr _ z [] = z foldr f z (x:xs) = f x (foldr f z xs) -- foldr (+) 0 [1,2,3,4] -- = foldr (+) 0 (1:2:3:4:[]) -- = foldr (+) 0 (1:(2:(3:(4:[])))) -- = 1+(2+(3+(4+0))) -- = 10 -- Data type definition example: defining a binary tree -- This defines a polymorphic binary tree that can hold -- values of any type 'a' -- The Tree type has two constructors: Leaf and Node -- Constructors describe how to build values of the Tree type -- They can be used in pattern matching as well data Tree a = Leaf a | Node (Tree a) (Tree a) -- Example function to calculate the size of a Tree treeSize :: Tree a -> Int treeSize (Leaf _) = 1 treeSize (Node left right) = treeSize left + treeSize right -- Exercise: A function that reverses (mirrors) a tree. reverse :: Tree a -> Tree a reverse (Leaf x) = Leaf x reverse (Node l r) = Node (reverse r) (reverse l)