lazy butlast

utilities — cgrand, 1 July 2008 @ 9 h 55 min

Named but-last to avoid name clash with butlast which is a low-level function (it is used in the definition of defn).

(defn but-last
 "Return a lazy sequence of all but the n last items in coll."
  ([coll] (but-last coll 1))
  ([coll n]
    ((fn this [s os]
       (if os
         (lazy-cons (first s) (this (rest s) (rest os))))) (seq coll) (drop n coll))))

Update: Rich Hickey improved this function and added it to boot.clj:

(defn drop-last
 "Return a lazy seq of all but the last n (default 1) items in coll"
  ([s] (drop-last 1 s))
  ([n s] (map (fn [x _] x) (seq s) (drop n s))))

and shared with us, mere mortals, a piece of wisdom:

I constantly have to remind myself to try to use a higher-order fn, because lazy-cons is so easy

From now on, I’ll try to question each lazy-cons.

0 Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

(c) 2017 Clojure and me | powered by WordPress with Barecity