在Clojure循环中追加到数组 [英] Appending to arrays in a Clojure loop

查看:94
本文介绍了在Clojure循环中追加到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图编写一个函数,将0和50之间的3和5的所有倍数加起来,但是Clojure似乎决定不告诉我正确的值。

I'm trying to write a function to add up all the multiples of 3 and 5 between 0 and 50, but Clojure seems determined not to add the correct values to my list when I tell it to.

(conj toSum计数器)表单应该将当前数字附加到toSum数组,并在循环退出(reduce + toSum)表单应该将数组中的所有内容加在一起。

The (conj toSum counter) form is supposed to append the current number to the toSum array, and when the loop exits the (reduce + toSum) form is supposed to add everything in the array together.

按现状,当调用 reduce 函数时, toSum 始终为空,因为 conj 函数未执行应做的工作。我肯定在某个地方搞砸了我的逻辑,但是我似乎无法弄清楚。

As it stands, when the reduce function is called, toSum is always empty because the conj function isn't doing what it's supposed to do. I must have screwed up my logic somewhere, but I can't seem to figure it out.

(defn calculate [target]
  (loop [counter target
         toSum []]
        (if (= 0 counter)
            (reduce + toSum)
          (if (or (= 0 (mod counter 3)) (= 0 (mod counter 5)))
              (do (conj toSum counter)
                  (println toSum)
                  (recur (dec counter) toSum))    
            (recur (dec counter) toSum)))))


推荐答案

conj 返回一个新集合,它不会对当前集合进行变异。您需要分配新的集合并重复以下操作:

conj returns a new collection, it does not mutate the current one in place. You need to assign the new collection and recur with that:

(let [nextSum (conj toSum counter)]
   (println nextSum)
   (recur (dec counter) nextSum))

这篇关于在Clojure循环中追加到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆