获取执行错误(StackOverflowError)时,求值的函数范围较大



在这个过程中我正在学习Clojure和解决SICP书中的练习。当评估(search-for-primes 1001 10000)时,我得到这个错误,但当调用较小的值(search-for-primes 101 1000)时,它工作得很好。

这似乎是一个内存问题,但我无法在它的原因归零。非常感谢你的帮助。谢谢你!代码如下:

(defn square [x]
(* x x))
(defn divides? [a b]
(= (rem b a) 0))
(defn find-divisor [n test-divisor]
(cond
(> (square test-divisor) n) n
(divides? test-divisor n) test-divisor
:else (find-divisor n (+ test-divisor 1))))
(defn smallest-divisor [n]
(find-divisor n 2))
;;return true if prime
(defn prime? 
[n]
(= n (smallest-divisor n)))
;;return the first of the three consecutive prime numbers
(defn search-for-primes [low high]
(if (< low high) 
(cond 
(and (prime? low) (prime? (+ low 2)) (prime? (+ low 4))) low 
:else (search-for-primes (+ low 2) high))))

你没有显示你得到的实际错误,但我猜它与堆栈溢出有关。

与Scheme不同,Clojure不支持尾部调用消除,因此您可能需要查看loop/recur,例如参见https://clojuredocs.org/clojure.core/loop。

最新更新