let vs def in clojure

后端 未结 6 1778
日久生厌
日久生厌 2020-12-15 03:07

I want to make a local instance of a Java Scanner class in a clojure program. Why does this not work:

; gives me:  count not supported on this          


        
6条回答
  •  旧巷少年郎
    2020-12-15 03:27

    You could think of let as syntactic sugar for creating a new lexical scope with fn then applying it immediately:

    (let [a 3 b 7] (* a b))  ; 21
    ; vs.
    ((fn [a b] (* a b)) 3 7) ; 21
    

    So you could implement let with a simple macro and fn:

    (defmacro fnlet [bindings & body]
      ((fn [pairs]
        `((fn [~@(map first pairs)] ~@body) ~@(map last pairs)))
       (partition 2 bindings)))
    
    (fnlet [a 3 b 7] (* a b)) ; 21
    

提交回复
热议问题