ClojureDocs

Nav

Namespaces

unreduced

clojure.core

Available since 1.7 (source)
  • (unreduced x)
If x is reduced?, returns (deref x), else returns x
2 Examples
(unreduced :foo)
;;=> :foo

(unreduced (reduced :foo))
;;=> :foo

(unreduced (clojure.lang.Reduced. :foo))
;;=> :foo
;; Transducers have a "completing arity" which is called at the end of the
;; reduction to finalize the output. This is done outside of the normal
;; reduction loop, so there is nothing to unwrap a reduced return value, should
;; the reducing function be called from the completing arity and happen to wrap
;; the return in a Reduced:

(defn conj-till-odd
  ([coll] coll)
  ([coll x] (cond-> (conj coll x) (odd? x) reduced)))

(defn inc-nums+7 [rf]
  (fn new-rf
    ([result] (rf result 7)) ; A bit contrived, but makes the point
    ([result x] (rf result (inc x)))))

(transduce inc-nums+7 conj-till-odd [] [1 3 5 7 9])
;; => #<Reduced@5c1e145d: [2 4 6 8 10 7]>

;; So we can wrap the return of the completing arity in `unreduced` to make sure
;; we don't return a Reduced. After all, it's the end of the reduction anyway:

(defn inc-nums+7 [rf]
  (fn new-rf
    ([result] (unreduced (rf result 7)))
    ([result x] (rf result (inc x)))))

(transduce inc-nums+7 conj-till-odd [] [1 3 5 7 9])
;; => [2 4 6 8 10 7]
See Also

Returns true if x is the result of a call to reduced

Added by svenschoenung

Wraps x in a way such that a reduce will terminate with the value x

Added by svenschoenung

f should be a function of 2 arguments. If val is not supplied, returns the result of applying f to...

Added by svenschoenung

If x is already reduced?, returns it, else returns (reduced x)

Added by svenschoenung
0 Notes
No notes for unreduced