47 lines
849 B
Haskell
47 lines
849 B
Haskell
module HW4Part1 where
|
|
|
|
data Reg = A | B | R
|
|
|
|
data Expr
|
|
= Lit Int
|
|
| Reg Reg
|
|
| Plus Expr Expr
|
|
| Leq Expr Expr
|
|
| Not Expr
|
|
|
|
type Prog = [Stmt]
|
|
|
|
data Stmt
|
|
= Store Reg Expr
|
|
| If Expr Prog Prog
|
|
| Loop Prog
|
|
| Break
|
|
|
|
program :: Prog
|
|
program =
|
|
[ Store A $ Lit 7
|
|
, Store B $ Lit 9
|
|
, Store R $ Lit 0
|
|
, Loop $
|
|
[ If (Reg A `Leq` Lit 0)
|
|
[ Break ]
|
|
[ Store R $ Reg R `Plus` Reg B
|
|
, Store A $ Reg A `Plus` Lit (-1)
|
|
]
|
|
]
|
|
]
|
|
|
|
while :: Expr -> Prog -> Stmt
|
|
while cond body = Loop [ If cond body [ Break ] ]
|
|
|
|
sumFromTo :: Int -> Int -> Prog
|
|
sumFromTo f t =
|
|
[ Store A $ Lit f
|
|
, Store B $ Lit t
|
|
, Store R $ Lit 0
|
|
, while (Leq (Reg A) (Reg B))
|
|
[ Store R $ Reg R `Plus` Reg A
|
|
, Store A $ Reg A `Plus` (Lit 1)
|
|
]
|
|
]
|