Skip to content

Instantly share code, notes, and snippets.

@Kakadu
Created November 22, 2018 12:10
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 Kakadu/72da724bbd3cc63da0a350d0c6a9c828 to your computer and use it in GitHub Desktop.
Save Kakadu/72da724bbd3cc63da0a350d0c6a9c828 to your computer and use it in GitHub Desktop.
{-# LANGUAGE FlexibleContexts #-}
module Main where
import Prelude hiding (abs, const)
import Data.Char (digitToInt)
import Text.Parsec
import Text.Parsec.Expr
import Text.Parsec.Token (reservedOp)
import Text.Parsec.Combinator (between, sepBy1, chainr1)
import Data.List (elemIndex)
data T
= Const Char
| Add T T
| Mul T T
deriving Show
const = do
d <- digit
return $ Const d
root :: Parsec String () T
root = buildExpressionParser table (spaces *> const <* spaces)
<?> "expression"
where
table =
[ [binary '*' Mul AssocLeft ]
, [binary '+' Add AssocLeft ]
]
binary name fun assoc = Infix (do{ spaces *> (char name); return fun }) assoc
root2 :: Parsec String () T
root2 = helper2
where
helper (op,f) item = item >>= \c -> many (char op *> item ) >>= \cs -> return $ foldl f c cs
helper2 = helper ('+',Add) (helper ('*',Mul) const)
main :: IO ()
main = do
print $ parse root "" "1+2*3"
print $ parse root2 "" "1+2*3+4"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment