GroteTrap

From HaskellWiki
Revision as of 13:11, 28 June 2008 by MartijnVanSteenbergen (talk | contribs) (added arithmetic example)
Jump to navigation Jump to search

GroteTrap allows you to quickly define expression languages. It is available for download on Hackage.

Example: Logic

data Logic
  = Var String
  | Or [Logic]
  | And [Logic]
  | Impl Logic Logic
  | Not Logic
  deriving (Show, Eq)

logicLanguage :: Language Logic
logicLanguage = language
  { variable  = Var
  , operators =
      [ Unary    Not  Prefix 0 "!"
      , Nary     And  True   1 "&&"
      , Nary     Or   True   2 "||"
      , Binary   Impl InfixR 3 "->"
      ]
  }

With this, we can do:

> readExpression logicLanguage "p && q -> r"
Impl (And [Var "p",Var "q"]) (Var "r")

Example: Arithmetic

arith :: Language Int
arith = language
  { number    = id
  , operators =
      [ Assoc   sum             2 "+"
      , Binary  (-)     InfixL  2 "-"
      , Assoc   product         1 "*"
      , Binary  div     InfixL  1 "/"
      , Binary  (^)     InfixL  0 "^"
      ]
  , functions = [ function1 abs "abs" ]
  }

evalArith :: String -> Int
evalArith = readExpression arith

> evalArith "abs(2 - 3) + abs(4 - 5)"
2