The lisp-way to solve Fibonnaci

前端 未结 14 1685
别那么骄傲
别那么骄傲 2021-02-08 07:17

I wanted to try and learn Lisp, but I very quickly gave up. I figured I\'d try again. I\'m looking at Problem 2 on Project Euler - finding the sum of all even Fibonacci numbers

14条回答
  •  萌比男神i
    2021-02-08 07:59

    Use tail recursion instead of naive recursion. Most Lisp implementations should perform the tailcall-optimization; no more recursion depth limit.

    Beyond that, try to think of things in terms of lists and abstract operations you could perform on those lists. Two of the more relevant operations to consider:

    • filter
    • fold

    Regarding other Lisp resources:

    • Common Lisp—On Lisp
    • Scheme—Structure and Interpretation of Computer Programs

    UPDATE: Tail-recursive Scheme fib function:

    (define (fib n)
      (fib-tr n 1 0))
    
    (define (fib-tr n next result)
      (cond ((= n 0) result)
            (else (fib-tr (- n 1) (+ next result) next))))
    

提交回复
热议问题