Type classes

CIS 194 Week 5
25 September 2014

Before we get down to the business of the day, we need a little header information to get us going:

{-# LANGUAGE FlexibleInstances #-}

That’s a so-called language pragma. GHC includes many features which are not part of the standardized Haskell language. To enable these features, we use language pragmas. There are lots of these language pragmas available — we’ll see only a few over the course of the semester.

import Data.Char  ( isUpper, toUpper )
import Data.Maybe ( mapMaybe )
import Text.Read  ( readMaybe )

Putting the fun in function

We have seen now several cases of using a functional programming style. Here, we will look at several functions using a very functional style to help you get acclimated to this mode of programming.

Functional combinators

First, we need a few more combinators to get us going:

(.) :: (b -> c) -> (a -> b) -> a -> c
(.) f g x = f (g x)

The (.) operator, part of the Haskell Prelude, is just function composition. Say we want to take every element of a list and add 1 and then multiply by 4. Here is a good way to do it:

add1Mul4 :: [Int] -> [Int]
add1Mul4 x = map ((*4) . (+1)) x

While we’re at it, we should also show the (