Clojure 开关内部箭头操作器
我在学clojure。我的问题是是否可以在(->)中使用(case)。 例如,我想要这样的东西(此代码不起作用): 还是改用多种方法更好?什么是正确的clojure方式 谢谢。箭头宏(->)只是重写了它的参数,以便将第n个形式的值作为第一个参数插入到第n+1个形式中。你所写的内容相当于:Clojure 开关内部箭头操作器,clojure,Clojure,我在学clojure。我的问题是是否可以在(->)中使用(case)。 例如,我想要这样的东西(此代码不起作用): 还是改用多种方法更好?什么是正确的clojure方式 谢谢。箭头宏(->)只是重写了它的参数,以便将第n个形式的值作为第一个参数插入到第n+1个形式中。你所写的内容相当于: (case (.compile (.newXPath (XPathFactory/newInstance)) xpath) return-type :node-list (
(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
,提前选择三种形式中的一种作为尾部形式,然后在threading宏的末尾将其线程化。像这样:
(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。不要害怕提供您正在使用的本地范围名称的数据,以帮助您跟踪您正在做的事情。它还可以帮助您避免将不适合的内容硬塞进线程宏中。查看以下clojure库,了解如何使用xpath表达式:
(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)))))