-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProof.hs
More file actions
74 lines (60 loc) · 2.03 KB
/
Proof.hs
File metadata and controls
74 lines (60 loc) · 2.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
{-# LANGUAGE OverloadedStrings #-}
import Control.Applicative
import Data.Attoparsec.Text
import Data.Char
import Data.Function
import Data.Ratio
import Data.Text (Text)
import Text.Parser.Combinators (chainl1, chainr1)
import Text.Printf
type Equation = (Expr, Expr)
data Expr
= Lit Integer
| Var Char
| Add Expr Expr
| Sub Expr Expr
| Mul Expr Expr
| Div Expr Expr
| Exp Expr Expr
| Neg Expr
deriving (Eq, Ord)
instance Show Expr where
show (Lit x) = show x
show (Var x) = [x]
show (Add x y) = printf "(%s + %s)" (show x) (show y)
show (Sub x y) = printf "(%s - %s)" (show x) (show y)
show (Mul x y) = printf "(%s * %s)" (show x) (show y)
show (Div x y) = printf "(%s / %s)" (show x) (show y)
show (Exp x y) = printf "(%s ^ %s)" (show x) (show y)
show (Neg x) = printf "-(%s)" (show x)
showRational :: Rational -> String
showRational x
| denominator x == 1 = show (numerator x)
| otherwise = printf "(%s/%s)" (show (numerator x)) (show (denominator x))
main :: IO ()
main = print $ toEquation "3*x^(y-2)^2/4=2"
fromExp = putStrLn . either ("error:"++) show . parseOnly (expr <* endOfInput)
toEquation :: Text -> Either String Equation
toEquation = parseOnly (equation <* endOfInput)
equation :: Parser Equation
equation = (,) <$> expr <* string "=" <*> expr
expr,term,fact,prim,lit,var,neg,parens :: Parser Expr
expr = term `chainl1` (addFn <|> subFn)
term = fact `chainl1` (mulFn <|> divFn)
fact = prim `chainr1` expFn
prim = choice [lit, var, parens, neg]
lit = Lit <$> decimal
var = Var <$> satisfy isAlpha
parens = char '(' *> expr <* char ')'
neg = Neg <$ char '-' <*> expr
addFn,subFn,mulFn,divFn,expFn :: Parser (Expr -> Expr -> Expr)
addFn = Add <$ char '+'
subFn = Sub <$ char '-'
mulFn = Mul <$ char '*'
divFn = Div <$ char '/'
expFn = Exp <$ char '^'
valid :: Equation -> Bool
valid = uncurry ((==) `on` toSOP)
--TODO IMPLEMENT!!!!
toSOP :: Expr -> Expr
toSOP = id