-- Lecture week 5B part 2 -- Symbolic expressions -- dave@chalmers.se -- 2016-09-29 import Test.QuickCheck import Data.Maybe(fromJust) xx = undefined ------------------------------------------------------ data Expr = Num Integer | Var VarName | Add Expr Expr | Mul Expr Expr deriving Eq type VarName = String ex1 = Mul (Add (Var "y") (Num 2)) (Var "x") ex2 = Add (Var "x") (Mul (Num 2) (Var "y")) ex3 = Num (-5) `Add` (Num 2 `Mul` Num 4) showExpr (Num n) = show n showExpr (Var v) = v showExpr (Add e e') = showExpr e ++ " + " ++ showExpr e' showExpr (Mul e e') = showFactor e ++ " * " ++ showFactor e' where showFactor e@(Add e1 e2) = "(" ++ showExpr e ++ ")" -- "as pattern" showFactor e = showExpr e instance Show Expr where show = showExpr vars :: Expr -> [VarName] vars (Num n) = [] vars (Var x) = [x] vars (Add e1 e2) = vars e1 ++ vars e2 vars (Mul e1 e2) = vars e1 ++ vars e2 type Table = [(VarName,Integer)] eval :: Table -> Expr -> Integer eval t (Num n) = n eval t (Var x) = fromJust \$ lookup x t eval t (Mul e1 e2) = eval t e1 * eval t e2 eval t (Add e1 e2) = eval t e1 + eval t e2 extable = [("x",2)] extable' = [("x",2),("y",3),("z",4)] ------------------------------------------------------ -- generators for expressions rExp :: Int -> Gen Expr rExp s = frequency [(1,rNum), (1,rVar), (s,rBin)] where rVar = elements [Var "x", Var "y", Var "z"] rNum = do n <- arbitrary return \$ Num n -- fmap Num arbitrary rBin = do op <- elements [Add,Mul] e1 <- rExp s' e2 <- rExp s' return \$ op e1 e2 where s' = s `div` 2 instance Arbitrary Expr where arbitrary = sized rExp ----------------------------------------------------------------------- derive :: VarName -> Expr -> Expr -- derive x e -- the derivative of e with respect to x (d/dx) derive x (Add e1 e2) = Add (derive x e1) (derive x e2) derive x (Mul e1 e2) = Add (Mul (derive x e1) e2) (Mul e1 (derive x e2)) derive x (Var y) | x == y = Num 1 | otherwise = Num 0 derive x (Num n) = Num 0 -- ***** simplify -- data EnvExpr = EnvExpr Table Expr -- deriving Show -- prop_simplify (EnvExpr t e) = .. -- * end