Let inside

I work with clojure, and while I was doing this with lisps, I was having trouble finding a clean way to nest expressions in cond expressions. For example, consider the following function:

(defn operate-on-list [xs]
  (let [[unpack vector] (first xs)]
    (cond
      [(empty? xs) 'empty
       unpack vector
       :else (operate-on-list (rest xs))])))

This is a pretty standard recursive operation in a list, but it needs to do some work on the first element in the list before it works with the contents. The problem, of course, is that the list may be empty.

In this example, it's easy to change unpackto ((first xs) 0)and vectorto ((first xs) 1), but it quickly gets ugly if more work is required (xs first).

Is there a way to efficiently use the let statement with cond?

Thanks.

-Nate

+5
source share
3

if-let:

(defn operate-on-list [xs]
  (if-let [[unpack v] (first xs)]
    (cond
      unpack v
      :else  (operate-on-list (rest xs)))))

list seq-able (, , ...) , true ( false nil). nil , .

, vector , v , , . , cond; .

. , if-let:

  • if-let, (first xs) nil (false ), , Clojure nil [unpack v].

  • , if-let else ( , if-let), , else, , false nil).

+11

    ;use conditional let: http://richhickey.github.com/clojure-contrib/cond-api.html

    (use 'clojure.contrib.cond)

    (cond-let [b]  
      nil  b
      12  (prn (+ b 1))
      :else 17 )

    ;==> 13
    

http://www.mail-archive.com/clojure@googlegroups.com/msg03684.html

+3

, let cond?

(defn operate-on-list [list]
  (let [ el_first (first list) ]
    (cond
      (nil? el_first) (println "Finished")
      :else (do 
       (let [ list_rest (rest list) ]
                (println el_first)  
                (operate-on-list list_rest))))))

(operate-on-list '(1 2 3))

:

1
2
3
Finished
+2

All Articles