Skip to content

Commit 9543c07

Browse files
Merge pull request #495 from oholiab/oholiab/iterate
Added iterate function and tests
2 parents 4078b9b + ffbb082 commit 9543c07

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

pixie/stdlib.pxi

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3072,3 +3072,23 @@ ex: (vary-meta x assoc :foo 42)"
30723072
(swap! cache assoc argsv ret)
30733073
ret)
30743074
val)))))
3075+
3076+
(deftype Iterate [f x]
3077+
IReduce
3078+
(-reduce [self rf init]
3079+
(loop [col (rest self)
3080+
acc (rf init (first self))]
3081+
(if (reduced? acc)
3082+
@acc
3083+
(recur (rest col) (rf acc (first col))))))
3084+
ISeq
3085+
(-seq [self]
3086+
(cons x (lazy-seq* (fn [] (->Iterate f (f x)))))))
3087+
3088+
(defn iterate
3089+
{:doc "Returns a lazy sequence of x, (f x), (f (f x)) etc. f must be free of
3090+
side-effects"
3091+
:signatures [[f x]]
3092+
:added "0.1"}
3093+
[f x]
3094+
(->Iterate f x))

tests/pixie/tests/test-stdlib.pxi

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -761,3 +761,9 @@
761761
(t/deftest test-memoize
762762
(let [f (memoize rand)]
763763
(t/assert= (f) (f))))
764+
765+
(t/deftest test-iterate
766+
(t/assert= (take 5 (iterate inc 5)) '(5 6 7 8 9))
767+
(t/assert= (reduce (fn [a v] (reduced "foo")) 0 (iterate inc 1)) "foo")
768+
(t/assert= (reduce (fn [a v] (if (< a 10) (+ a v) (reduced a))) 0 (iterate (partial + 2) 1)) 16))
769+

0 commit comments

Comments
 (0)