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
.
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)))
(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))