Why should I use 'apply' in Clojure?

后端 未结 6 1881
执念已碎
执念已碎 2021-01-30 08:34

This is what Rich Hickey said in one of the blog posts but I don\'t understand the motivation in using apply. Please help.

A big difference between Clojur

6条回答
  •  你的背包
    2021-01-30 09:26

    Apply is useful with protocols, especially in conjunction with threading macros. I just discovered this. Since you can't use the & macro to expand interface arguments at compile time, you can apply an unpredictably sized vector instead.

    So I use this, for instance, as part of an interface between a record holding some metadata about a particular xml file and the file itself.

    (query-tree [this forms]
      (apply xml-> (text-id-to-tree this) forms)))
    

    text-id-to-tree is another method of this particular record that parses a file into an xml zipper. In another file, I extend the protocol with a particular query that implements query-tree, specifying a chain of commands to be threaded through the xml-> macro:

    (tags-with-attrs [this]
      (query-tree this [zf/descendants zip/node (fn [node] [(map #(% node) [:tag :attrs])])])
    

    (note: this query by itself will return a lot of "nil" results for tags that don't have attributes. Filter and reduce for a clean list of unique values).

    zf, by the way, refers to clojure.contrib.zip-filter, and zip to clojure.zip. The xml-> macro is from the clojure.contrib.zip-filter.xml library, which I :use

提交回复
热议问题