-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstdlib.lisp
More file actions
65 lines (55 loc) · 1.64 KB
/
stdlib.lisp
File metadata and controls
65 lines (55 loc) · 1.64 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
;;;;
;;;; The DLISP standard library.
;;;;
(def id '(x) x)
(def not '(p) (cond p nil true))
(def and '(p q) (cond p q p))
(def or '(a b) (cond a a b))
;; A casting function from truthy values to `nil` or `false`. Note that this is
;; a second-order function because it invokes `not`, which is defined right here
;; in the stdlib!
(def bool '(p) (not (not p)))
;; Multiplication of positive integers.
;;
;; TODO: Design a scheme for handling bad inputs.
(def mul '(a b) (_mul a b 0))
;; Tail-recursive helper function for `mul`. Returns n * m + sum.
(def _mul '(n m sum)
;; Although (not n) would be sufficient, we can also
;; short-circuit when m is zero as an optimization.
(cond (or (not n) (not m))
sum
(_mul (sub n 1)
m
(add sum m))))
;; Factorial of positive integers.
(def fact '(n)
(cond (not n)
1
(mul n (fact (sub n 1)))))
;; A very horrible equality check for positive integers.
(def pos_eq '(a b)
(cond (and (not a) (not b))
true
(cond (or (and (not a) b)
(and a (not b)))
nil
(pos_eq (sub a 1) (sub b 1)))))
;; Given positive integers `start` and `end`, returns the list of intermediate
;; values. Includes `start`, but excludes `end`.
(def range '(start end)
(cond (pos_eq start end)
'()
(cons start
(range (add start 1)
end))))
(def map '(f xs)
(cond xs
(cons (f (car xs)) (map f (cdr xs)))
'()))
(def filter '(f xs)
(cond xs
(cond (f (car xs))
(cons (car xs) (filter f (cdr xs)))
(filter f (cdr xs)))
'()))