This repository has been archived by the owner on Nov 14, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 31
/
core.gk
145 lines (111 loc) · 2.38 KB
/
core.gk
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
;;(ns core)
(def first car)
(def rest cdr)
(def ffirst (fn (xs) (car (car xs))))
(def second (fn (xs) (car (cdr xs))))
(def last
(fn (xs)
(if (cdr xs)
(recur (cdr xs))
(first xs))))
(def inc
(fn (n) (+ n 1)))
(def dec
(fn (n) (- n 1)))
(def zero?
(fn (n) (eq? 0 n)))
(def reduce
(fn (f init xs)
(if xs
(recur f (f init (car xs)) (cdr xs))
init)))
(def count
(fn (lst)
(reduce (fn (x y) (inc x)) 0 lst)))
(def identity (fn (x) x))
(def every?
(fn (pred xs)
(if xs
(if (pred (car xs))
(recur pred (cdr xs)))
t)))
(def some
(fn (pred xs)
(if xs
(if (pred (car xs))
t
(recur pred (cdr xs)))
nil)))
(def or (fn (& xs) (some identity xs)))
(def and (fn (& xs) (every? identity xs)))
(def not (fn (x) (if x nil t)))
(def complement
(fn (pred)
(fn (x) (not (pred x)))))
(def even?
(fn (n) (eq? 0 (mod n 2))))
(def odd?
(complement even?))
(def drop
(fn (n lst)
(if (eq? 0 n)
lst
(recur (dec n) (cdr lst)))))
(def take
(fn (n lst)
(if (> n 0)
(if lst
(cons (car lst) (take (dec n) (cdr lst)))))))
(def nth
(fn (n lst)
(car (drop n lst))))
(def map
(fn (f xs)
(if xs
(cons (f (car xs)) (map f (cdr xs))))))
(def reverse
(fn (lst)
(reduce (fn (xs y) (cons y xs)) nil lst)))
(def concat
(fn (lst & more)
(if lst
(cons (car lst) (apply concat (cons (cdr lst) more)))
(if more
(apply concat more)))))
(def partial
(fn (f & args)
(fn (& more)
(apply f (concat args more)))))
(def juxt
(fn (& fns)
(fn (arg)
(map (fn (f) (f arg)) fns))))
(def repeat
(fn (n x)
(if (> n 0) (cons x (repeat (dec n) x)))))
(def interleave
(fn (& lst)
(if (every? identity lst)
(concat (map car lst) (apply interleave (map cdr lst))))))
(def interpose
(fn (sep lst)
(drop 1 (interleave (repeat (count lst) sep) lst))))
(def join
(fn (sep lst)
(apply str (interpose sep lst))))
(def filter
(fn (pred lst)
(if lst
(if (pred (car lst))
(cons (car lst) (filter pred (cdr lst)))
(recur pred (cdr lst))))))
(def remove
(fn (pred lst)
(filter (complement pred) lst)))
(def comp
(fn (& fns)
((fn (rfns)
(fn (& args)
(reduce (fn (val f) (f val))
(apply (car rfns) args)
(cdr rfns)))) (reverse fns))))