20-CS-4003-001 Organization of Programming Languages Fall 2018
Functors

Lambda calculus, Type theory, Formal semantics, Program analysis

Prev     Next     All lectures           Code

Basics

 ```{- functor class class Functor f where fmap :: (a -> b) -> f a -> f b f is a type constructor ex: instance of Functor - List, map is implemented like this map :: (a -> b) -> [a] -> [b] map (\x -> [x]) [1,2,3] ---> [[1],[2],[3]] ex: instance of Functor - Maybe instance Functor Maybe where fmap f (Just x) = (Just (f x)) fmap f Nothing = Nothing -} {- fmap (++ " World") "Hello" produces an error -} w1 = fmap (++ " World") (Just "Hello") w2 = fmap (++ " World") ["Hello"] data Tree a = Empty | Node a (Tree a) (Tree a) {- a is the info of the Node -} | Leaf a deriving (Show, Read, Eq) {- a is the info of the Leaf -} {- treeInsert :: (Ord a) => a -> Tree a -> Tree a Note: an entire new tree is returned Note: Ord is required because compares are made to place nodes in the tree -} 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) {- search for x in a Tree -} inTree x Empty = False inTree x (Leaf a) | x == a = True | otherwise = False inTree x (Node a left right) | x == a = True | x < a = inTree x left | x > a = inTree x right instance Functor Tree where fmap f Empty = Empty fmap f (Leaf x) = (Leaf (f x)) fmap f (Node x leftsub rightsub) = Node (f x) (fmap f leftsub) (fmap f rightsub) w3 = fmap (*4) (foldr treeInsert Empty [5,7,3,2,1,7]) ```