The lisp-way to solve Fibonnaci

前端 未结 14 1486
别那么骄傲
别那么骄傲 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:09

    danio's answer will help greatly with the performance questions.

    Here's a short critic of your style:

     (defun fib(i)
       (if (= i 1) ;//Could rewrite this as a case statement
         1
         (if (= i 2)
           1
           (+ (fib (- i 1)) (fib (- i 2)))
         )
       )
     )
    

    Refactor nested IFs into a COND.

    Don't put parentheses on a line by themselves.

     (defun solve(i)
       (let ((f (fib i))) ;//Store result in local variable
         (print f) ;//For debugging
         (if (
    
    

    Using ZEROP is clearer.

             (+ f (solve (+ i 1))) ;//add number
             (solve (+ i 1)) ;//Don't
    

    Why do you put those // in? A semicolon followed by a space is enough.

    ) ) ) ) (print (solve 1))

    You last PRINT statement makes me a bit suspicious. Are you running this program from a file or from the REPL? If you do the former then you should consider doing the latter. If you do the latter you can just say (solve 1) to get the result.

提交回复
热议问题