Skip to content

Commit 5b03225

Browse files
committed
Merge pull request pixie-lang#333 from stuarth/misc-fns
add select-keys, rand-int, some?
2 parents f756ff7 + 4d8aef8 commit 5b03225

2 files changed

Lines changed: 33 additions & 0 deletions

File tree

pixie/stdlib.pxi

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -552,6 +552,11 @@ returns true"
552552
(defn rem [num div]
553553
(-rem num div))
554554

555+
(defn rand-int
556+
{:doc "random integer between 0 (inclusive) and n (exclusive)"}
557+
[n]
558+
(rem (rand) n))
559+
555560
(defn =
556561
{:doc "Returns true if all the arguments are equivalent. Otherwise, returns false. Uses
557562
-eq to perform equality checks."
@@ -946,6 +951,16 @@ If further arguments are passed, invokes the method named by symbol, passing the
946951
(fn [v]
947952
(transduce ordered-hash-reducing-fn v)))
948953

954+
(defn select-keys
955+
{:doc "Produces a map with only the values in m contained in key-seq"}
956+
[m key-seq]
957+
(with-meta
958+
(transduce
959+
(comp (filter (fn [k] (contains? m k)))
960+
(map (fn [k] [k (get m k)])))
961+
conj {} key-seq)
962+
(meta m)))
963+
949964
(defn keys
950965
{:doc "If called with no arguments returns a transducer that will extract the key from each map entry. If passed
951966
a collection, will assume that it is a hashmap and return a vector of all keys from the collection."
@@ -1411,6 +1426,10 @@ The new value is thus `(apply f current-value-of-atom args)`."
14111426
(defn nil? [x]
14121427
(identical? x nil))
14131428

1429+
(defn some? [x]
1430+
{:doc "true if x is not nil"}
1431+
(not (nil? x)))
1432+
14141433
(defn fnil [f else]
14151434
(fn [x & args]
14161435
(apply f (if (nil? x) else x) args)))

tests/pixie/tests/test-stdlib.pxi

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,16 @@
189189
(t/assert= (set (vals v)) #{1 2 3})
190190
(t/assert= (transduce (vals) conj! v) (vals v))))
191191

192+
(t/deftest test-select-keys
193+
(let [m ^{:k :v} {:a 1 :b 2}]
194+
(t/assert= (select-keys m [:a :b]) m)
195+
(t/assert= :v
196+
(-> (select-keys m [:a])
197+
meta
198+
:k))
199+
(t/assert= (select-keys m [:a :not-found]) {:a 1})
200+
(t/assert= (select-keys m nil) {})
201+
(t/assert= (select-keys {} [:a]) {})))
192202

193203
(t/deftest test-empty
194204
(t/assert= (empty '(1 2 3)) '())
@@ -273,6 +283,10 @@
273283
(t/assert= (every? even? []) true)
274284
(t/assert= (every? odd? []) true))
275285

286+
(t/deftest test-rand-int
287+
(let [vs (repeatedly 10 #(rand-int 4))]
288+
(t/assert (every? #(and (>= % 0) (< % 4)) vs))))
289+
276290
(t/deftest test-some
277291
(t/assert= (some even? [2 4 6 8]) true)
278292
(t/assert= (some odd? [2 4 6 8]) false)

0 commit comments

Comments
 (0)