Question: I need to implement the IFELSE type so that I get the results correctly as seen in the picture below. Here is my code in
I need to implement the IFELSE type so that I get the results correctly as seen in the picture below. Here is my code in Haskell:
--LDI: loads one integer to the stack
--IFELSE :
- rule for the IFELSE: If the value on top of the stack is true, then run the first program, else run the second program
-- Since we do not know which branch is executed we will need to verify that there is enough stack to execute either branch on the current stack contents.
-- If either Prog1 or Prog2 produces a rank error then the entire IFELSE produces an error.
-- If the IFELSE command does not produce a rank error then set the rank of the current stack used for subsequent command to the min {rank(Prog1) , rank (Prog2)}. --For example, p2 = [IFELSE [ADD] [LDI 2, DUP] ] ran with stack s2 = [B True, I 5] of rank 2 would result in a rank error.
--However, if p2 ran with stack s3 = [B False, I 10] the result would be [I 2, I 2,I 10].
--Since we dont know which branch the IFELSE statement will take we will -------assign a Rank Error if the stack is rank 2.
type Prog = [Cmd] data Cmd = LDI Int | IFELSE Prog Prog deriving Show data Val = I Int | B Bool deriving Show
type Stack = [Val]
data Result = A Stack | RankError | TypeError deriving Show
type D = Stack -> Stack type Rank = Int type CmdRank = (Int, Int)
-- Define a function rankP that computes the rank of a program -- when ran with a stack of rank r. -- Maybe data type is used to capture rank error. rankP :: Prog -> Rank -> Maybe Rank rankP [] s' = Just s' rankP (x:cs) s | s
run :: Prog -> Stack -> Result run (x:cs) s = case rankP [x] (length s) of Nothing -> RankError Just r -> case semCmd x s of Just s' -> if length s' /= r then TypeError else A s' Nothing -> TypeError
semCmd :: Cmd -> Stack -> Maybe Stack -- loads integer onto the stack semCmd (LDI x ) s = Just (I x:s)
-- loads boolean parameter onto the stack semCmd (LDB b ) s = Just (B b:s)
--rank(n,m) = where n is what is being taken off the stack and m is what is being inserted in the stack.
-- For example:
-- rankC (LDI _) = (0, 1) since LDI adds one value to the stack.
rankC::Cmd -> CmdRank rankC (LDI _) = (0,1) rankC (LDB _) = (0,1) rankC (IFELSE p q) = (0,0)

Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
