我正在学习clojure。我的问题是在(-> )中使用(case)是可能的吗?例如,我想要这样的代码(这个代码不能工作):
(defn eval-xpath [document xpath return-type]
(-> (XPathFactory/newInstance)
.newXPath
(.compile xpath)
(case return-type
:node-list (.evaluate document XPathConstants/NODESET)
:node (.evaluate document XPathConstants/NODE)
:number (.evaluate document XPathConstants/NUMBER)
)
))或者使用多方法会更好呢?什么是正确的“clojure”方式?
谢谢。
发布于 2012-08-29 05:02:43
箭头宏(->)只是重写其参数,以便将第n个表单的值作为第一个参数插入到n+1th表单中。您正在编写的内容相当于:
(case
(.compile
(.newXPath (XPathFactory/newInstance))
xpath)
return-type
:node-list (.evaluate document XPathConstants/NODESET)
:node (.evaluate document XPathConstants/NODE)
:number (.evaluate document XPathConstants/NUMBER)在一般情况下,您可以使用let提前选择三种形式中的一种作为尾式形式,然后在线程宏末尾将其插入。如下所示:
(defn eval-xpath [document xpath return-type]
(let [evaluator (case return-type
:node-list #(.evaluate % document XPathConstants/NODESET)
:node #(.evaluate % document XPathConstants/NODE)
:number #(.evaluate % document XPathConstants/NUMBER))]
(-> (XPathFactory/newInstance)
.newXPath
(.compile xpath)
(evaluator))))但是,您真正想要做的是将关键字映射到XPathConstants上的常量。这可以通过一张地图来完成。请考虑以下几点:
(defn eval-xpath [document xpath return-type]
(let [constants-mapping {:node-list XPathConstants/NODESET
:node XPathConstants/NODE
:number XPathConstants/NUMBER}]
(-> (XPathFactory/newInstance)
.newXPath
(.compile xpath)
(.evaluate document (constants-mapping return-type)))))您有一个关键字到常量的映射,所以使用Clojure的数据结构来表示。此外,线程宏的真正价值在于帮助您编译xpath。不要害怕使用本地作用域名称提供数据,以帮助您跟踪正在执行的操作。它还可以帮助您避免尝试将不想适应的东西硬塞到线程宏中。
发布于 2012-11-14 22:48:37
查看以下用于处理xpath表达式的clojure库:https://github.com/kyleburton/clj-xpath
https://stackoverflow.com/questions/12167060
复制相似问题