clojure - 如何使用 if-let 中的嵌套 let 编写一次函数调用?

标签 clojure

我有这些功能:

(def i (atom {})) ;incremented/calculated file stats

(defn updatei [n fic fos]
  (swap! i conj {(keyword n)[fic fos]}))

(defn calcfo [fo fi fis]
  (if-let [n (get @i fo)] ;find a previous record?
    (let [fic (inc (first n)), fos (+ fis (second n))] ;increment the stats
      (updatei fo fic fos))
    (let [fic 1, fos fis] ;if not then: first calc recorded
      (updatei fo fic fos))))

如何编写 (updatei fo fic fos) 一次,而不是在函数中列出两次?难道有什么 secret 或者让我不知道的吗?

-假设代码-

(defn calcfo [fo fi fis]
  (if-let [n (get @i fo)] ;find a previous record?
    (let [fic (inc (first n)), fos (+ fis (second n))] ;increment the stats
    (or-let [fic 1, fos fis] ;if not then: first calc recorded
      (updatei fo fic fos)))))

或者我是否过于强制而不是功能性地考虑这个问题?

编辑:

我认为这对我来说最有意义:

(defn calcfo [fo fis]
  (apply updatei fo
  (if-let [[rfc rfos] (get @i fo)] ;find a previous record?
       [(inc rfc) (+ rfos fis)] ;increment the stats
       [1 fis]) ;if not then: first calc recorded
      ))

感谢您的精彩解答!

最佳答案

重新安排可能会有所帮助

(defn calcfo [fo fi fis]
  (apply updatei fo
    (if-let [n (get @i fo)]
      [(inc (first n)), (+ fis (second n))]
      [1, fis] )))

关于clojure - 如何使用 if-let 中的嵌套 let 编写一次函数调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17578805/

相关文章:

clojure - 你能扩展一个类型/记录来实现 Clojure 中的 str 函数吗?

clojure - 如何使用 core.async channel 对 Rx 的 `withLatestFrom` 进行建模?

c++ - 您将如何在 Clojure 中编写此 C++ 循环?

functional-programming - Clojure:如何在运行时找出函数的数量?

clojure - 您如何列出 Leiningen 模板的选项?

clojure - 如何将 Clojure 命名空间转换为字符串?

clojure - 更新原子/范围

clojure - gen-class 不生成类

clojure - 在 Clojure 向量中查找类似正则表达式的值序列

file - 使 Clojure 识别并隔离文件中的行