forked from kvalle/diy-lang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stdlib.diy
92 lines (75 loc) · 1.56 KB
/
stdlib.diy
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
;; Some logical operators.
(define not
(lambda (b)
(if b #f #t)))
(define or
(lambda (a b)
(if a #t b)))
(define and
(lambda (a b)
(if a b #f)))
(define xor
(lambda (a b)
(not (eq a b))))
(define >=
(lambda (a b)
(or (> a b) (eq a b))))
(define <=
(lambda (a b)
(not (> a b))))
(define <
(lambda (a b)
(not (>= a b))))
(define length
(lambda (xs)
(if (empty xs)
0
(+ 1 (length (tail xs))))))
(define sum
(lambda (xs)
(if (empty xs)
0
(+ (head xs) (sum (tail xs))))))
(define range
(lambda (start end)
(if (> start end)
'()
(cons start (range (+ 1 start) end)))))
(define append
(lambda (xs ys)
(if (empty xs)
ys
(cons (head xs) (append (tail xs) ys)))))
(define reverse_
(lambda (xs acc)
(if (empty xs)
acc
(reverse_ (tail xs) (cons (head xs) acc)))))
(define reverse
(lambda (xs)
(reverse_ xs '())))
(define filter
(lambda (predicate xs)
(if (empty xs)
'()
(if (predicate (head xs))
(cons (head xs) (filter predicate (tail xs)))
(filter predicate (tail xs))))))
(define map
(lambda (f xs)
(if (empty xs)
'()
(cons (f (head xs)) (map f (tail xs))))))
(define reduce
(lambda (f acc xs)
(if (empty xs)
acc
(reduce f (f acc (head xs)) (tail xs)))))
(define sort
(lambda (xs)
(if (empty xs)
'()
(append
(sort (filter (lambda (x) (<= x (head xs))) (tail xs)))
(cons (head xs)
(sort (filter (lambda (x) (> x (head xs))) xs)))))))