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.

Lazier than lazy

utilities — cgrand, 23 June 2008 @ 20 h 47 min

If you can’t put off what you have to do, ask someone else to do it for you.

(defn off
 "Computes a lazy-seq in another (dedicated) thread."
 [s]
  (let [ex (. java.util.concurrent.Executors newSingleThreadExecutor)]
    ((fn this [s]
       (if s 
         (let [future-rest (java.util.concurrent.FutureTask. #(rest s))]
           (.execute ex future-rest)
             (lazy-cons (first s) (this (.get future-rest))))
         (.shutdown ex))) s)))

Jumping to Javadocs from the REPL

utilities — cgrand, 28 May 2008 @ 17 h 29 min
(defn open-url [url]
  (let [htmlpane (new javax.swing.JEditorPane url)]
    (.setEditable htmlpane false)
    (.addHyperlinkListener htmlpane
      (proxy [javax.swing.event.HyperlinkListener] []
        (hyperlinkUpdate [#^javax.swing.event.HyperlinkEvent e]
          (when (= (.getEventType e) (. javax.swing.event.HyperlinkEvent$EventType ACTIVATED))
            (if (instance? javax.swing.text.html.HTMLFrameHyperlinkEvent e)
              (.. htmlpane getDocument (processHTMLFrameHyperlinkEvent e))
              (try
                (.setPage htmlpane (.getURL e))
                (catch Throwable t
                               (.printStackTrace t))))))))
    (doto (new javax.swing.JFrame)
      (setContentPane (new javax.swing.JScrollPane htmlpane))
      (setBounds 32 32 700 900)
      (show))))

(defn javadoc [c]
  (let [url (str "http://java.sun.com/javase/6/docs/api/"
              (.. c getName (replace \. \/) (replace \$ \.)) ".html")]
    (open-url url)))

; usage:
; (javadoc Throwable) opens a window displaying Throwable's javadoc 
; hint: (javadoc (class some-object))
« Previous Page
(c) 2017 Clojure and me | powered by WordPress with Barecity