Created
May 25, 2017 20:52
-
-
Save elliotpotts/2ed93b23d0e0b97ce6355f59e6dd673f to your computer and use it in GitHub Desktop.
This file contains 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
import Control.Applicative | |
import Control.Monad | |
newtype Parser a = Parser (String -> [(String, a)]) | |
run :: Parser a -> String -> [(String, a)] | |
run (Parser pf) = pf | |
instance Functor Parser where | |
fmap f (Parser pf) = Parser $ \s -> fmap (fmap f) (pf s) | |
-- Identity | |
-- fmap id = id | |
-- Composition | |
-- fmap f . fmap g = fmap (f . g) | |
instance Applicative Parser where | |
pure x = Parser $ \s -> [(s, x)] | |
(Parser a2b_pf) <*> ap = Parser $ \s -> a2b_pf s >>= (\(rest, a2b) -> run (fmap a2b ap) rest) | |
-- Identity | |
-- pure id <*> v = v | |
-- Homomorphism | |
-- pure f <*> pure x = pure (f x) | |
-- Interchange | |
-- u <*> pure y = pure ($ y) <*> u | |
-- Composition | |
-- pure . <*> u <*> v <*> w = u <*> (v <*> w) | |
instance Monad Parser where | |
return = pure | |
(Parser apf) >>= a2_bpf = Parser $ \s -> apf s >>= (\(rest, a) -> run (a2_bpf a) rest) | |
-- Left identity | |
-- return a >>= f = f a | |
-- Right identity | |
-- m >>= return = m | |
-- Associativity | |
-- (m >>= f) >>= g = m >>= (\x -> f x >>= g) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment