lab03: impl int, succ, pred
This commit is contained in:
@@ -21,6 +21,9 @@ Representing this language in Haskell is fairly straightforward.
|
||||
> data Exp = ETrue
|
||||
> | EFalse
|
||||
> | Eif Exp Exp Exp
|
||||
> | EInt Int
|
||||
> | ESucc Exp
|
||||
> | EPred Exp
|
||||
> deriving Show
|
||||
|
||||
|
||||
@@ -37,6 +40,7 @@ As with our expressions, representing our values in Haskell is straightforward:
|
||||
|
||||
> data Val = VTrue
|
||||
> | VFalse
|
||||
> | VInt Int
|
||||
> deriving Show
|
||||
|
||||
The next part is to define our "evaluate" function.
|
||||
@@ -89,6 +93,15 @@ You must complete the other cases.
|
||||
> case evaluate e1 of
|
||||
> VTrue -> evaluate e2
|
||||
> VFalse -> evaluate e3
|
||||
> evaluate (EInt n) = VInt n
|
||||
> evaluate (ESucc e) =
|
||||
> case evaluate e of
|
||||
> VInt n -> VInt (n + 1)
|
||||
> _ -> error "Succ expects an integer"
|
||||
> evaluate (EPred e) =
|
||||
> case evaluate e of
|
||||
> VInt n -> VInt (n - 1)
|
||||
> _ -> error "Pred expects an integer"
|
||||
|
||||
|
||||
And here we have a couple of programs to test.
|
||||
@@ -96,6 +109,9 @@ prog1 should evaluate to VTrue and prog2 should evaluate to VFalse
|
||||
|
||||
> prog1 = Eif ETrue ETrue EFalse
|
||||
> prog2 = Eif (Eif ETrue EFalse ETrue) ETrue (Eif ETrue EFalse ETrue)
|
||||
> prog3 = ESucc (EInt 1)
|
||||
> prog4 = EPred (EInt 5)
|
||||
> prog5 = Eif (ETrue) (EInt 1) (EInt 2)
|
||||
|
||||
The following lines evaluate the test expressions and display the results.
|
||||
Note the type of main. 'IO ()' indicates that the function performs IO and returns nothing.
|
||||
@@ -107,6 +123,9 @@ when we deal with the great and terrible subject of _monads_.)
|
||||
> main = do
|
||||
> putStrLn $ "Evaluating '" ++ (show prog1) ++ "' results in " ++ (show $ evaluate prog1)
|
||||
> putStrLn $ "Evaluating '" ++ (show prog2) ++ "' results in " ++ (show $ evaluate prog2)
|
||||
> putStrLn $ "Evaluating '" ++ (show prog3) ++ "' results in " ++ (show $ evaluate prog3)
|
||||
> putStrLn $ "Evaluating '" ++ (show prog4) ++ "' results in " ++ (show $ evaluate prog4)
|
||||
> putStrLn $ "Evaluating '" ++ (show prog5) ++ "' results in " ++ (show $ evaluate prog5)
|
||||
|
||||
|
||||
Once you have the evaluate function working
|
||||
|
||||
Reference in New Issue
Block a user