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:

1
2
3
4
5
6
7
8
-- Given the type below
data Shape = Rectangle Float Float Float Float | Circle Float Float Float
 
area :: Shape -&;gt; 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:

1
2
3
4
5
6
7
8
9
10
11
tmp = (1, (2, (3, 4)))
 
unpackTmp1 :: (Int, (Int, (Int, Int)))
unpackTmp1 (<;em&gt;, (</em&gt;, rtn)) = rtn
unpackTmp1 tmp
-- rtn = (3,4)
 
unpackTmp2 :: (Int, (Int, (Int, Int)))
unpackTmp2 (<;em&gt;, (</em&gt;, (_, 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:

1
2
3
4
5
6
7
8
9
10
11
12
x = [1..10]
secondItem (<;em&gt;:i:</em&gt;) = i
secondItem x
-- returns 2
 
thirdItem (<;em&gt;:</em&gt;:i:_) = i
thirdItem x
-- return 3
 
tail' (_:rest) = rest
tail' x
-- returns [2..10]