-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLisp.fs
More file actions
2012 lines (1321 loc) · 46.1 KB
/
Lisp.fs
File metadata and controls
2012 lines (1321 loc) · 46.1 KB
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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Today we'll be learning F#.
// By writing a Lisp interpreter.
// And then using it to implement microKanren.
// And then... well that one is a surprise!
// Nothing to Lisp in Four Simple Steps.
//
// 1. Read • Syntax, operator precedence table, AST, ... 🤔
// 2. Print • ToStrings, serialization, handlers, ... 😧
// 3. Eval • Code generation, toolchain, libraries, ... 🤯
// 4. Loop • Review, test, build, stage, publish, ... 😬
//
// How hard can it be?
//
// In the case of a Lisp, it turns out to be easy.
//
// We just skip all of it (for this toy interpreter!)
/// A simple Scheme/Clojure inspired interpreter.
///
/// Original implementation taken from
/// https://github.com/AshleyF/FScheme/blob/master/FScheme.fs
///
/// With minor fixes and few additions.
module Lisp
open System
// Step -1 • Requirements
// -----------------------------------------------------------------
// This is what we'd like to provide as input to the interpreter:
/// Data.
///
/// Think of it as JSON; it's just scalars, sequences and maps.
///
/// A few notable additions enable us to represent programs:
/// - Lists, for function application
/// - Symbols, for identifiers and variables
/// - Keywords, for enum values, map keys and more (fast cmp)
/// - Quotation, to generate list expressions, like templates
///
/// This is the entirety of the language's syntax.
let source = """
;; Comments, because comments are good.
#! #nil #t #f ; Short-form literals (*)
; Top value -> type of all our values; think 'object' in C#
undefined ; Bottom -> type has no values; raises an error if evaluated
nil ; Unit -> type Nil has only one value, nil
true false ; Booleans
+1 2 -3 3.14 ; Numbers -> just doubles, this is a toy language, like JavaScript
"Hello World" ; Strings -> utf-16, because these are already available
bare words ! ; Symbols -> syntax? where we're going, we don't need syntax
:key :words ; Keywords -> like symbols, but as self-evaluating values
'a `b ~x ~@xs ; Quotation (quote, quasiquote, unquote, splice-unquote)
() (1 2 "hi") ; Lists
[] [1 2 "hi"] ; Vectors
{} {1 2 3 4} ; Maps
#{} #{1 2 3} ; Sets
"""
/// Code.
///
/// Evaluating data interprets the data as code.
let forms = """
;; Symbols for variables and identifiers
print ;=> #<print> (the print function)
;; Lists for function application.
(print "Hello")
(head [1 2]) ;=> 1
;; Blocks evaluate expressions in sequence
;; The value of the block is from the last expression
(do (print 1) "Hello") ;=> "Hello"
;; Def names a definition in the current namespace
(def answer 42)
;; Conditionals introduce a choice between multiple expressions
(if true
answer
(print "oh no!"))
;; Lambda creates a new function
(def print-name
(fn [name]
(print "Hello, " name)))
;; Let bindings introduce local variables
(let [user "You"]
(print-name user)
;; Let Over Lambda: Capture the current lexical environment
(let [x 42]
(fn add-x [y]
(+ x y)))
"""
// Step 0 • Types Definitions
// -----------------------------------------------------------------
// Only a handful of data types are required.
//
// Most of the types will be function signatures,
// and inferred automatically from the compiler.
/// Tokens provide a lexical view of the source text.
type Token =
| Ignore | Dot
| OpenParen | CloseParen
| OpenSquare | CloseSquare
| OpenCurly | CloseCurly
| OpenHashCurly
| Quote | QuasiQuote | Unquote | UnquoteSplice
| Number of string
| String of string
| Symbol of string
| Keyword of string
/// Expressions represent both data as immutable values and code as functions.
///
/// The 'read' function creates an Expr from a string. (ie JSON.parse)
/// The 'eval' function applies an Expr as code. (this variant unique to Lisp)
/// The 'print' function converts an Expr to a string. (ie JSON.stringify)
///
/// A function evaluates its arguments before applying them.
/// A macro does not, allowing this language to be extended.
[<CustomComparison>]
[<CustomEquality>]
type Expr =
| Undefined | Nil
| Bool of bool
| Num of double
| Str of string
| Sym of string
| Key of string
| Cons of Expr list * Expr
| List of Expr list
| Vec of Expr []
| Map of Map<Expr, Expr>
| Set of Set<Expr>
| Fn of string * (Cont -> Expr list -> Expr)
| Form of string * (Cont -> Env -> Expr list -> Expr)
| Curr of Cont
| Rest of Expr list
| Marker of string
| LVar of int
interface IComparable with
member x.CompareTo y =
match y with
| :? Expr as y' ->
match x, y' with
| Nil, Nil -> 0
| Bool a, Bool b -> a.CompareTo b
| Num a, Num b -> a.CompareTo b
| Str a, Str b | Sym a, Sym b | Key a, Key b -> a.CompareTo b
| LVar a, LVar b -> a.CompareTo b
| _ -> -1
| _ -> failwith "not an Expr"
override x.Equals y =
match y with
| :? Expr as y' ->
match x, y' with
| Nil, Nil -> true
| Bool a, Bool b -> a = b
| Num a, Num b -> a = b
| Str a, Str b | Sym a, Sym b | Key a, Key b -> a = b
| List a, List b | List a, Rest b | Rest a, List b -> a = b
| Vec a, Vec b -> a = b
| Map a, Map b -> a = b
| Set a, Set b -> a = b
| Fn (_, f), Fn (_, g) -> Object.ReferenceEquals (f, g)
| Form (_, f), Form (_, g) -> Object.ReferenceEquals (f, g)
| Curr f, Curr g -> Object.ReferenceEquals (f, g)
| LVar a, LVar b -> a = b
| _ -> false
| _ -> false
override _.GetHashCode () = failwith "TODO"
/// Continuations represent the next step in a computation.
/// Called with the result of the expression being evaluated.
/// They can be called more than once. Or never.
///
/// The current continuation is captured using 'call/cc',
/// allowing powerful manipulations of control flow, for example
/// implementing async/await or exception handling from a library.
and Cont = Expr -> Expr
/// Scopes are sets of definitions and local variables indexed by name.
/// As a ref cell so 'def' can add new definitions to the current scope.
/// Each definition and variable is also a ref cell to support 'set!'.
and Scope = Map<string, Expr ref> ref
/// Our evaluation environment.
///
/// Passed to Form expressions only. Fn doesn't use it, having its arguments already evaluated.
///
/// The top of the list is the current scope. Popping this list returns to the previous scope.
///
/// Better than prototype inheritance -> same features, no chain lookups; backtracking is free.
and Env = Scope list
/// Utilities, mostly allowing vectors, sets & maps to be transformed using list functions.
/// A more serious impl would abstract over a seq.
module Expr =
module List =
let rec toPair = function
| [] -> []
| [_] -> failwith "Syntax error (toPair)."
| a :: b :: t -> (a, b) :: toPair t
let ofPair xs =
let rec expand' acc = function
| [] -> List.rev acc
| (a, b) :: t -> expand' (b :: a :: acc) t
expand' [] xs
module Map =
let ofList = List.toPair >> Map.ofSeq >> Map
let toList: Map<_,_> -> Expr list = Map.toList >> List.ofPair
module Set =
let ofList = Set.ofList >> Set
let toList = Set.toList
module Vec =
let ofList = Array.ofList >> Vec
let toList = Array.toList
// Step 0.1 • Constant Definitions
// -----------------------------------------------------------------
// Values used by the interpreter.
let undefined = Undefined
let nil = Nil
let boolTrue = Bool true
let boolFalse = Bool false
let restArg = Sym "&"
let fn = Sym "fn"
let macro = Sym "macro"
let quote = Sym "quote"
let quasiQuote = Sym "quasiquote"
let unquote = Sym "unquote"
let splice = Sym "unquote-splicing"
let unbound = Marker "unbound"
let doMark = Marker "do"
let letrec = Marker "letrec"
// Step 1 • Read :: string -> Expr
// -----------------------------------------------------------------
// The first step is converting source text into data.
let tokenize src =
let rec string acc = function
| '\\' :: '"' :: t -> string (acc + "\"") t
| '\\' :: 'b' :: t -> string (acc + "\b") t
| '\\' :: 'f' :: t -> string (acc + "\f") t
| '\\' :: 'n' :: t -> string (acc + "\n") t
| '\\' :: 'r' :: t -> string (acc + "\r") t
| '\\' :: 't' :: t -> string (acc + "\t") t
| '\\' :: '\\' :: t -> string (acc + "\\") t
| '"' :: t -> acc, t
| c :: t -> string (acc + (c.ToString ())) t
| _ -> failwith "Malformed string."
let rec comment = function
| '\r' :: t | '\n' :: t -> t
| _ :: t -> comment t
| [] -> []
let endsToken = function
| '(' | ')' | '[' | ']' | '{' | '}' | ';' | '"' -> true
| w -> Char.IsWhiteSpace w
let rec token acc = function
| c :: _ as t when endsToken c -> acc, t
| w :: t when Char.IsWhiteSpace w -> acc, t
| c :: t -> token (acc + (c.ToString ())) t
| [] -> acc, []
and token' ty acc x t =
let x', t' = token (x.ToString ()) t
tokenize' (ty x' :: acc) t'
and tokenize' acc = function
| w :: t when Char.IsWhiteSpace w -> tokenize' acc t
| ';' :: t -> tokenize' acc <| comment t
| '.' :: t -> tokenize' (Dot :: acc) t
| '(' :: t -> tokenize' (OpenParen :: acc) t
| ')' :: t -> tokenize' (CloseParen :: acc) t
| '[' :: t -> tokenize' (OpenSquare :: acc) t
| ']' :: t -> tokenize' (CloseSquare :: acc) t
| '{' :: t -> tokenize' (OpenCurly :: acc) t
| '}' :: t -> tokenize' (CloseCurly :: acc) t
| '#' :: '<' :: _ -> failwith "Unreadable."
| '#' :: '_' :: t -> tokenize' (Ignore :: acc) t
| '#' :: '{' :: t -> tokenize' (OpenHashCurly :: acc) t
| '~' :: '@' :: t -> tokenize' (UnquoteSplice :: acc) t
| '~' :: t -> tokenize' (Unquote :: acc) t
| '`' :: t -> tokenize' (QuasiQuote :: acc) t
| '\'' :: t -> tokenize' (Quote :: acc) t
| '"' :: t ->
let s, t' = string "" t
tokenize' (String s :: acc) t'
| '-' :: (d :: _ as t) when Char.IsDigit d -> token' Number acc '-' t
| '+' :: (d :: _ as t) when Char.IsDigit d -> token' Number acc '+' t
| d :: t when Char.IsDigit d -> token' Number acc d t
| ':' :: s :: t when not <| endsToken s -> token' Keyword acc s t
| s :: t -> token' Symbol acc s t
| [] -> List.rev acc
tokenize' [] <| Seq.toList src
let tokens = tokenize source
type private ReadState = TopLevel | InList | InVec | InMapOrSet
let read src =
let rec endList ch expected st acc t =
if st = expected then List.rev acc, t
else failwith <| sprintf "Unexpected '%c'" ch
and list st st' ty f t acc =
let e, t' = read' st' [] t
read' st (ty (f e) :: acc) t'
and concat acc acc' t = List.rev (List.rev acc' @ acc), t
and ignore st acc t =
let e, t' = read' st [] t
match e with
| [] -> failwith "Syntax error (ignore #_)."
| [_] -> acc, t'
| _ :: e' -> concat acc e' t'
and wrap st s acc t =
let e, t' = read' st [] t
let wrap' h e' = concat (List [s; h] :: acc) e' t'
match e with
| [] -> failwith "Syntax error (quote ')."
| [h] -> wrap' h []
| h :: e' -> wrap' h e'
and read' st acc = function
| Dot :: _ -> failwith "TODO cons reader"
| OpenParen :: t -> list st InList List id t acc
| OpenSquare :: t -> list st InVec Expr.Vec.ofList id t acc
| OpenCurly :: t -> list st InMapOrSet Expr.Map.ofList id t acc
| OpenHashCurly :: t -> list st InMapOrSet Expr.Set.ofList id t acc
| CloseParen :: t -> endList ')' InList st acc t
| CloseSquare :: t -> endList ']' InVec st acc t
| CloseCurly :: t -> endList '}' InMapOrSet st acc t
| Ignore :: t -> ignore st acc t
| Quote :: (_ :: _ as t) -> wrap st quote acc t
| QuasiQuote :: (_ :: _ as t) -> wrap st quasiQuote acc t
| Unquote :: (_ :: _ as t) -> wrap st unquote acc t
| UnquoteSplice :: (_ :: _ as t) -> wrap st splice acc t
| x :: t ->
let map = function
| Symbol "#!" | Symbol "undefined" | Symbol "⊥" -> undefined
| Symbol "#nil" | Symbol "nil" -> nil
| Symbol "#t" | Symbol "true" -> boolTrue
| Symbol "#f" | Symbol "false" -> boolFalse
| Symbol s -> Sym s
| Keyword s -> Key s
| String s -> Str s
| Number n -> Num (Double.Parse n)
| _ -> failwith "Syntax error."
read' st (map x :: acc) t
| [] -> List.rev acc, []
tokenize src |> read' TopLevel [] |> fst
let testMore = read "(1 (2 '(3 ~4 (5 ~6 #_7 8))))"
let fullExpr = read "(1 2 3 + () [] #{:hello \"world\" {:map 12}})"
let codeExpr = read "(if (do something) (run something-else) :failed)"
let expr = read source
// Step 2 • Print :: Expr -> string
// -----------------------------------------------------------------
// Being able to display data is important. Literals can be read back.
let rec printList (xs: seq<Expr>) = String.Join (" ", Seq.map print xs)
and print = function
| Undefined -> "⊥"
| Nil -> "nil"
| Bool b -> if b then "true" else "false"
| Num n -> n.ToString ()
| Sym s -> s
| Key s -> ":" + s
| Str s -> "\"" + s + "\""
| Cons (h, t) -> "(" + (printList h) + " . " + (print t) + ")"
| List [Sym "quote"; e] -> "'" + print e
| List [Sym "quasiquote"; e] -> "`" + print e
| List [Sym "unquote"; e] -> "~" + print e
| List [Sym "unquote-splice"; e] -> "~@" + print e
| List l | Rest l -> "(" + printList l + ")"
| Vec v -> "[" + printList (Seq.ofArray v) + "]"
| Map m -> "{" + printList (Map.toSeq m |> Seq.collect (fun (a, b) -> [a; b])) + "}"
| Set s -> "#{" + printList (Set.toSeq s) + "}"
| Fn (s, _) | Form (s, _) -> "#<" + s + ">"
| Curr _ -> "#<cont>"
| Marker s -> "#:" + s
| LVar n -> "?" + (n.ToString ())
printfn "%s" <| printList fullExpr
printfn "%s" <| printList expr
// Step a • Interpreter Utilities
// -----------------------------------------------------------------
let malformed n e =
failwith <| sprintf "Malformed '%s': %s" n (print (List [e]))
let math name identity unary op =
let math' cont = function
| [] -> Num identity |> cont
| [Num n] -> Num (unary * n) |> cont
| Num n :: ns ->
let op' a = function
| Num b -> op a b
| m -> malformed (sprintf "%s arg" name) m
Num (List.fold op' n ns) |> cont
| m -> malformed name (List m)
ref <| Fn (name, math')
let compare name pred =
let compare' cont = function
| [Num a; Num b] -> (if pred a b then boolTrue else boolFalse) |> cont
| m -> malformed name (List m)
ref <| Fn (name, compare')
let extend env bindings = ref (Map.ofList bindings) :: env
let lookup env symbol =
match List.tryPick (fun (s: Scope) -> Map.tryFind symbol s.Value) env with
| Some e -> e
| None -> failwith <| sprintf "No binding for '%s'." symbol
type ParamList =
| Params of Expr list
| VarArg of Expr list * Expr
let mkParams xs =
let len = Array.length xs
if len < 2 || xs.[len - 2] <> restArg
then Params <| List.ofArray xs
else VarArg (List.ofArray <| Array.sub xs 0 (len - 2), xs.[len - 1])
let zipParams args =
let len = List.length args
function
| Params xs ->
if len = List.length xs then List.zip xs args
else failwith "Wrong number of arguments."
| VarArg (xs, rest) ->
let xlen = List.length xs
if len < xlen then failwith "Not enough arguments." else
(List.zip xs <| List.take xlen args) @ [rest, Rest <| List.skip xlen args]
let undefinedTy = Sym "Undefined"
let nilTy = Sym "Nil"
let boolTy = Sym "Bool"
let numTy = Sym "Num"
let strTy = Sym "Str"
let symTy = Sym "Sym"
let keyTy = Sym "Key"
let consTy = Sym "Cons"
let listTy = Sym "List"
let vecTy = Sym "Vec"
let mapTy = Sym "Map"
let setTy = Sym "Set"
let fnTy = Sym "Fn"
let lvarTy = Sym "LVar"
let refStar1 = ref Nil
let refStar2 = ref Nil
let refStar3 = ref Nil
let refStarE = ref Nil
let mutable backtrack: list<(unit -> Expr)> = []
type Either<'a, 'b> =
| Left of 'a
| Right of 'b
// Step 3 • Eval :: Expr -> Expr
// -----------------------------------------------------------------
// Evaluating an expression yields another expression.
//
// Evaluation Models:
// - Register (LLVM -> infinity of immutable registers -> explicit registers specified for results and operands)
// - Stack (MSIL -> infinity of immutable locals -> results pushed on stack, operands taken from stack)
// - CPS (Lisp -> environment + function composition -> code being eval is a value passed back to eval)
// (only the Scheme dialect of Lisps -> CPS is not the eval model of Clojure, Common-Lisp, Emacs-Lisp and others)
// (not to be confused with CSP -> building processes using async operations on data channels -> Go language, Clojure core.async lib)
//
// Rich Code for Tiny Computers: A Simple Commodore 64 Game in C++17 - Jason Turner
// https://www.youtube.com/watch?v=zBkNBP00wJE
let rec eval cont env = function
// Environment lookup -> Variables
| Sym s -> (lookup env s).Value |> cont
// Self Evaluating Forms -> Literals
| Nil | Bool _ | Num _ | Str _ | Key _ | Curr _ | List [] | LVar _ as lit -> cont lit
| Rest r -> mapEval (List >> cont) env r
| Vec v -> Expr.Vec.toList v |> mapEval (Expr.Vec.ofList >> cont) env
| Set s -> Expr.Set.toList s |> mapEval (Expr.Set.ofList >> cont) env
| Map m -> Expr.Map.toList m |> mapEval (Expr.Map.ofList >> cont) env
// Application -> Function calls
| List (h :: t) ->
eval (function
| Fn (_, f) -> apply cont env f t // User-defined function -> Program
| Form (_, f) -> f cont env t // Special form or macro -> Compiler
| Curr f ->
match t with
| [] -> malformed "call/cc continuation param" (List t)
| [x] -> eval f env x
| xs -> mapEval (List >> f) env xs
| m -> malformed "call" m) env h
// Runtime errors (or compile-time inside macros)
| Marker s -> failwith <| sprintf "Cannot evaluate marker value %s" s
| Undefined -> failwith "Undefined behavior!"
| m -> malformed "expr" m
and apply cont env fn args = mapEval (fn cont) env args
and mapEval cont env forms =
let rec mapEval' acc = function
| h :: t -> eval (fun a -> mapEval' (a :: acc) t) env h
| [] -> List.rev acc |> cont
mapEval' [] forms
// Step 3.1 • Special Forms ->
// -----------------------------------------------------------------
// A Turing Complete and Extendable Language in 9 Simple Forms
//
// On the Expressive Power of Programming Languages - Shriram Krishnamurthi
// https://www.youtube.com/watch?v=43XaZEn2aLc
//
// Into the Core - Squeezing Haskell into Nine Constructors - Simon Peyton Jones
// https://www.youtube.com/watch?v=uR_VzYxvbxg
// (Do form ...) -> blocks, eval given forms and returns the last result
and Do cont env =
let rec foldEval last = function
| h :: t -> eval (fun x -> foldEval x t) env h
| [] -> cont last
foldEval nil
// (If cond then else) -> eval cond determines the branch to eval next
and If cont env = function
| [cond; t; f] ->
eval (function
| Nil | Bool false -> eval cont env f
| _ -> eval cont env t) env cond
| m -> malformed "if" (List m)
// (Let [bindings] block) -> eval block in a new scope with local variable bindings
and Let cont env = function
| Vec bindings :: body ->
let rec mapBind acc = function
| [Sym s; e] :: t -> eval (fun x -> mapBind ((s, ref x) :: acc) t) env e
| [] ->
let frame = List.rev acc
let env' = extend env frame
Do cont env' body
| _ -> failwith "Malformed 'let' binding."
mapBind [] <| letBind bindings
| m -> malformed "let" (List m)
and LetStar cont env = function
| Vec bindings :: body ->
let rec foldBind env' = function
| [Sym s; e] :: t -> eval (fun x ->
foldBind (extend env' <| [s, ref x]) t) env' e
| [] -> Do cont env' body
| _ -> failwith "Malformed 'let*' binding."
foldBind env <| letBind bindings
| m -> malformed "let*" (List m)
and LetRec cont env = function
| Vec bindings :: body ->
let bind = function
| [Sym s; _] -> s, ref letrec
| m -> malformed "letrec binding" (List m)
let bindings' = letBind bindings
let env' = List.map bind bindings' |> extend env
let frame = env'.Head.Value
let rec mapUpdate = function
| [Sym s; e] :: t -> eval (fun x -> (frame.Item s).Value <- x; mapUpdate t) env' e
| [] -> Do cont env' body
| _ -> failwith "Malformed 'letrec' binding."
mapUpdate bindings'
| m -> malformed "letrec" (List m)
and letBind = Array.toList >> List.chunkBySize 2
// (Def var value) -> eval value and add it to the environment as var
and DefVar cont (env : Env) = function
| [Sym s; e] ->
let def = ref unbound
env.Head.Value <- Map.add s def env.Head.Value
eval (fun x -> def.Value <- x; x |> cont) env e
| m -> malformed "def" (List m)
// (Set! var value) -> eval value and assign it to var
and SetVar cont env = function
| [Sym s; e] -> eval (fun x -> (lookup env s).Value <- x; x |> cont) env e
| m -> malformed "set!" (List m)
// (Fn [arg-list] block) -> lambda constructor. Evaluates arguments when called,
// (Fn name [arg-list] block) binds them to arg-list and then evaluates block.
and Lambda cont env = function
| Vec _ as paramList :: body -> Lambda cont env <| fn :: paramList :: body
| Sym name :: Vec xs :: body ->
let ps = mkParams xs
let closure cont' env' args =
let rec mapBind acc = function
| (Sym p, a) :: t -> eval (fun x -> mapBind ((p, ref x) :: acc) t) env' a
| [] ->
let env'' = List.rev acc |> extend (env @ env')
Do cont' env'' body
| _ -> failwith "Malformed fn param."
zipParams args ps |> mapBind []
Form (name, closure) |> cont
| m -> malformed "fn" (List m)
// (Macro [arg-list] block) -> macro constructor. Same as a lambda, but
// (Macro name [arg-list] block) evaluates the result instead of the arguments (!)
and Macro cont env = function
| Vec _ as paramList :: body -> Macro cont env <| macro :: paramList :: body
| Sym name :: Vec xs :: body ->
let ps = mkParams xs
let closure cont' env' args =
let bind = function Sym p, a -> p, ref a | _, m -> malformed "macro param" m
let env'' = zipParams args ps |> List.map bind |> extend env
Do (eval cont' env') env'' body
Form (name, closure) |> cont
| m -> malformed "macro" (List m)
// (Quote form) -> prevents the evaluation of a form. QuasiQuote allows evaluating subexpressions.
and Quote cont _ = function
| [x] -> cont x
| m -> malformed "quote" (List m)
and QuasiQuote cont env =
let rec cat acc = function
| Left x -> x :: acc
| Right x -> List.rev x @ acc
and map acc ty = function
| [] -> ty <| List.rev acc
| h' :: t' -> unquote (fun x -> map (cat acc x) ty t') h'
and unquote cont' = function
| List [Sym "unquote"; e] -> eval (Left >> cont') env e
| List [Sym "unquote-splicing"; e] ->
let splice cont'' = function
| List l | Rest l -> l |> cont''
| Vec v -> Expr.Vec.toList v |> cont''
| Set s -> Expr.Set.toList s |> cont''
| Map m -> Expr.Map.toList m |> cont''
| m -> malformed "unquote-splicing" m
eval (splice <| Right >> cont') env e
| List (Sym "unquote" :: _) as m -> malformed "unquote" m
| List (Sym "unquote-splicing" :: _) as m -> malformed "unquote-splicing" m
| List l -> map [] List l |> Left |> cont'
| Vec v -> Expr.Vec.toList v |> map [] Expr.Vec.ofList |> Left |> cont'
| Set s -> Expr.Set.toList s |> map [] Expr.Set.ofList |> Left |> cont'
| Map m -> Expr.Map.toList m |> map [] Expr.Map.ofList |> Left |> cont'
| e -> cont' (Left e)
function
| [e] -> unquote (function Left e -> cont e | Right e -> cont (List e)) e
| m -> malformed "quasiquote" (List m)
// (Call/CC f) -> Call w/ Current Continuation. Swiss-army knife of control flow.
and CallCC cont env = function
| [callee] -> eval (function
| Form (_, f) -> f cont env [Curr cont]
| Curr f -> Curr cont |> f |> cont
| m -> malformed "call/cc" m) env callee
| m -> malformed "call/cc" (List m)
// Step 3.2 • Library
// -----------------------------------------------------------------
and Eq cont = function
| [a; b] -> a.Equals b |> Bool |> cont
| m -> malformed "=" (List m)
and Read cont = function
| [Str s] -> read s |> List.head |> cont
| m -> malformed "read (not a string)" (List m)
and Eval cont env = function
| [form] -> eval (eval cont env) env form
| m -> malformed "eval" (List m)
and Print cont args = printList args |> printfn "%s"; cont nil
and Type cont = function
| [e] -> match e with
| Undefined | Marker _ -> cont undefinedTy
| Nil -> cont nilTy
| Bool _ -> cont boolTy
| Num _ -> cont numTy
| Str _ -> cont strTy
| Sym _ -> cont symTy
| Key _ -> cont keyTy
| Cons _ -> cont consTy
| List _ | Rest _ -> cont listTy
| Vec _ -> cont vecTy
| Map _ -> cont mapTy
| Set _ -> cont setTy
| Fn _ | Form _ | Curr _ -> cont fnTy
| LVar _ -> cont lvarTy
| m -> malformed "type" (List m)
and Name cont = function
| [Sym s] | [Key s] -> cont (Str s)
| [(Str _) as s] -> cont s
| m -> malformed "name" (List m)
and Count cont =