collections – 将org.w3c.dom.NodeList转换为Clojure ISeq
发布时间:2020-12-16 05:35:26 所属栏目:百科 来源:网络整理
导读:我正在尝试处理新的defprotocol,reify等. 我有一个从XPath调用返回的org.w3c.dom.NodeList,我想将它“转换”为一个ISeq. 在Scala中,我实现了一个隐式转换方法: implicit def nodeList2Traversable(nodeList: NodeList): Traversable[Node] = { new Traversa
我正在尝试处理新的defprotocol,reify等.
我有一个从XPath调用返回的org.w3c.dom.NodeList,我想将它“转换”为一个ISeq. 在Scala中,我实现了一个隐式转换方法: implicit def nodeList2Traversable(nodeList: NodeList): Traversable[Node] = { new Traversable[Node] { def foreach[A](process: (Node) => A) { for (index <- 0 until nodeList.getLength) { process(nodeList.item(index)) } } } } NodeList包括方法int getLength()和Node item(int index). 我如何在Clojure中做相同的操作?我希望我需要使用defprotocol.我需要定义哪些函数来创建seq? 如果我使用循环和重复进行简单,天真的转换到列表,我将得到一个非惰性结构. 解决方法
Clojure的大多数序列处理函数都返回lazy seqs,包括map和range函数:
(defn node-list-seq [^org.w3c.dom.NodeList node-list] (map (fn [index] (.item node-list index)) (range (.getLength node-list)))) 请注意,上面的NodeList类型提示不是必需的,但可以提高性能. 现在您可以像这样使用该功能: (map #(.getLocalName %) (node-list-seq your-node-list)) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |