Stack overflow from recursive function call in Lisp

后端 未结 4 496
再見小時候
再見小時候 2020-12-31 16:38

I am learning Lisp from the book \"The Land of Lisp\" by Conrad Barski. Now I have hit my first stumbling block, where the author says:

Calling yourse

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-31 17:02

    Creating recursive functions to operate on recursive datastructures is indeed good for in lisp. And a list (in lisp) is defined as a recursive datastructure, so you should be ok.

    However, as you have experienced, if traversing a datastructure a million items deep using recursion, will also allocate a million frames on the stack, and you can expect a stack overflow unless you specifically ask your runtime environment to allocate huge amount of stack-space (I have no idea if or how you could do this in gnu clisp...).

    First of all, I think this shows that the list-datastructure isn't really a the best for everything, and in this case another structure might be better (however, you might not have come to vectors in your lisp-book yet ;-)

    Another thing is that for large recursions such as this to be effective, the compiler should optimise tail recursions and convert them into iterations. I don't know if clisp has this functionality, but you would need to change your function to actually be optimisable. (If "tail recursion optimisation" makes no sense, please let me know and I can dig up some references)

    For other ways of iterating, take a look at:

    • http://www.lispworks.com/documentation/HyperSpec/Body/c_iterat.htm
    • http://www.lispworks.com/documentation/HyperSpec/Body/06_a.htm

    Or other datastructures:

    • http://www.lispworks.com/documentation/HyperSpec/Body/t_vector.htm

提交回复
热议问题