haskell notes Flashcards
Functor laws
– preserve identity law
fmap id = id
– preserve function composition
fmap (g . h) = fmap g . fmap h
Applicative laws
– preserves identity function
pure id ^*> x = x
– preserves function application
pure (g x) = pure g ^*> pure x
– order of evaluation does not matter
x ^> pure y = pure (\g -> g y) ^> x
– is associative
x ^> (y ^> z) = (pure (.) ^> x ^> y) ^*> z
Monad laws
– bind returned value a function = apply function to value
return x»_space;= f = f x
– bind return to a monadic value is the monadic value
mx»_space;= return = mx
– binding is associative
(mx»_space;= f)»_space;= g = mx»_space;= (\x -> (f x»_space;= g))
Functor Class definition
class Functor f where fmap::(a->b) -> f a -> f b
list Functor instance
instance Functor [] where
– fmap :: (a -> b) -> [a] -> [b]
fmap = map
Maybe Functor instance
instance Functor Maybe where -- fmap :: (a -> b) -> Maybe a -> Maybe b fmap _ Nothing = Nothing fmap g (Just x) = Just (g x)
IO Functor instance
instance Functor IO where
– fmap :: (a -> b) -> IO a -> IO b
fmap g mx = do
x
Applicative class definition
class Functor f => Applicative f where
pure::a -> f a
()::f (a -> b) -> f a -> f b
Maybe Applicative instance
instance Applicative Maybe where
– pure:: a -> Maybe a
pure = Just
– ():: Maybe (a -> b) -> Maybe a -> Maybe b
Nothing _ = Nothing
(Just g) mx = fmap g mx
list Applicative instance
instance Applicative [] where
– pure :: a -> [a]
pure a = [a]
-- ()::[a->b] -> [a] -> [b] gs xs = [g x | g
IO Applicative instance
instance Applicative IO where
– pure:: a -> IO a
pure = return
-- () :: IO (a -> b) -> IO a -> IO b mg mx = do g
Monad class definition
class Applicative m => Monad m where return :: a -> m a (>>=) :: m a -> (a -m b) -> m b
Maybe Monad instance
instance Monad Maybe where
– (»=):: Maybe a -> (a -> Maybe b) -> Maybe b
Nothing»_space;= _ = Nothing
(Just x)»_space; f = f x
list Monad instance
instance Monad [] where
– (»=) :: [a] -> (a -> [b]) -> [b]
xs»_space;= f = [y | x
Monoid class definition
class Monoid a where
mempty: :a mappend: : a -> a-> a mconcat:: [a] -> a mconcat = foldr mappend mempty