Another update from ingydotnet^djgoku
This commit is contained in:
parent
91df62d461
commit
948b86eafa
7604 changed files with 108452 additions and 22726 deletions
|
|
@ -1,5 +1,7 @@
|
|||
import Text.ParserCombinators.Parsec
|
||||
import Text.ParserCombinators.Parsec.Expr
|
||||
import Text.Parsec
|
||||
import Text.Parsec.Expr
|
||||
import Text.Parsec.Combinator
|
||||
import Data.Functor
|
||||
|
||||
data Exp = Num Int
|
||||
| Add Exp Exp
|
||||
|
|
@ -8,22 +10,20 @@ data Exp = Num Int
|
|||
| Div Exp Exp
|
||||
|
||||
expr = buildExpressionParser table factor
|
||||
where table = [[op "*" (Mul) AssocLeft, op "/" (Div) AssocLeft]
|
||||
,[op "+" (Add) AssocLeft, op "-" (Sub) AssocLeft]]
|
||||
op s f assoc = Infix (f <$ string s) assoc
|
||||
factor = (between `on` char) '(' ')' expr
|
||||
<|> (Num . read <$> many1 digit)
|
||||
on f g = \x y -> f (g x) (g y)
|
||||
|
||||
table = [[op "*" (Mul) AssocLeft, op "/" (Div) AssocLeft]
|
||||
,[op "+" (Add) AssocLeft, op "-" (Sub) AssocLeft]]
|
||||
where op s f assoc = Infix (do string s; return f) assoc
|
||||
eval :: Num a => Exp -> a
|
||||
eval e = case e of
|
||||
Num x -> fromIntegral x
|
||||
Add a b -> eval a + eval b
|
||||
Sub a b -> eval a - eval b
|
||||
Mul a b -> eval a * eval b
|
||||
Div a b -> eval a `div` eval b
|
||||
|
||||
factor = do char '(' ; x <- expr ; char ')'
|
||||
return x
|
||||
<|> do ds <- many1 digit
|
||||
return $ Num (read ds)
|
||||
|
||||
evaluate (Num x) = fromIntegral x
|
||||
evaluate (Add a b) = (evaluate a) + (evaluate b)
|
||||
evaluate (Sub a b) = (evaluate a) - (evaluate b)
|
||||
evaluate (Mul a b) = (evaluate a) * (evaluate b)
|
||||
evaluate (Div a b) = (evaluate a) `div` (evaluate b)
|
||||
|
||||
solution exp = case parse expr [] exp of
|
||||
Right expr -> evaluate expr
|
||||
Left _ -> error "Did not parse"
|
||||
solution :: Num a => String -> a
|
||||
solution = either (const (error "Did not parse")) eval . parse expr ""
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue