gpt4 book ai didi

clojure - 在箭头运算符内切换

转载 作者:行者123 更新时间:2023-12-02 22:31:32 24 4
gpt4 key购买 nike

我正在学习 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 方式?

谢谢。

最佳答案

箭头宏 (->) 只是重写了它的参数,以便将第 n 个形式的值作为第一个参数插入到第 n+1 个形式中。你写的等同于:

(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 上的常量。这可以通过 map 来完成。考虑以下几点:

(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 的数据结构来表达它。此外,线程宏的真正值(value)在于帮助您编译 xpath。不要害怕为您正在使用的数据提供局部范围的名称,以帮助您跟踪您正在做的事情。它还可以帮助您避免尝试将真正不想适应的东西硬塞进线程宏中。

关于clojure - 在箭头运算符内切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12167060/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com