Search code examples
functionlispcommon-lisp

Common Lisp - Function that builds, from a list of numbers, the list of more, smaller or equal to a given number


I having trouble with this function, I would like a function which returns a list of number inferior for a given a number.

What I did so far,

(defun inf (n l)
(cond
((not l) 0)
((>= n (car l))(cons n (inf n(cdr l))))
(cons (car l) (inf n (cdr l))) ))

But it keeps returns

(inf 12 '(12 5 3))
(12 12 10)

Instead of :

(inf 12 '(12 5 3 53 45))
(12 5 3)

What did I miss ?


Solution

  • A not-so-obvious way to solve the same problem using Common Lisp's existing functions is to pass a comparison operator to REMOVE.

    (remove 10 '(0 3 5 11 22 10 22 3 2) :test #'<)
    

    The above removes all elements "equal" to 10 according to #'<, which are thus all elements u such that (< 10 u) holds. In other words, all elements strictly above 10:

    (0 3 5 10 3 2)
    

    It turns out that there is an example of this in the section linked above:

    (remove 3 '(1 2 4 1 3 4 5) :test #'>) =>  (4 3 4 5)
    

    Edit: since this is now the accepted answer, note also that this approach is probably hard to read, be careful when using it (add a comment, etc.).