Overflow while using recur in clojure

前端 未结 1 897
无人及你
无人及你 2021-01-17 18:26

I have a simple prime number calculator in clojure (an inefficient algorithm, but I\'m just trying to understand the behavior of recur for now). The code is:



        
相关标签:
1条回答
  • 2021-01-17 19:19

    recur always uses tail recursion, regardless of whether you are recurring to a loop or a function head. The issue is the calls to remove. remove calls first to get the element from the underlying seq and checks to see if that element is valid. If the underlying seq was created by a call to remove, you get another call to first. If you call remove 20000 times on the same seq, calling first requires calling first 20000 times, and none of the calls can be tail recursive. Hence, the stack overflow error.

    Changing (remove ...) to (doall (remove ...)) fixes the problem, since it prevents the infinite stacking of remove calls (each one gets fully applied immediately and returns a concrete seq, not a lazy seq). I think this method only ever keeps one candidates list in memory at one time, though I am not positive about this. If so, it isn't too space inefficient, and a bit of testing shows that it isn't actually much slower.

    0 讨论(0)
提交回复
热议问题