12. Monads and more Flashcards
What is a Functor used for?
For mapping a function over each element in a class
What is the declaration of the Functor class?
class Functor f where
fmap :: (a -> b) -> f a -> f b
Describe the functor definition of the Maybe class
instance Functor Maybe where
fmap _ Nothing = Nothing
fmap f Just x = Just (f x)
What is an Applicative used for?
As an extension of the Functor class so that it can take multiple arguments.
What is the decleration of the Applicative class?
class Functor => Applicative f where
pure :: a -> f a
(<*>) :: f (a -> b) -> f a - > f b
What is a Monad used for?
To abstract away details of computations that involve side-effects or other complexities.
What is the definition of the Monad class?
class Applicative m => Monad m where
return :: a -> m a
(»=) :: m a -> (a -> m b) -> m b
Describe the bind function “»=”
Takes a value of the monad type and a function that takes a plain value and returns a monad value, and applies the function to the plain value.
Describe the monad ‘return’ function
Also called pure, takes a plain value and wraps it in the monad type.
Describe the Monad laws
- return x»_space;= f = f x
- mx»_space;= return = mx
- (mx»_space;= f)»_space;= g = mx»_space;= (\x -> (f x»_space;= g))