3

I am trying to create a function where it takes a list of letters as parameter and a single letter as a parameter. I want to remove the single letter from the list.

(defun extract-all (lett li)
   (let ((new-list nil))
     (dolist (letter li new-list)
        (if (eql lett letter)
             (setf new-list (cons nil new-list))
          (setf new-list (cons letter new-list))))))

so if I call the function with (extract-all 'n '(i n t e l l)), I want it to return i t e l l with the n removed.

KB_Shayan
  • 632
  • 8
  • 24

1 Answers1

4

First of all, you are not removing letters (characters), but rather symbols:

(type-of 'n)
==> SYMBOL

Second, there is a standard function remove to do just that:

(remove 'n '(i n t e l l))
==> (I T E L L)

Third, if you remove your "then" clause and reverse the result, you will get what you want:

(defun my-remove (object list)
  (let ((new-list nil))
    (dolist (element list (nreverse new-list))
      (unless (eql object element)
        (push element new-list)))))
(my-remove 'n '(i n t e l l))
==> (I T E L L)

Note that there are more ways to skin the cat, e.g.,

(defun my-remove (object list)
  (loop for element in list
    unless (eql object element)
    collect element))

However, it is always best to use the library.

See also Where to learn how to practically use Common Lisp.

sds
  • 58,617
  • 29
  • 161
  • 278
  • What is the purpose of unless? is it some kind of else? – KB_Shayan Jan 09 '18 at 15:19
  • Which `unless`? [this](http://clhs.lisp.se/Body/m_when_.htm) or [this](http://clhs.lisp.se/Body/06_af.htm)? – sds Jan 09 '18 at 15:33
  • So what is the question? why does CL have if, cond, when and unless? or what do they do? these are reasonable questions, please ask them separately! – sds Jan 09 '18 at 15:45