diff --git a/src/rethinkdb/query.cljc b/src/rethinkdb/query.cljc index f4ad124..5ee27ef 100644 --- a/src/rethinkdb/query.cljc +++ b/src/rethinkdb/query.cljc @@ -459,6 +459,11 @@ [sq x-or-func] (term :CONTAINS [sq x-or-func])) +(defn fold + "Apply a function to a sequence in order, maintaining state via an accumulator. + The fold command returns either a single value or a new sequence." + [sq base func & [optargs]] (term :FOLD [sq base func] optargs)) + ;;; Document manipulation (defn pluck diff --git a/src/rethinkdb/types.cljc b/src/rethinkdb/types.cljc index 4d60aec..8307539 100644 --- a/src/rethinkdb/types.cljc +++ b/src/rethinkdb/types.cljc @@ -86,6 +86,7 @@ "LIMIT" 71, "OFFSETS_OF" 87, "CONTAINS" 93, + "FOLD" 187, "GET_FIELD" 31, "KEYS" 94, "VALUES" 186, diff --git a/test/rethinkdb/core_test.clj b/test/rethinkdb/core_test.clj index 81bdb5f..ad5e72b 100644 --- a/test/rethinkdb/core_test.clj +++ b/test/rethinkdb/core_test.clj @@ -230,7 +230,15 @@ (r/max [4 6]) 6 (r/distinct [1 6 1 8]) [1 6 8] (r/contains [1 6 1 8] 1) true - (r/contains [1 6 1 8] 2) false))) + (r/contains [1 6 1 8] 2) false + (r/fold [1 6 1 8] 0 (r/fn [acc number] (r/add acc number))) 16 + (r/fold [1 6 1 8] 0 (r/fn [acc number] (r/add acc 1)) ; increment accumulator + {:emit (r/fn [acc number new-acc] + (r/branch (-> new-acc (r/mod 2) (r/eq 0)) + [number] + [])) ; select elements on even positions + :final-emit (r/fn [acc] [100])}) [6 8 100] ; append 100 to the end + ))) (deftest changefeeds (with-open [conn (r/connect)]