Clojure无限循环噩梦

Clojure无限循环噩梦,clojure,Clojure,我已经用noisesmith注释更新了下面的代码(除了格式我不知道应该是什么 其思想是,给定一个向量[2 8 4 0],它最终将返回[8 8 n],其中n是获得该结果所需的递归量。其中前3个输入是偶数。前3个输入可以是任意偶数自然数。 让我举一个例子: (adjustedCandyAmounts [12 4 24 1]) [18 8 18 2] So know I iterate (recur... i guess) (adjustedCandyAmounts [18 8 18 3]) [18

我已经用noisesmith注释更新了下面的代码(除了格式我不知道应该是什么

其思想是,给定一个向量[2 8 4 0],它最终将返回[8 8 n],其中n是获得该结果所需的递归量。其中前3个输入是偶数。前3个输入可以是任意偶数自然数。

让我举一个例子:

(adjustedCandyAmounts [12 4 24 1]) [18 8 18 2] So know I iterate (recur... i guess) (adjustedCandyAmounts [18 8 18 3]) [18 14 18 4] recur... (adjustedCandyAmounts [18 14 18 3]) [18 16 18 4] Finally we reach our condition... (adjustedCandyAmounts [18 16 18 4]) [18 18 18 5] At this point the if statement should kick in.. So techniquely i just want to see a different paramater (vector) to adjustedCandyAmounts until the condition is met.
您的终止条件是奇数。
(=(第n个电流0)(第n个电流1)(第n个电流2)2)
表示您正在测试当前
的前三个元素是否都等于2

myLoopFunc
中,您将迭代
AdjustedCandyMounts
,直到输出为
[2 n]
(您不测试第四个值)。如果以
[4 n]
作为参数调用
AdjustedCandyMounts
,它将返回
[4 n+1]
。此输入无法使代码达到您的终止条件

递归的一般思想是,必须有某个参数保证接近结束条件。例如,您可以有一个在每个周期递减的数字,当它达到0时停止,或者您可以有一个变短的序列,当它为空时停止。此代码无限期运行,因为无法达到终止条件

最后,关于风格的几点:

请使用标准排列、注释排列、空格和缩进。您现在的格式很难阅读

在上下文中,
(into[](flatten(vector a b c d))
只是一种低效且难以阅读的书写方式
[a b c d]


(conj[]current)
最好写成
[current]

关于您对
recur
的评论-您在谈论第二个参数是什么?您的代码中没有任何参数超过一个。您是否误解了
循环的语法?
?这是代码的早期版本。我删除了注释。现在有一个示例说明了调整后的CandyMounts是如何满足的这是条件,但我仍然得到无限循环。它必须是数据结构。([current])应该是[current]-额外的参数将导致异常。if条件现在肯定是错误的。我还将对向量进行调整。is(n次电流0)(n次电流1)(n次电流2)每次迭代更新值还是保持不变?我需要每次迭代都更改它。我还必须从if条件中删除2。
(
  defn calcAdjusted [[candyOwned adjacentCandy]]
  (let [TotalCandy (+ 
                     (quot candyOwned 2) ; i had to give half of my candies to someone else
                     (quot adjacentCandy 2); i receive half of someone elses candy
                    )] 
    (if (odd? TotalCandy)
       (+ TotalCandy 1);"Yes is an odd" 
       TotalCandy     ;"is not an odd number"
    )
  )

 )
(defn adjustedCandyAmounts [[r s t u]]
  (let 
       [
        rUpdated (calcAdjusted [r t]); r receives half of what t owns
        sUpdated (calcAdjusted [s r]); s receives half of what r owns
        tUpdated (calcAdjusted [t r]); t receives half of what s owns
        counterIncremented (inc u) 
       ]
      ; (println rUpdated)
       (vector rUpdated sUpdated tUpdated counterIncremented )
  )

)


(defn myLoopFunc [[r s t u]]
 (
     let [candyInitial [r s t u]]
     (
        loop [ current candyInitial]
        (

           if (= (nth current 0) (nth current 1) (nth current 2) )   
           [current]
           (recur (adjustedCandyAmounts current)) ; 

        )
    )

 )
)