patterns of computation Flashcards
how would we define a tree type
data Tree a = Leaf a
| Node (Tree a) (Tree a)
what does functor actually do
allows you do use map with any data type not just lists
what does functor represent
a type that can be mapped over
what is the functor definition
class Functor f where
fmap :: (a -> b) -> f a -> f b
what does the applicative functor do
generalises functor to multiple arguments functions
in which case do we use the applicative functor
when we want the other arguments for a function to come dynamically from data (e.g. another list)
what is the (worse) alternative to using the applicative functor
zip the data lists together and pass to map as a tuple, then deconstruct the type inside of the function being passed
what is the definition for the applicative functor
class Applicative f where
pure :: a -> f a
(<*>) :: f (a -> b) -> f a -> f b
what is the role of ‘pure’ in an applicative functor
lifts the value into the context of the function
what is the role of <*> in an applicative functor
its an operator that applies a function inside a context to a value inside a context
what does monad do
generalises the flow of computation depending on the result of functions in that computation allowing each step to influence the next
what is the definition for monad
class Monad m where
(»=) :: m a -> (a -> m b) -> m b
(») :: m a -> m b -> m b
pure :: a -> m a
what does “(»=) :: m a -> (a -> m b) -> m b” do in monad
takes a value inside a monad and the function that creates a new nomadic value and applies it to transform the value
what does “(») :: m a -> m b -> m b” do in monad
sequences two monadic actions ignoring the result of the first
(»)
used for when the variant takes no input argument (usually for io)
(»=)
chainMaybe operator
how are io and monad related
io extends the monad context as it gives it a way to chain functions together so data gets passed on to the next