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 belowdata Shape = Rectangle Float Float Float Float | Circle Float Float Floatarea :: Shape -&;gt; Float-- We can pattern match below, to change the defn depending on the constructorarea (Rectangle x1 y1 x2 y2) = (y1 - y2) * (x1 - x2) :: Float-- Use _ to discard matchesarea (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>, (</em>, rtn)) = rtnunpackTmp1 tmp-- rtn = (3,4)unpackTmp2 :: (Int, (Int, (Int, Int)))unpackTmp2 (<;em>, (</em>, (_, rtn))) = rtnunpackTmp2 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>:i:</em>) = isecondItem x-- returns 2thirdItem (<;em>:</em>:i:_) = ithirdItem x-- return 3tail' (_:rest) = resttail' x-- returns [2..10] |