haskell hunit code example
Example 1: haskell monad
-- Monads are a way of chaining functions in a way
-- that previous computations can have an "effect" on future ones
-- You can model state, non-determinism, IO, partial functions,
-- and tons of other concepts with them.
-- Monads have 2 primary functions associated with them,
return :: Monad m => a -> m a
-- puts a value in the minimal monadic context
(>>=) :: Monad m => m a -> a -> (m b) -> m b
-- allows for a monadic value to be "unwrapped" and passed into
-- another context-creating function
-- for instance, the Maybe type is defined as
data Maybe a = Nothing | Just a
-- the Maybe monad is implemented as
instance Monad Maybe where
-- return :: a -> Maybe a
return x = Just x
-- (>>=) :: Maybe a -> (a -> Maybe b) -> Maybe b
Nothing >>= f = Nothing
(Just x) >>= f = f x
Example 2: haskell functor
-- Functors are a class of data structure that "contain" a generic type
-- you can "inject" functions inside these functors with `fmap`
-- Applying a function "inside" of a functor will not change the structure
-- of the functor
-- e.g `fmap (\x -> x + 1)` [1..10] will not change the length of the list
-- Functors require an implentation of `fmap`
fmap :: Functor f => (a -> b) -> f a -> f b
-- and have to obey the functor laws:
-- fmap id = id
-- fmap (f . g) = fmap f . fmap g