Why no destructing in def form?

后端 未结 4 2123
北恋
北恋 2021-02-18 20:10

In a let form (Clojure here) I can doing something like

(let [[u s v] (svd A)] 
   (do-something-with u v))

where svd

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-18 20:50

    This is not perfect but it is start on writing a def+ https://clojuredocs.org/clojure.core/destructure

    (defmacro def+
      "binding => binding-form
      internalizes binding-forms as if by def."
      {:added "1.9", :special-form true, :forms '[(def+ [bindings*])]}
      [& bindings]
      (let [bings (partition 2 (destructure bindings))]
        (sequence cat 
          ['(do) 
           (map (fn [[var value]] `(def ~var ~value)) bings)
           [(mapv (fn [[var _]] (str var)) bings)]])))
    

    With that you can do...

    (def+ [u s v] [1 5 9], foo "bar")
    

    ...while not compromising the simplicity of def...

    (def+ foo "bar")
    

    ...which is what was requested and suggested. This does still have the issue of introducing gensym variables into the global namespace. The gensym problem could be handled but given the use case (use in repl) the additional variables are probably acceptable.

提交回复
热议问题