Search code examples
clojure

clojure - take-while to include last item when predicate is false


I have the following function that uses take-while

(defn process [[cash amount wrappers]]
  (let [bought (int (Math/floor (/ cash amount)))
        free (->>
              (iterate (partial unwrapper wrappers) bought)
              (take-while (partial (fn [w a]
                                     (prn (str "a = " a))
                                     (>= a w)
                                     ) wrappers)))]

The problem I have is that I want to include the last item when the predicate is false but take-while does not return that last item.

Is there a way round that with take-while or should I use something else?


Solution

  • You could do something like this, based on the source of take-while:

    (defn take-while+
      [pred coll]
      (lazy-seq
        (when-let [[f & r] (seq coll)]
          (if (pred f)
            (cons f (take-while+ pred r))
            [f]))))