Last active
July 5, 2016 18:49
-
-
Save rewinfrey/f9727f8429a47238536eb1cd36a22213 to your computer and use it in GitHub Desktop.
Haskell Derivation Basics
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Basics where | |
{- | |
1. What is Semigroup? Define the type class. | |
2. What is Monoid? Define the type class. | |
3. What is Functor? Define the type class. | |
4. What is Applicative? Define the type class. | |
5. What is Monad? Define the type class. | |
6. Define fmap in terms of bind. | |
7. Define bind in terms of fmap and join. | |
-} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module BasicsAnswers where | |
{- 1. Semigroup is a type class that defines a single function: | |
mappend (<>) | |
-} | |
class Semigroup where | |
(<>) :: a -> a -> a | |
{- 2. Monoid is a type class whose parent is Semigroup, but adds an additional function: | |
mempty | |
-} | |
class Semigroup a => Monoid a where | |
mempty :: a | |
{- 3. Functor is a type class without a parent, and defines two functions: | |
fmap (<$>) | |
<$ | |
-} | |
class Functor (f :: * -> *) where | |
fmap :: (a -> b) -> f a -> fb | |
<$ :: a -> f b -> f a | |
{- 4. Applicative is a type class whose parent is Functor, but adds an additional four functions: | |
applicative (<*>) | |
pure | |
*> | |
<* | |
-} | |
class Functor f => Applicative (f :: * -> *) where | |
pure :: a -> f a | |
(<*>) :: f (a -> b) -> f a -> f b | |
(*>) :: f a -> f b -> f b | |
(<*) :: f a -> f b -> f a | |
{- 5. Monad is a type class whose parent is Applicative, but adds an additional four functions: | |
return | |
bind (>>=) | |
sequence (>>) | |
fail | |
-} | |
class Applicative m => Monad (m :: * -> *) where | |
return :: a -> m a | |
(>>=) :: (a -> m b) -> m a -> m b | |
(>>) :: m a -> m b -> m b | |
fail :: String -> m a | |
{- 6. Define fmap in terms of bind: -} | |
fmap' (a -> b) -> f a -> f b | |
fmap' f a = a >>= return . f | |
{- 7. Define bind in terms of fmap and join -} | |
(>>=) :: (a -> m b) -> m a -> m b | |
(>>=) f m = join $ f <$> m |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment