Skip to content

Instantly share code, notes, and snippets.

@kprav33n
Last active August 29, 2015 14:09
Show Gist options
  • Save kprav33n/d067106facf16db34d21 to your computer and use it in GitHub Desktop.
Save kprav33n/d067106facf16db34d21 to your computer and use it in GitHub Desktop.
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE RebindableSyntax #-}
module Parser where
import Prelude (Char, String)
type Parser a = String -> [(a,String)]
parse :: Parser a -> String -> [(a, String)]
parse parser input = parser input
-- The following four functions are necessary for the do notation.
return :: a -> Parser a
return v = \input -> [(v,input)]
(>>=) :: Parser a -> (a -> Parser b) -> Parser b
p >>= f = \input -> case parse p input of
[] -> []
[(v,out)] -> parse (f v) out
(>>) :: Parser a -> Parser b -> Parser b
p >> f = p >>= \_ -> f
fail :: Parser a
fail = \_ -> []
item :: Parser Char
item = \input -> case input of
[] -> []
(x:xs) -> [(x,xs)]
tupleParse :: Parser (Char, Char)
tupleParse = item >>= \x ->
item >>= \_ ->
item >>= \y ->
return (x, y)
-- This is the syntactic sugar version that uses do notation.
tupleParseSugar :: Parser (Char, Char)
tupleParseSugar = do x <- item
item
y <- item
return (x, y)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment