在更大范围的值上评估函数时出现执行错误(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。


以上是在更大范围的值上评估函数时出现执行错误(StackOverflowError)的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>