ObiJuanKanobe
ObiJuanKanobe

Reputation: 45

How to move an element in a list to the front of the list in LISP

I am trying to check if a word is an element of a list. It it isn't then add the word to the front of the list, but if it is move that word to the front of the list. I am able to add the word to the list if it isn't already there, but I don't know how to the move the element to the front of the list if it is in the list already. Here is my code:

(defun movetofront (word lst)
  (cond
    ((member word lst) 
     (remove word lst))
    (T (cons word lst)))) 

Upvotes: 2

Views: 996

Answers (1)

sds
sds

Reputation: 60014

You do not have to check for the presence:

(defun move-to-front (word list)
   (cons word (remove word list)))

Note that if word is, e.g., a string, you will need to pass :test to remove.

Upvotes: 6

Related Questions