Expression parser added

This commit is contained in:
osmarks 2017-08-17 13:31:24 +01:00
parent 21d1d2bd83
commit bdaf5b159b
2 changed files with 46 additions and 1 deletions

View File

@ -9,7 +9,8 @@
"exposed-modules": [],
"dependencies": {
"elm-lang/core": "5.1.1 <= v < 6.0.0",
"elm-lang/html": "2.0.0 <= v < 3.0.0"
"elm-lang/html": "2.0.0 <= v < 3.0.0",
"Bogdanp/elm-combine": "3.1.1 <= v < 4.0.0"
},
"elm-version": "0.18.0 <= v < 0.19.0"
}

44
src/Expr.elm Normal file
View File

@ -0,0 +1,44 @@
module Expr exposing (Expr(..), Op(..), parse)
import Combine exposing (..)
import Combine.Num as Num
type Op
= Add
| Subtract
| Multiply
| Divide
type Expr
= Num Float
| Op Op
| Group (List Expr)
num : Parser () Expr
num =
Num <$> Num.float <|> Num << toFloat <$> Num.int
stringIs : String -> a -> Parser s a
stringIs str val =
string str *> succeed val
op : Parser () Expr
op =
stringIs "+" Add
<|> stringIs "-" Subtract
<|> stringIs "*" Multiply
<|> stringIs "/" Divide
|> map Op
group : Parser () Expr
group =
between (string "(") (string ")") (sepBy1 whitespace (lazy <| \_ -> parser)) -- Avoid bad recursion issues using lazy parser evaluation
|> map Group
parser : Parser () Expr
parser =
(lazy <| \_ -> group) <|> op <|> num
parse : String -> Result (ParseErr ()) (ParseOk () Expr)
parse =
Combine.parse parser