miniMAL: step9
[jackhill/mal.git] / core.mal
1 (def! inc (fn* (a) (+ a 1)))
2
3 (def! dec (fn* (a) (- a 1)))
4
5 (def! zero? (fn* (n) (= 0 n)))
6
7 (def! reduce
8 (fn* (f init xs)
9 (if (> (count xs) 0)
10 (reduce f (f init (first xs)) (rest xs))
11 init)))
12
13 (def! identity (fn* (x) x))
14
15 (def! every?
16 (fn* (pred xs)
17 (if (> (count xs) 0)
18 (if (pred (first xs))
19 (every? pred (rest xs))
20 false)
21 true)))
22
23 (def! not (fn* (x) (if x false true)))
24
25 (def! some
26 (fn* (pred xs)
27 (if (> (count xs) 0)
28 (let* (res (pred (first xs)))
29 (if (pred (first xs))
30 res
31 (some pred (rest xs))))
32 nil)))
33
34 (defmacro! and
35 (fn* (& xs)
36 (if (empty? xs)
37 true
38 (if (= 1 (count xs))
39 (first xs)
40 `(let* (and_FIXME ~(first xs))
41 (if and_FIXME (and ~@(rest xs)) and_FIXME))))))
42
43 (defmacro! or
44 (fn* (& xs)
45 (if (empty? xs)
46 nil
47 (if (= 1 (count xs))
48 (first xs)
49 `(let* (or_FIXME ~(first xs))
50 (if or_FIXME or_FIXME (or ~@(rest xs))))))))
51
52 (defmacro! cond
53 (fn* (& clauses)
54 (if (> (count clauses) 0)
55 (list 'if (first clauses)
56 (if (> (count clauses) 1)
57 (nth clauses 1)
58 (throw "cond requires an even number of forms"))
59 (cons 'cond (rest (rest clauses)))))))
60
61 (defmacro! ->
62 (fn* (x & xs)
63 (if (empty? xs)
64 x
65 (let* (form (first xs)
66 more (rest xs))
67 (if (empty? more)
68 (if (list? form)
69 `(~(first form) ~x ~@(rest form))
70 (list form x))
71 `(-> (-> ~x ~form) ~@more))))))
72
73 (defmacro! ->>
74 (fn* (x & xs)
75 (if (empty? xs)
76 x
77 (let* (form (first xs)
78 more (rest xs))
79 (if (empty? more)
80 (if (list? form)
81 `(~(first form) ~@(rest form) ~x)
82 (list form x))
83 `(->> (->> ~x ~form) ~@more))))))
84