-
Notifications
You must be signed in to change notification settings - Fork 6
/
utils.mal
74 lines (66 loc) · 2.21 KB
/
utils.mal
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
(def! inc (fn* (a) (+ a 1)))
(def! string/length
(fn* [s]
(count (seq (str s)))))
(def! replace-chars
(fn* [s replace-map]
(let* [chars (seq (str s))
replace-one-char
(fn* [char]
(if (contains? replace-map char)
(get replace-map char)
char))
helper
(fn* [result index]
(if (>= index (count chars))
(apply str result)
(helper (concat result [(replace-one-char (nth chars index))])
(inc index))))]
(helper [] 0))))
(def! last
(fn* [coll]
(if (empty? coll)
nil
(nth coll (- (count coll) 1)))))
(def! string/join
(fn* [separator coll]
(let*
[iter (fn* [res xs]
(cond
(empty? xs) ""
(= (count xs) 1) (str res (first xs))
'else (iter (str res (first xs) separator) (rest xs))))]
(iter "" coll))))
(def! n-entries
(fn* [func size]
(let* [helper
(fn* [result]
(if (= size (count result))
result
(helper (concat result (list (func))))))]
(helper (list)))))
(def! map-with-index
(fn* [func coll]
(let* [loop-func
(fn* [remaining-seq seq-index map-result]
(if (empty? remaining-seq)
map-result
(loop-func (rest remaining-seq) (inc seq-index) (concat map-result [(func (first remaining-seq) seq-index)]))))]
(loop-func coll 0 '()))))
(def! vector-map-with-index
(fn* [func coll]
(let* [loop-func
(fn* [remaining-seq seq-index map-result]
(if (empty? remaining-seq)
map-result
(loop-func (rest remaining-seq) (inc seq-index) (conj map-result (func (first remaining-seq) seq-index)))))]
(loop-func coll 0 []))))
(def! zip
(fn* [a b]
(let* [helper
(fn* [remain-a remain-b zip-result]
(let* [both-empty (if (empty? remain-a) (empty? remain-b) false)]
(if both-empty
zip-result
(helper (rest remain-a) (rest remain-b) (conj zip-result [(first remain-a) (first remain-b)])))))]
(helper a b []))))