Skip to content

Commit

Permalink
Add q60
Browse files Browse the repository at this point in the history
  • Loading branch information
davidkun committed Aug 31, 2024
1 parent a49d057 commit 633e722
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 2 deletions.
20 changes: 20 additions & 0 deletions src/ex/q060.clj
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
;; https://4clojure.oxal.org/#/problem/060
;; Write a function which behaves like reduce, but returns
;; each intermediate value of the reduction. Your function
;; must accept either two or three arguments, and the return
;; sequence must be lazy.

(ns ex.q060)

(defn ans
"Problem 60, Sequence Reductions. restriction: reductions"
([f coll]
(lazy-seq
(if-let [s (seq coll)]
(ans f (first s) (rest s))
(list (f)))))
([f val coll]
(cons val
(lazy-seq
(when-let [s (seq coll)]
(ans f (f val (first s)) (rest s)))))))
3 changes: 1 addition & 2 deletions test/ex/q059_test.clj
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,4 @@
(t/is (= [6] ((sut/ans +) 1 2 3)))
(t/is (= [21 6 1] ((sut/ans + max min) 2 3 5 1 6 4)))
(t/is (= ["HELLO" 5] ((sut/ans #(.toUpperCase %) count) "hello")))
(t/is (= [2 6 4] ((sut/ans :a :c :b) {:a 2, :b 4, :c 6, :d 8 :e 10})))
))
(t/is (= [2 6 4] ((sut/ans :a :c :b) {:a 2, :b 4, :c 6, :d 8 :e 10})))))
11 changes: 11 additions & 0 deletions test/ex/q060_test.clj
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
;; https://4clojure.oxal.org/#/problem/060

(ns ex.q060-test
(:require [clojure.test :as t]
[ex.q060 :as sut]))

(t/deftest test-q60
(t/testing "Problem 60, Sequence Reductions"
(t/is (= [0 1 3 6 10] (take 5 (sut/ans + (range)))))
(t/is (= [[1] [1 2] [1 2 3] [1 2 3 4]] (sut/ans conj [1] [2 3 4])))
(t/is (= 120 (reduce * 2 [3 4 5]) (last (sut/ans * 2 [3 4 5]))))))

0 comments on commit 633e722

Please sign in to comment.