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
75
76
77
78
79
80
81
82
83
84
85
86
87
|
{-
- Copyright 2018 Raymond Hogenson
-
- This file is part of HSC.
- HSC is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- HSC is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with HSC. If not, see <http://www.gnu.org/licenses/>.
-}
module Expr (parseE, Expr(..)) where
import Text.Parsec
import Text.Parsec.Language
import Text.Parsec.Token
import Text.Parsec.Expr
import qualified Data.Functor.Identity
data Expr = Plus Expr Expr
| Negate Expr
| Minus Expr Expr
| Times Expr Expr
| Div Expr Expr
| Pow Expr Expr
| EInt Integer
| EFloat Double
| E
| Pi
| Log Expr
| Sin Expr
| Cos Expr
| Sqrt Expr
tokenParser :: TokenParser st
tokenParser = haskell
parseNumber :: Parsec String u Expr
parseNumber = do n <- naturalOrFloat tokenParser
case n of
Left i -> return (EInt i)
Right d -> return (EFloat d)
tokenS :: String -> Parsec String u ()
tokenS s = () <$ try (symbol tokenParser s)
inner :: Parsec String u Expr
inner = parseNumber <|> E <$ tokenS "e" <|> Pi <$ tokenS "pi" <|> parens tokenParser parseExpr
binary :: String -> (a -> a -> a) -> Assoc
-> Operator String u Data.Functor.Identity.Identity a
binary name fun assoc =
Infix (fun <$ tokenS name) assoc
prefix :: String -> (a -> a)
-> Operator String u Data.Functor.Identity.Identity a
prefix name fun = Prefix (fun <$ tokenS name)
table :: [[Operator String u Data.Functor.Identity.Identity Expr]]
table = [ [ prefix "log" Log, prefix "sin" Sin, prefix "cos" Cos, prefix "sqrt" Sqrt ]
, [ prefix "-" Negate ]
, [ binary "^" Pow AssocLeft ]
, [ binary "*" Times AssocLeft
, binary "/" Div AssocLeft
]
, [ binary "+" Plus AssocLeft
, binary "-" Minus AssocLeft
]
]
parseExpr :: Parsec String u Expr
parseExpr = buildExpressionParser table inner
parser :: Parsec String u Expr
parser = do whiteSpace tokenParser
parseExpr
parseE :: String -> Either ParseError Expr
parseE s = parse parser "" s
|