Skip to content

Instantly share code, notes, and snippets.

@laser
Created May 30, 2014 23:07
Show Gist options
  • Save laser/a1144f9fdbc4aefc5b80 to your computer and use it in GitHub Desktop.
Save laser/a1144f9fdbc4aefc5b80 to your computer and use it in GitHub Desktop.
wtf.haskell
-- Ex. 2 - implement an Applicative instance for Parser
--
-- A. pure a represents the parser which consumes no input
-- and successfully returns a result of a.
--
-- B. p1 <*> p2 represents the parser which first runs p1
-- (which will consume some input and produce a
-- function), <----- doesn't this produce a Maybe (a, String) ????
-- ...then passes the remaining input to p2
-- (which consumes more input and produces some value),
-- then returns the result of applying the function to
-- the value. However, if either p1 or p2 fails then the
-- whole thing should also fail (put another way, p1 <*>
-- p2 only succeeds if both p1 and p2 succeed).
instance Applicative Parser where
pure x = Parser $ \s -> Just (x, s)
(Parser p1) <*> (Parser p2) = Parser f
where
f s = case p1 s of
(Just (x, xs)) -> case p2 xs of
(Just (y, ys)) -> Nothing
Nothing -> Nothing
Nothing -> Nothing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment