Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lisp list iteration

I have a function that gets x(a value) and xs(a list) and removes all values that are bigger than x from the list. Well it doesn't work, can you tell me why?

(defun biggerElems(x xs) 
  (let ((xst))
    (dolist (elem xs)
      (if (> x elem)
          (setf xst (remove elem xs))))
    xst))
like image 219
Alexander Stolz Avatar asked Dec 17 '22 10:12

Alexander Stolz


2 Answers

I think it's this line that's not right:

(setf xst (remove elem xs))))

The first argument to setf is the place, followed by the value. It looks like you have it backwards (and xst is either nil or uninitialized).

You might find it easier to do this:

(defun biggerElems (x xs)
  (remove-if (lambda (item) (> item x)) xs))
like image 66
Ben Collins Avatar answered Jan 13 '23 17:01

Ben Collins


Most concise AFAIK:

(defun bigger-elements (x xs) (remove x xs :test #'<))

returning a fresh list, it removes all elements y from xs for which

(< y x)

or using the famous LOOP:

(defun bigger-elements-2 (x xs) 
  (loop for e in xs
        unless (< e x)
        collect e))
like image 29
Bart Avatar answered Jan 13 '23 18:01

Bart