in Programming

Pattern Matching in Haskell

I’ve only been taking one class this semester. It’s an advanced programming course focusing on the functional language Haskell. While I was familiar with some functional concepts such as map, fold, and currying from using Javascript, and lazy-evaluation from dabbling with Clojure, this class has introduced a number of new, intriguing concepts.

Not necessarily a functional feature, pattern matching in Haskell is an incredible feature that has really come to make a lot of sense to me. Given a type constructor with two definitions:


-- Given the type below
data Shape = Rectangle Float Float Float Float | Circle Float Float Float

area :: Shape -> Float
-- We can pattern match below, to change the defn depending on the constructor
area (Rectangle x1 y1 x2 y2) = (y1 - y2) * (x1 - x2) :: Float
-- Use _ to discard matches
area (Circle _ _ radius) = pi * radius * radius

In Haskell, tuples are a basic data type. You can pattern match to unpack a tuple, like this:

tmp = (1, (2, (3, 4)))

unpackTmp1 :: (Int, (Int, (Int, Int)))
unpackTmp1 (<em>, (</em>, rtn)) = rtn
unpackTmp1 tmp
-- rtn = (3,4)

unpackTmp2 :: (Int, (Int, (Int, Int)))
unpackTmp2 (<em>, (</em>, (_, rtn))) = rtn
unpackTmp2 tmp
-- rtn = 4

So, pattern is something really new to me that I haven’t seen in other languages before. It makes dealing with tuples easy, and you can also use it with lists:

x = [1..10]
secondItem (<em>:i:</em>) = i
secondItem x
-- returns 2

thirdItem (<em>:</em>:i:_) = i
thirdItem x
-- return 3

tail' (_:rest) = rest
tail' x
-- returns [2..10]