--- /dev/null
+implementation module RefactorX\r
+\r
+import StdEnv\r
+\r
+//Start = map toString [E1,E2,E3,E4,E5]\r
+//Start = map free [E1,E2,E3,E4,E5]\r
+//Start = map toString (map remove_unused_lets [E1,E2,E3,E4,E5])\r
+Start = map eval [E1,E2,E3,E4,E5]\r
+ where\r
+ E1 = OP (LET "x" (OP (NR 42) MIN (NR 3)) (OP (VAR "x") DIV (NR 0))) PLUS (LET "y" (NR 6) (OP (VAR "y") MUL (VAR "y")))\r
+ E2 = LET "x" (NR 42) (OP (VAR "x") PLUS (LET "x" (NR 58) (VAR "x")))\r
+ E3 = LET "x" (NR 1) (LET "y" (NR 2) (LET "x" (NR 3) (NR 4)))\r
+ E4 = LET "x" (NR 1) (OP (VAR "x") PLUS (VAR "y"))\r
+ E5 = OP (LET "x" (NR 1) (VAR "x")) MUL (VAR "x")\r
+\r
+(<+) infixl 9 :: String a -> String | toString a\r
+(<+) str a = str +++ toString a\r
+\r
+instance toString Operator where\r
+ toString PLUS = "+"\r
+ toString MIN = "-"\r
+ toString MUL = "*"\r
+ toString DIV = "/"\r
+ \r
+instance toString Expr where\r
+ toString (NR n) = toString n\r
+ toString (VAR v) = v\r
+ toString (LET n e1 e2) = "(let " <+ n <+ "=" <+ e1 <+ " in " <+ e2 <+ ")"\r
+ toString (OP e1 o e2) = bracket e1 <+ o <+ bracket e2\r
+ where\r
+ bracket :: Expr -> String\r
+ bracket (OP e1 o e2) = "(" <+ (OP e1 o e2) <+ ")"\r
+ bracket e = toString e\r
+\r
+free:: Expr -> [Name]\r
+free (NR n) = [] \r
+free (VAR v) = [v]\r
+free (OP e1 o e2) = removeDup (free e1 ++ free e2)\r
+free (LET n e1 e2) = removeMember n (free e2)\r
+\r
+remove_unused_lets:: Expr -> Expr\r
+remove_unused_lets (LET n e1 e2)\r
+| isMember n (free e2) = (LET n (remove_unused_lets e1) (remove_unused_lets e2))\r
+| otherwise = remove_unused_lets e2\r
+remove_unused_lets (OP e1 o e2) = (OP (remove_unused_lets e1) o (remove_unused_lets e2))\r
+remove_unused_lets e = e\r
+\r
+apply:: Operator Val Val -> Val\r
+apply _ Undef _ = Undef\r
+apply _ _ Undef = Undef\r
+apply DIV _ (Result 0) = Undef\r
+apply o (Result e1) (Result e2) = Result (apply` o e1 e2)\r
+ where \r
+ apply`:: Operator -> Int Int -> Int\r
+ apply` PLUS = +\r
+ apply` MIN = -\r
+ apply` MUL = *\r
+ apply` DIV = /\r
+\r
+\r
+eval:: Expr -> Val\r
+eval e = eval` (remove_unused_lets e) []\r
+ where\r
+ eval`:: Expr [(Name, Val)] -> Val\r
+ eval` (NR n) _ = Result n\r
+ eval` (VAR v) [] = Undef\r
+ eval` (VAR v) [(n, e):xs]\r
+ | v == n = e\r
+ | otherwise = eval` (VAR v) xs\r
+ eval` (OP e1 o e2) xs = apply o (eval` e1 xs) (eval` e2 xs)\r
+ eval` (LET n e1 e2) xs = eval` e2 [(n, eval` e1 xs):xs]\r