Skip to content

Instantly share code, notes, and snippets.

@elliotpotts
Created May 25, 2017 20:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elliotpotts/2ed93b23d0e0b97ce6355f59e6dd673f to your computer and use it in GitHub Desktop.
Save elliotpotts/2ed93b23d0e0b97ce6355f59e6dd673f to your computer and use it in GitHub Desktop.
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