我不明白使用中有哪些优点或缺点let,因为可以避免在下面的代码中使用let?
(defn make-adder [x]
(let [y x]
(fn [z] (+ y z))))
(def add2 (make-adder 2))
;; or without let
(defn add2 [z] (+ 2 z))
(add2 4)
Run Code Online (Sandbox Code Playgroud)
命名中间结果有三个主要原因:
let-ed名称,但不会将其发送给外部世界.在您的make-adder示例中,没有真正需要,let因为它只是为传入参数建立别名.但如果你有更多的东西参与,那么这些优势开始变得相关.
仅仅因为我有它,这里是我最近另一个答案的一些代码:
(defn trades-chan
"Open the URL as a tab-separated values stream of trades.
Returns a core.async channel of the trades, represented as maps.
Closes the HTTP stream on channel close!"
[dump-url]
(let[stream (-> dump-url
(client/get {:as :stream})
:body) ;;This is an example of 3.
lines (-> stream
io/reader
line-seq)
;; This is an example of 2. I don't want to make multiple readers just because I use them in multiple expressions.
;;fields and transducer are examples of 1.
fields (map keyword (str/split (first lines) #"\t"))
transducer (map (comp #(zipmap fields %) #(str/split % #"\t")))
;;output-chan is another example of 2
output-chan (async/chan 50 transducer)]
(async/go-loop [my-lines (drop 1 lines)]
(if (async/>! output-chan (first my-lines))
(recur (rest my-lines))
(.close stream))) ;;Here, the closure closes the HTTP stream, so it needs a name to refer to it by.
output-chan))
Run Code Online (Sandbox Code Playgroud)