The lisp-way to solve Fibonnaci

前端 未结 14 1502
别那么骄傲
别那么骄傲 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条回答
  •  旧巷少年郎
    2021-02-08 08:04

    My understanding of "the spirit of lisp" is to detach yourself from any fixed, dogmatic, stuckup idea of the spirit of lisp, and use the lisp construct that most closely reflects the structure of computation required to solve your problem. For example,

    (defun euler2 (&optional (n 4000000))
      (do ((i 1 j)
           (j 2 (+ i j))
           (k 0))
          ((<= n i) k)
        (when (evenp i) (incf k i))))
    

    If you insist on recursion, here is another way:

    (defun euler2 (&optional (n 4000000))
      (labels ((fn (i j k) 
                 (if (<= n i) k (fn j (+ i j) (if (oddp i) k (+ k i))))))
        (fn 1 2 0)))
    

提交回复
热议问题