/
prelude.v
128 lines (96 loc) · 2.21 KB
/
prelude.v
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
;;;;;;;;;; Procedures
(def defproc
(macro
(proc (name args &rest exps)
(list 'def name
(list 'proc args
(cons 'begin exps))))))
(def defmacro
(macro
(proc (name args body)
(list 'def name
(list 'macro
(list 'proc args
body))))))
;;;;;;;;;; Math
(defproc <= (a b)
(or (< a b) (= a b)))
(defproc >= (a b)
(or (> a b) (= a b)))
;;;;;;;;;; Logic
(def else true)
(defproc binary-or (a b)
(cond
(= a true) true
(= b true) true
else false))
(defproc binary-and (a b)
(if (= a true)
(if (= b true)
true
false)
false))
(defproc or (&rest xs)
(foldl binary-or false xs))
(defproc and (&rest xs)
(foldl binary-and true xs))
(defproc not (b)
(cond
(= b false) true
(= b true) false
else false))
;;;;;;;;;; Higher Order Procedures
(defproc foldl (f init xs)
(if (= xs '())
init
(foldl f
(f init (first xs))
(rest xs))))
(defproc reverse (xs)
(foldl (proc (acc x) (cons x acc)) '() xs))
(defproc map (f l)
(let (loop (proc (accum xs)
(if (empty? xs)
accum
(loop (cons (f (first xs)) accum)
(rest xs)))))
(loop '() (reverse l))))
;;;;;;;;;; Type Predicates
(defproc list? (n)
(= (typeof n) 'list))
(defproc char? (n)
(= (typeof n) 'char))
(defproc symbol? (n)
(= (typeof n) 'symbol))
(defproc number? (n)
(= (typeof n) 'number))
(defproc procedure? (n)
(= (typeof n) 'procedure))
(defproc macro? (n)
(= (typeof n) 'macro))
(defproc environment? (n)
(= (typeof n) 'environment))
(defproc primitive? (n)
(= (typeof n) 'primitive))
(defproc string? (n)
(= (typeof n) 'string))
(defproc atom? (n)
(not (list? n)))
(defproc empty? (n)
(cond (= n '()) true
(= n "") true
(= n nil) true
else false))
(defproc boolean? (n)
(cond (= n true) true
(= n false) true
else false))
;; (if (= a b) (typeof a) (typeof b))
;; =>
;; (cond (= a b) (typeof a)
;; true (typeof b))
(defmacro if2 (condition consequent alternative)
(list 'cond condition consequent
true alternative))
;;;;;;;;;;
"Prelude version 2016-02-12"