Apologies if this is a beginner question. Harsh comments are welcome. I am learning LISP and got a snippet like the below. It checks a constant value in a list and returns only the elements greater than it.
(defun greaterthanX (l)
(if l
(if (> (car l) 5)
(cons (car l) (greaterthanX (cdr l)))
(greaterthanX (cdr l))
)
)
)
(print(greaterthanx '(1 2 3 4 5 6 7 8 3)))
Output : (6 7 8)
My question is how do I pass a variable inside the recursive function and modify it instead of passing a constant value (ie. 5 in the above case)?
I am looking for something like this :
(defun greaterthanX (x l)
(if l
(if (> (car l) x)
(cons (car l) (greaterthanX (cdr l)))
(greaterthanX (cdr l))
)
)
)
(print(greaterthanx '5 '(1 2 3 4 5 6 7 8 3)))
you would additionally pass the x
value in the two recursive calls to greaterthanX
:
CL-USER 5 > (defun greater-than-x (x l)
(if (consp l)
(if (> (first l) x)
(cons (first l)
(greater-than-x x (rest l)))
(greater-than-x x (rest l)))))
GREATER-THAN-X
CL-USER 6 > (print (greater-than-x 5 '(1 2 3 4 5 6 7 8 3)))
(6 7 8) ; printed
(6 7 8) ; repl output