Welcome to the most active Linux Forum on the web.
Go Back > Blogs > primenu
User Name


Rate this Entry

Creating a Random Expression in Haskell

Posted 12-22-2009 at 06:10 AM by primenu

I have a Haskell program for parsing and evaluating an mathematical expression of type:
data Expr
= Num Double
| Add Expr Expr
| Mul Expr Expr
| Sin Expr
| Cos Expr
| Var Name
| Neg Expr
deriving (Eq,Show)

type Name = String

I have the defined a property to perform quickcheck: to check the readExpr and showExpr are valid bothway round, here readExpr takes a string of type "2*3+x" and converts it to Expression of type Expr and vice versa for showExpr
prop_showReadExpr :: Expr -> Bool
prop_showReadExpr ex = case (readExpr(showExpr ex)) of
Nothing -> False
_ -> showExpr(fromJust(readExpr(showExpr ex))) == showExpr ex

instance Arbitrary Expr where
arbitrary = sized arbExpr

arbExpr :: Int -> Gen Expr
arbExpr s =
[ (1, do n <- arbitrary return (Num (abs(n))))
, (s, do a <- arbExpr s' b <- arbExpr s' return (Add a b))
, (s, do a <- arbExpr s' b <- arbExpr s' return (Mul a b))
, (s, do a <- arbExpr s' return (Sin (a)))
, (s, do a <- arbExpr s' return (Cos (a)))
, (1, do return (Var "x"))
where s' = s `div` 2

Now I want to get a random expression fro my GUI Calculator, where whenever the user presses a button and the Calculator generates a random Expression of the above type.Can I use the arbExpr which returns a Expression of type 'Gen Expr' for my GUI Calculator, the problem I am having is whenever I try to use :showExpr (arbExpr 9) to get an Expr I get type miss match error saying:
Couldn't match expected type `Expr'
against inferred type `Gen Expr'
In the first argument of `showExpr', namely `(arbExpr 1)'
In the expression: showExpr (arbExpr 1)
In the definition of `it': it = showExpr (arbExpr 1)

Thanks in Advance..
Posted in Uncategorized
Views 1147 Comments 0
« Prev     Main     Next »
Total Comments 0




All times are GMT -5. The time now is 10:26 PM.

Main Menu
Write for LQ is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration