/
SchemeEval.hs
658 lines (563 loc) · 17.1 KB
/
SchemeEval.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
module SchemeEval where
import Data.Maybe
import SchemeParser
import SchemeTypes
import qualified Data.IntMap as M
import Control.Monad.Reader
import Control.Monad.Cont
import Control.Monad.Trans.Maybe
import Control.Monad.State
import Data.Function
newtype Scheme u k s a = Scheme { unScheme :: ReaderT u (ContT k (MaybeT (State s))) a }
deriving (Functor, Applicative, Monad, MonadReader u, MonadState s, MonadCont, MonadFail)
type Scheme' a = Scheme U [E] S a
{-
eval :: Expr -> U -> K -> C
= Expr -> U -> ([E] -> C) -> C
= Expr -> U -> ([E] -> S -> A) -> S -> A
= Expr -> U -> ([E] -> S -> (Maybe [E], S)) -> S -> (Maybe [E], S)
~ Expr -> U -> ([E] -> MaybeT (State S) [E]) -> MaybeT (State S) [E]
~ Expr -> U -> ContT [E] (MaybeT (State S)) [E]
~ Expr -> Reader U (ContT [E] (MaybeT (State S)) [E])
-}
-- _ :: Expr -> U -> K -> C
eval1 :: Expr -> U -> ([E] -> C) -> C
eval1 = eval
eval2 :: Expr -> U -> ([E] -> S -> A) -> S -> A
eval2 = eval1
eval2' :: Expr -> U -> ([E] -> S -> (Maybe [E], S)) -> S -> (Maybe [E], S)
eval2' = eval2
eval3 :: Expr -> U -> ([E] -> State S (Maybe [E])) -> State S (Maybe [E])
eval3 e u k = state (eval2 e u (runState . k))
eval3' :: Expr -> U -> ([E] -> MaybeT (State S) [E]) -> MaybeT (State S) [E]
eval3' e u k = MaybeT (eval3 e u (runMaybeT . k))
eval4 :: Expr -> U -> ContT [E] (MaybeT (State S)) [E]
eval4 e u = ContT (eval3' e u)
eval5 :: Expr -> ReaderT U (ContT [E] (MaybeT (State S))) [E]
eval5 e = ReaderT (eval4 e)
eval6 :: Expr -> Scheme' [E]
eval6 = Scheme . eval5
-- Combine into one expression
reflect
:: (u -> (a -> s -> (Maybe k, s)) -> s -> (Maybe k, s))
-> Scheme u k s a
reflect act = Scheme (ReaderT (\u -> ContT (\k -> MaybeT (state (act u (runState . (runMaybeT . k)))))))
reify
:: Scheme u k s a
-> u -> (a -> s -> (Maybe k, s)) -> s -> (Maybe k, s)
reify f r k s = f
& unScheme
& (`runReaderT` r)
& (`runContT` (MaybeT . state . k))
& runMaybeT
& (`runState` s)
{-
λ> reify . reflect
reify . reflect
:: (u -> (a -> s -> (Maybe k, s)) -> s -> (Maybe k, s))
-> u -> (a -> s -> (Maybe k, s)) -> s -> (Maybe k, s)
λ> reflect . reify
reflect . reify :: Scheme u k s a -> Scheme u k s a
-}
evalM (Const a) =
sendM (Ek a)
evalM (Id i) = do
p <- ask
r <- singleM =<< holdM (envLookup p i)
case r of
Em Undefined -> wrongM ("Undefined variable: " <> i)
e -> sendM e
evalM (App e0 e) = do
(e:es) <- evalsM (e0 : e)
applicateM e es
evalM (If e0 e1 e2) = do
e <- singleM =<< evalM e0
if truish e
then evalM e1
else evalM e2
evalM (IfPartial e0 e1) = do
e <- singleM =<< evalM e0
if truish e
then evalM e1
else sendM (Em Unspecified)
evalM (Lambda is g e0) = do
s <- get
p <- ask
let l = new s
sendM
( Ef
( l,
\es k' ->
if length es == length is
then
tievals
((\p' -> evalc g p' (eval e0 p' k')) . extends p is)
es
else
wrong
( "wrong number of arguments, expected "
<> show (length is)
<> ", namely "
<> show is
<> " but got "
<> show (length es)
<> " instead"
)))
evalM (LambdaV is i gs e0) = do
s <- get
p <- ask
let l = new s
sendM
(Ef
( l
, \es k' ->
if length es >= length is
then tievalsrest
((\p' -> evalc gs p' (eval e0 p' k')) .
extends p (is <> [i]))
(length is)
es
else wrong
("too few arguments, expected at least " <>
show (length is) <> ", namely " <> show is)))
evalM (LambdaVV i gs e0) = evalM (LambdaV [] i gs e0)
evalM (Set i e) = do
[e] <- evalM e
p <- ask
modify (update (envLookup p i) e)
sendM (Em Unspecified)
eval :: Expr -> U -> K -> C
eval = reify . evalM
-- |Evaluate a list of expressions, sending the collected result to
-- the continuation.
evals :: [Expr] -> U -> K -> C
evals [] _ k = k []
evals (e0:es) p k = eval e0 p $ single $ \e0 -> evals es p $ \es -> k (e0 : es)
evalsM :: [Expr] -> Scheme U [E] S [E]
-- evalsM = mapM evalM
evalsM = mapM (singleM <=< evalM)
-- |Evaluate a list of commands, returning to the continuation.
evalc :: [Expr] -> U -> C -> C
evalc [] p θ = θ
evalc (g0:gs) p θ = eval g0 p $ \es -> evalc gs p θ
-- |Look up an identifier in the environment.
envLookup :: U -> Ide -> L
envLookup u i = fromMaybe 0 (lookup i u)
-- |Extend an environment with a list of identifiers and their store
-- locations.
extends :: U -> [Ide] -> [L] -> U
extends p is as = zip is as <> p
-- |Send a value to the continuation.
send :: E -> K -> C
send e k = k [e]
sendM e = pure [e]
-- |Raise an error.
wrong :: X -> C
wrong x p = (Nothing, p)
wrongM :: MonadFail m => String -> m a
wrongM = fail
-- |Given a location, look it up in the store and send it to the
-- continuation.
hold :: L -> K -> C
hold a k s@(c, m) = send (fst (m M.! a)) k s
holdM :: L -> Scheme' [E]
holdM a = do
(c,m) <- get
sendM (fst (m M.! a))
single :: (E -> C) -> K
single f es
| length es == 1 = f (head es)
| otherwise =
wrong
("wrong number of return values, expected 1 but got " <> show (length es))
singleM es =
if length es == 1
then pure (head es)
else wrongM ("wrong number of return values, expected 1 but got " <> show (length es))
-- |Given the store, return the next free cell.
new :: S -> L
new (c, _) = c + 1
-- |The empty environment.
emptyEnv :: U
emptyEnv = mempty
-- |The empty store.
emptyStore :: S
emptyStore = (0, mempty)
update :: L -> E -> S -> S
update a e (c, s) = (max a c, M.insert a (e, True) s)
assign :: L -> E -> C -> C
assign a e θ s = θ (update a e s)
truish :: E -> T
truish (Ek (Boolean False)) = False
truish _ = True
-- |Permute an expression list (as the order of evaluation of
-- arguments is undefined in Scheme). Must be an inverse operation to
-- @unpermute@.
permute :: [Expr] -> [Expr]
permute = id
-- |Unpermute a value list (as the order of evaluation of arguments is
-- undefined in Scheme). Must be an inverse operation to @permute@.
unpermute :: [E] -> [E]
unpermute = id
-- |Apply a Scheme procedure to a Haskell function that accepts list
-- of values, passing them as operands to the procedure.
applicate :: E -> [E] -> K -> C
applicate (Ef e) es k = snd e es k
applicate x _ _ =
wrong ("failed to apply " <> show x <> ", expected a procedure")
applicateM f es = reflect (const (applicate f es))
-- |Lift a Haskell function that takes one argument into a
-- Scheme procedure.
onearg :: (E -> K -> C) -> [E] -> K -> C
onearg ζ [e] k = ζ e k
onearg _ a _ =
wrong ("wrong number of arguments, expected 1 but got " <> show (length a))
-- |Lift a Haskell function that takes two arguments into a Scheme
-- procedure.
twoarg :: (E -> E -> K -> C) -> [E] -> K -> C
twoarg ζ [e1, e2] k = ζ e1 e2 k
twoarg _ x _ =
wrong
("wrong number of arguments, expected 2 but got " <>
show (length x) <> ": " <> show x)
-- |Scheme @list@, also an example of how Scheme procedures can be
-- defined from other ones, but written in CPS.
list :: [E] -> K -> C
list [] k = send (Ek Nil) k
list (e:es) k = list es $ single $ \es -> cons [e, es] k
-- TODO: rewrite with mapM
-- |Scheme @cons@.
cons :: [E] -> K -> C
cons =
twoarg
(\e1 e2 k s ->
(\s' -> send (Ep (new s, new s', True)) k (update (new s') e2 s'))
(update (new s) e1 s))
factorial :: [E] -> K -> C
factorial =
onearg
(\e1 k ->
case e1 of
(Ek (Number 0)) -> send (Ek (Number 1)) k
m@(Ek (Number n)) ->
factorial [Ek (Number (n - 1))] $ single $ \e -> mult [e, m] k
x -> wrong ("non-numeric argument to factorial" <> show x))
makeNumBinop name constructor op =
twoarg
(\e1 e2 k ->
case e1 of
(Ek (Number r1)) ->
case e2 of
(Ek (Number r2)) -> send (constructor (op r1 r2)) k
x ->
wrong
("non-numeric argument to " <>
name <> ", got " <> show x <> " instead")
x ->
wrong
("non-numeric argument to " <>
name <> ", got " <> show x <> " instead"))
-- |Scheme @+@
add :: [E] -> K -> C
add = makeNumBinop "+" (Ek . Number) (+)
-- |Scheme @<@
less :: [E] -> K -> C
less = makeNumBinop "<" (Ek . Boolean) (<)
-- |Scheme @>@
more :: [E] -> K -> C
more = makeNumBinop ">" (Ek . Boolean) (>)
-- |Scheme @=@
eqli :: [E] -> K -> C
eqli = makeNumBinop "=" (Ek . Boolean) (==)
-- |Scheme @>=@
eqlig :: [E] -> K -> C
eqlig = makeNumBinop ">=" (Ek . Boolean) (>=)
-- |Scheme @<=@
eqlilt :: [E] -> K -> C
eqlilt = makeNumBinop "<=" (Ek . Boolean) (<=)
-- |Scheme @*@
mult :: [E] -> K -> C
mult = makeNumBinop "*" (Ek . Number) (*)
-- |Scheme @-@
sub :: [E] -> K -> C
sub = makeNumBinop "-" (Ek . Number) (-)
-- |Scheme @modulo@
smod :: [E] -> K -> C
smod = makeNumBinop "modulo" (Ek . Number) mod
-- |Scheme @div@
sdiv :: [E] -> K -> C
sdiv = makeNumBinop "div" (Ek . Number) div
-- |Scheme @car@
car :: [E] -> K -> C
car =
onearg
(\case
(Ep (a, _, _)) -> hold a
x -> \_ -> wrong ("non-pair argument to car: " <> show x))
-- |Scheme @cdr@
cdr :: [E] -> K -> C
cdr =
onearg
(\case
(Ep (_, a, _)) -> hold a
x -> \_ -> wrong ("non-pair argument to cdr: " <> show x))
-- |Scheme @set-car!@
setcar :: [E] -> K -> C
setcar =
twoarg
(\e1 e2 k ->
case e1 of
Ep (a, _, True) -> assign a e2 (send (Em Unspecified) k)
Ep _ -> wrong "immutable argument to set-car!"
x -> wrong ("non-pair argument to set-cdr!: " <> show x))
-- |Scheme @set-car@
setcdr :: [E] -> K -> C
setcdr =
twoarg
(\e1 e2 k ->
case e1 of
Ep (_, a, True) -> assign a e2 (send (Em Unspecified) k)
Ep _ -> wrong "immutable argument to set-cdr!"
x -> wrong ("non-pair argument to set-cdr! got " <> show x))
-- |Scheme @eqv?@
eqv :: [E] -> K -> C
eqv =
twoarg
(\e1 e2 ->
case (e1, e2) of
(Ek a, Ek β) -> retbool $ a == β
(Em a, Em β) -> retbool $ a == β
(Ev a, Ev β) -> retbool $ a == β
(Ep (a, x, _), Ep (β, y, _)) -> retbool $ a == β && x == y
(Ef (a, _), Ef (β, _)) -> retbool $ a == β
_ -> retbool False)
retbool :: Bool -> K -> C
retbool = send . Ek . Boolean
predLift :: (E -> Bool) -> [E] -> K -> C
predLift p = onearg (retbool . p)
-- |Scheme @number?@
numberp :: [E] -> K -> C
numberp = predLift p
where
p (Ek (Number _)) = True
p _ = False
-- |Scheme @boolean?@
booleanp :: [E] -> K -> C
booleanp = predLift p
where
p (Ek (Boolean _)) = True
p _ = False
-- |Scheme @symbol?@
symbolp :: [E] -> K -> C
symbolp = predLift p
where
p (Ek (Symbol _)) = True
p _ = False
-- |Scheme @procedure?@
procedurep :: [E] -> K -> C
procedurep = predLift p
where
p (Ef _) = True
p _ = False
-- |Scheme @pair?@
pairp :: [E] -> K -> C
pairp = predLift p
where
p (Ep _) = True
p _ = False
-- |Scheme @null?@
nullp :: [E] -> K -> C
nullp = predLift p
where
p (Ek Nil) = True
p _ = False
-- |Scheme @string?@
stringp :: [E] -> K -> C
stringp = predLift p
where
p (Ek (String _)) = True
p _ = False
-- |Scheme @symbol->string@
symbolToString :: [E] -> K -> C
symbolToString = onearg
(\case
(Ek (Symbol q)) -> send (Ek (String q))
v -> \_ -> wrong ("non-symbol argument to symbol->string: " <> show v))
-- |Scheme @string->symbol@
stringToSymbol :: [E] -> K -> C
stringToSymbol = onearg
(\case
(Ek (String q)) -> send (Ek (Symbol q))
v -> \_ -> wrong ("non-string argument to string->symbol: " <> show v))
-- |Scheme @string-append@
stringAppend = twoarg
(\e1 e2 ->
case (e1, e2) of
(Ek (String p), Ek (String q)) -> send (Ek (String (p <> q)))
(x, Ek (String q)) -> \_ -> wrong
("non-string argument to string-append: " <> show x)
(Ek (String p), x) -> \_ -> wrong
("non-string argument to string-append: " <> show x)
(x, x') -> \_ -> wrong ("non-string arguments to string-append: " <> show x <> " " <> show x'))
-- |Scheme @number->string
numberToString = onearg
(\case
(Ek (Number n)) -> send (Ek (String (show n)))
x -> \_ -> wrong ("non-numeric argument to number->string: " <> show x))
valueStdExtract (Nothing, _) =
error "Failed to extract value from expression"
valueStdExtract (Just a, _) = head a
liftExpr = applicate . valueStdExtract . evalStd
liftString = liftExpr . rparse
-- |Parse and evaluate a string.
reval :: String -> A
reval s =
case readProg s of
Right res -> evalStd res
Left err -> (Nothing, emptyStore)
-- |Parse a string into an expression.
rparse :: String -> Expr
rparse s =
case readProg s of
Right res -> res
Left _ -> error ("Failed to parse" <> s)
-- |An example of defining a Scheme procedure given an expression.
recursive =
liftExpr
(Lambda
["fn"]
[]
(App
(Lambda ["h"] [] (App (Id "h") [Id "h"]))
[ Lambda
["g"]
[]
(App
(Id "fn")
[ LambdaVV
"arglist"
[]
(App (Id "apply") [App (Id "g") [Id "g"], Id "arglist"])
])
]))
-- |Scheme @apply@
apply :: [E] -> K -> C
apply =
twoarg
(\e1 e2 k ->
case e1 of
Ef f -> valueslist [e2] (\es -> applicate e1 es k)
x -> wrong ("bad procedure argument to apply: " <> show x))
valueslist :: [E] -> K -> C
valueslist =
onearg
(\e k ->
case e of
Ep _ ->
cdr
[e]
(\es -> valueslist es (\es -> car [e] (single (\e -> k (e : es)))))
(Ek Nil) -> k []
x -> wrong ("non-list argument to values-list:" <> show x))
tievals :: ([L] -> C) -> [E] -> C
tievals f [] s = f [] s
tievals f (e:es) s = tievals (\as -> f (new s : as)) es (update (new s) e s)
-- tievals :: ([L] -> S -> A) -> [E] -> S -> A
tievalsM f l s = reflect (const (const (tievals f l)))
-- tievalsM f l s = do
-- newLocs <- traverse (\e -> update <$> gets new <*> pure e) l
-- -- forM_ l (\e -> do
-- -- l <- gets new
-- -- modify (update l e)
-- -- )
-- pure ()
-- |Scheme @call-with-current-continuation@
callcc :: [E] -> K -> C
callcc =
onearg
(\e k ->
case e of
Ef _ ->
\s ->
applicate
e
[Ef (new s, \es k' -> k es)]
k
(update (new s) (Em Unspecified) s)
_ -> wrong ("bad procedure argument to call/cc: " <> show e))
-- |Scheme @values@
values :: [E] -> K -> C
values es k = k es
-- |Scheme @call-with-values@
cwv = twoarg (\e1 e2 k -> applicate e1 [] (\es -> applicate e2 es k))
tievalsrest :: ([L] -> C) -> Int -> [E] -> C
tievalsrest f es v =
list (dropfirst es v) (single (\e -> tievals f (takefirst es v <> [e])))
dropfirst = drop
takefirst = take
-- |The "normal" continuation.
idKCont :: [E] -> S -> A
idKCont e s = (Just e, s)
-- |Evaluate an expression with the standard environment and store.
evalStd prog = reify (reflect (eval prog)) stdEnv idKCont stdStore
-- |The standard environment
stdEnv :: U
stdEnv = zip stdEnvNames [1 ..]
exprDefinedOps = [("recursive", recursive)]
-- |The list of built-in operations.
builtInOps =
[ ("+", add)
, ("*", mult)
, ("-", sub)
, ("/", sdiv)
, ("modulo", smod)
, ("<", less)
, (">", more)
, ("=", eqli)
, (">=", eqlig)
, ("<=", eqlilt)
, ("cons", cons)
, ("car", car)
, ("cdr", cdr)
, ("list", list)
, ("eqv?", eqv)
, ("boolean?", booleanp)
, ("symbol?", symbolp)
, ("procedure?", procedurep)
, ("pair?", pairp)
, ("number?", numberp)
, ("set-car!", setcar)
, ("set-cdr!", setcdr)
, ("null?", nullp)
, ("apply", apply)
, ("call-with-values", cwv)
, ("values", values)
, ("call-with-current-continuation", callcc)
, ("call/cc", callcc)
, ("string?", stringp)
, ("symbol->string", symbolToString)
, ("string->symbol", stringToSymbol)
, ("string-append", stringAppend)
, ("number->string", numberToString)
] <>
exprDefinedOps
-- |The list of names of standard operations.
stdEnvNames :: [String]
stdEnvNames = map fst builtInOps
-- |The list of standard operations.
stdOps :: [[E] -> K -> C]
stdOps = map snd builtInOps
-- |The standard prelude.
stdPrelude :: S
stdPrelude = (n, M.fromList ((0,(Em Undefined, False)) : zipWith makeOpStore [1 ..] stdOps))
where
n = length stdOps + 1
makeOpStore loc op = (loc, (Ef (loc, op), True))
-- |The standard store, consisting of a Prelude and infinite space.
stdStore :: S
stdStore = stdPrelude