20-CS-4003-001 Organization of Programming Languages Fall 2017
Types

Lambda calculus, Type theory, Formal semantics, Program analysis

Prev     Next     All lectures           Code

Functors

class Functor f where
  fmap :: (a -> b) -> f a -> f b

instance Functor [] where
  fmap = map

v1 = fmap (*2) [1..3]

instance Functor Maybe where
  fmap f (Just x) = Just (f x)
  fmap f Nothing = Nothing

v2 = fmap (*2) (Just 200)

data Tree a =
    Empty
  | Node a (Tree a) (Tree a)
  | Leaf a deriving (Show, Read, Eq)

instance Functor Tree where
  fmap f Empty = Empty
  fmap f (Leaf x) = Leaf (f x)
  fmap f (Node x left right) =
    Node (f x) (fmap f left) (fmap f right)

v3 = fmap (*2) Empty

treeInsert x Empty = Leaf x
treeInsert x (Leaf a)
  | x == a = Leaf x
  | x < a
    = Node a (treeInsert x Empty) Empty
  | x > a
    = Node a Empty (treeInsert x Empty)
treeInsert x (Node a left right)
  | x == a = Node x left right
  | x < a
    = Node a (treeInsert x left) right
  | x > a
    = Node a left (treeInsert x right)

v4 =
  fmap (*4) 
       (foldr treeInsert Empty [5,6,4,2,1,3])
  -   A functor maps a function over elements of a list. It is defined like this:
 class Functor f where
   fmap :: (a -> b) -> f a -> f b
Note that f is not really a function but a type constructor. If it were a function there would be some concrete types that it would map over. fmap takes a function from one type to another and a functor applied with one type and returns a functor applied with another type. Maybe can be turned into a functor:
 instance Functor Maybe where  
   fmap f (Just x) = Just (f x)  
   fmap f Nothing = Nothing  
To the left, v1 is [2,4,6] and v2 is Just 400. Also to the left is a functor that traverses a Tree, applying a function to every Node. The example shown involves a Tree with integer Nodes and the function that is applied to each Node multiplies the Node's value by 4.