Lecture 7 - Higher Order Functions

0.0(0)
studied byStudied by 0 people
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
Card Sorting

1/12

encourage image

There's no tags or description

Looks like no tags are added yet.

Study Analytics
Name
Mastery
Learn
Test
Matching
Spaced

No study sessions yet.

13 Terms

1
New cards

What is a higher-order function?

A function that either takes functions as arguments and/or returns a function as a result.

2
New cards

Think about currying in terms of higher-order functions…

Wow - all Haskell functions are higher-order! Because in currying is the process of making a function that takes arguments all together into a function that takes one argument and returns a function!

3
New cards

What is the operator (.) and what does it do?

It takes two functions either side of it and composes them as follows:
odd = not . even
odd x = not (even x)

The type annotation for (.) is:
(.) :: (b → c) → (a → b) → (a → c)

4
New cards

What are some common higher order functions? (3) What do they do?

Map - which applies a function to every element
Filter - which keeps elements that satisfy a predicate
Foldr - which reduces a list to a value

5
New cards

What is the type annotation for map (on a list)?

map :: (a → b) → [a] → [b]

6
New cards

What about the type annotation for map on a binary tree?

bmap :: (a → b) → BinaryTree a → BinaryTree b

7
New cards

What is a functor?

A functor is a type class of mappable types (tuples, lists) that can have a function applied to every element/component of them.

8
New cards

So, fmap is like the functor generalisation of map. What is the type annotation for this?

fmap :: (a → b) → c a → c b

9
New cards

What are the two laws that functors must obey?

1 - Identity Law. If you fmap an identity function across a structure, the result will be the same as the input.
fmap id == id
2 - Composition Law. Composing two functions then mapping them should output the same as mapping one after the other.
fmap (f . g) = = fmap f . fmap g

10
New cards

Can you prove the identity law?

fmap id (Cons x xs)
= Cons (id x) (fmap id xs)
= Cons x xs

11
New cards

What is a functor instance?

You define a functor instance for your own data type which implements the Functor type by providing a valid fmap function.

12
New cards

How would you define a functor instance for a list?

data List a = Nil | Cons a (List a)
instance Functor List where
fmap _ Nil = Nil

fmap f (Cons x xs) = Cons (f x) (fmap f xs)

13
New cards

How would you define a functor instance for a binary tree?

data BinaryTree a = Leaf a | Node a (BinaryTree a) (BinaryTree a)
instance Functor BinaryTree where
fmap f (Leaf a) = Leaf (f a)
fmap f (Node a l r) = Node (f a) (fmap f l) (fmap f r)