The lisp-way to solve Fibonnaci

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

    (let ((a 1) (b 1))
      (flet ((nextfib ()
               (prog1 a
                 (psetf a b b (+ a b)))))
        (loop for fib = (nextfib)
              while (<= fib 4000000)
              when (evenp fib)
                sum fib)))
    

    Above defines a function NEXTFIB which will generate the next fibonacci number for each call. The LOOP sums the even results upto the limit of 4000000.

    PROG1 returns the value of the first of its subexpressions. PSETF sets a and b in 'parallel'.

    That's a common pattern. There is a generator function and one calls it repeatedly, filters the results and combines them.

提交回复
热议问题