Lisp void variable error when evaluating a function

I'm trying to learn Lisp (elisp, actually) and I tried to write the following function as a project Euler exercise Problem 2

(defun sumfib (n fn1 fn2 sum)
  "Calculate Fibonacci numbers up to 4,000,000 and sum all the even ones"
  (if (< 4000000 (+ fn1 fn2))
      sum
    (if (equal n 3)
        (sumfib 1 (+ fn1 fn2) fn1 (+ sum (+fn1 fn2)))
      (sumfib (+ n 1) (+ fn1 fn2) fn1 sum)))

When I evaluate it, I get the following error:

Debugger entered--Lisp error: (void-variable fn1)
  (+ fn1 fn2)
  (< 4000000 (+ fn1 fn2))
...

Why not recognize fn1? If I try to put (+ fn1 fn2) before "if", it doesn't complain about it, so why is there a mistake?

In addition, I understand that the function cannot actually be correct, but for now, the logic does not bother me - I will find out later. At the moment, I am only interested in this error.

+3
source share
2 answers

, ( elisp), . "" "sum".

  (if (< 4000000 (+ fn1 fn2))
      sum)

:

 (if (< 4000000 (+ fn1 fn2))
      sum

, .

+2
  • .
  • , : (+fn1 fn2) (+ fn1 fn2). ELisp fn2 +fn1.

:

  • A cond , ifs, ELisp.
  • = - , , equal. equal , . ( , Lisp, , , ELisp .)

.

(defun sumfib (n fn1 fn2 sum)
  "Calculate Fibonacci numbers up to 4,000,000 and sum all the even ones"
  (cond 
    ((< 4000000 (+ fn1 fn2)) sum)
    ((= n 3) (sumfib 1 (+ fn1 fn2) fn1 (+ sum (+ fn1 fn2))))
    (t (sumfib (1+ n) (+ fn1 fn2) fn1 sum))))

, , , .

+4

Source: https://habr.com/ru/post/1716548/


All Articles