Search code examples
lispcommon-lispclisp

Need help understanding an error (F3 '(6 3 4 1)) is not a real number Lisp code


This is my lisp code. I’m trying to solve this problem:

Define function f3 that takes a simple list of integers as an argument and returns the number (count) of integers in the list which are between -3 and +15 (-3 and +15 included). For example:

LISP> (f3 '(1 -2 17 -4))
2

This is my take on the problem and I’m stuck. I don't know what I’m doing wrong.

(defun f3 (x)
  (if (null x)
      0
    (if (>(car x) - 3) 
        (if (<(car x) 15)
            (+ 1(f3 (cdr x)))
          (f3 (cdr x))
          (f3 (cdr x))))))

Solution

  • You don't have enough parentheses after the second (f3 (cdr xx)). As you can see when the code is properly indented, that puts the last 2 recursive calls inside the same if; the last one was supposed to be in the previous if.

    But there's no need for separate if expressions for -3 and 15. You can combine the tests with and, or take advantage of the fact that it's the same comparison for both endpoints and use (<= -3 (car x) 15). Note also that the question says that the endpoints are included, so you should use <= rather than <.

    Finally, there shouldn't be a space between - and 3. I suspect that was just a copying error, since you would have gotten a different error in that case.

    (defun f3 (x)
      (if (null x)
          0
        (if (<=  -3 (car x) 15)
            (+ 1 (f3 (cdr x)))
          (f3 (cdr x)))))