-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStep7.hs
66 lines (56 loc) · 1.43 KB
/
Step7.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
{-# LANGUAGE NoMonomorphismRestriction, FlexibleContexts #-}
-- implicit zero pair, ReaderT layer
module Step7 (
ifThenElse', ifThenElse, divide, withZero
) where
import Instr -- move, moveb, inc, ..., debug
import Allocator (compile, alloc, nalloc)
import Pair
import Translatable
import Control.Monad.Reader
withZero zero body = runReaderT body zero
-- if x is not zero perform thenClause else perform elseClause
-- x+1 must be non-zero if x is zero
-- zero and zero+1 both must contain zero
ifThenElse' x thenClause elseClause = do
zero <- ask
at x open
thenClause
move zero
close
moverel 1
open
moveb (translate 1 x)
elseClause
at (translate 1 zero) close
ifThenElse x thenClause elseClause = do
assign (translate 1 x) 1
ifThenElse' x thenClause elseClause
-- divide x by r
-- quotient is returned in q
-- remainder is returned in r'
divide x r q = do
let r' = translate 1 r
x' = translate 1 x
clear q
clear r'
-- invariant: r + r' is constant (the divisor)
-- so if r == 0 then r' /= 0
dotimes' x $ do
decr r
incr r'
ifThenElse' r
(return ())
(do dotimes' r' (incr r)
incr q)
test_divide a b = do
allocPair $ \zero -> do
withZero zero $ do
allocPair $ \x -> do
allocPair $ \r -> do
alloc $ \q -> do
assign x a -- note: x and r are Pairs!
assign r b
divide x r q
debug q "quotient"
debug (translate 1 r) "remainder"