有没有更干净的方法来编写这个循环、更新和返回映射的Clojure函数?
此函数可以工作,但我正在学习Clojure,我想知道是否有更好/更简洁的方法来编写此函数:有没有更干净的方法来编写这个循环、更新和返回映射的Clojure函数?,clojure,Clojure,此函数可以工作,但我正在学习Clojure,我想知道是否有更好/更简洁的方法来编写此函数: ;; loop over methods, update the scripts map, and return scripts (defn update-scripts [filename] (loop [scripts {} methods (get-methods filename)] (if (seq methods) (let [method (f
;; loop over methods, update the scripts map, and return scripts
(defn update-scripts
[filename]
(loop [scripts {}
methods (get-methods filename)]
(if (seq methods)
(let [method (first methods)
sig (get-method-signature method)
name (get-method-name sig)]
(recur (assoc scripts name {:sig sig, :method method})
(rest methods)))
scripts)))
(update-scripts "gremlin.groovy")
更新:以下是我最终使用的:
(defn- update-scripts
[scripts method]
(let [sig (get-method-signature method)
name (get-method-name sig)]
(assoc scripts name {:sig sig :method method})))
(defn get-scripts
[filename]
(reduce update-scripts {} (get-methods filename)))
我会这样做,减少如下:
(defn update-scripts
[filename]
(reduce (fn [scripts method]
(let [sig (get-method-signature method)
name (get-method-name sig)]
(assoc scripts name {:sig sig :method method})))
{}
(get-methods filename)))
当我必须获取一个集合并返回一个不同类型的集合时,我会遵循这一“模式”。这里我们有一个方法列表,我们希望将这个列表转换成一个映射(在对它进行一些处理之后)。我觉得reduce是最具可读性的方法。我会使用
map
为get方法返回的每个条目构建一个哈希映射,然后将所有这些哈希映射合并为一个
(defn update-scripts
[filename]
(apply merge
(map
#(hash-map (get-method-name %) {:sig (get-method-signature %) :method %})
(get-methods filename))))
一般来说,最好使用标准的序列操作函数,如map
,filter
等,而不是循环
,谢谢@vedang——在阅读了您的答案后,我学习了关于reduce
的本教程:
(defn update-scripts
[filename]
(into {} (map (fn [m] [ (get-method-name (get-method-signature m)) {:sig (get-method-signature m), :method m} ] ) (get-methods filename) )))