# GroteTrap

### From HaskellWiki

(Difference between revisions)

(initial contents) |
(updated logicLanguage to reflect the new API) |
||

(4 intermediate revisions by one user not shown) | |||

Line 1: | Line 1: | ||

'''GroteTrap''' allows you to quickly define expression languages. It is [http://hackage.haskell.org/cgi-bin/hackage-scripts/package/GroteTrap available for download] on Hackage. |
'''GroteTrap''' allows you to quickly define expression languages. It is [http://hackage.haskell.org/cgi-bin/hackage-scripts/package/GroteTrap available for download] on Hackage. |
||

− | An example: |
+ | == Example: Logic == |

<haskell> |
<haskell> |
||

Line 17: | Line 17: | ||

{ variable = Var |
{ variable = Var |
||

, operators = |
, operators = |
||

− | [ Unary Not Prefix 0 "!" |
+ | [ Unary Not Prefix 0 "!" |

− | , Nary And True 1 "&&" |
+ | , Assoc And 1 "&&" |

− | , Nary Or True 2 "||" |
+ | , Assoc Or 2 "||" |

− | , Binary Impl InfixR 3 "->" |
+ | , Binary Impl InfixR 3 "->" |

] |
] |
||

} |
} |
||

Line 30: | Line 30: | ||

<haskell> |
<haskell> |
||

− | > readExpression logicLanguage "p && q" |
+ | > readExpression logicLanguage "p && q -> r" |

− | And [Var "p",Var "q"] |
+ | Impl (And [Var "p",Var "q"]) (Var "r") |

</haskell> |
</haskell> |
||

+ | |||

+ | == Example: Arithmetic == |
||

+ | |||

+ | <haskell> |
||

+ | |||

+ | 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 |
||

+ | |||

+ | </haskell> |
||

+ | |||

+ | [[Category:Libraries]] |

## Latest revision as of 13:13, 28 June 2008

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

## [edit] 1 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 "!" , Assoc And 1 "&&" , Assoc Or 2 "||" , Binary Impl InfixR 3 "->" ] }

With this, we can do:

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

## [edit] 2 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