Doesn't Matter
Doesn't Matter

Reputation: 405

using the rplaca function

I am trying to replace a symbol in a list with another symbol example: (replace 'the 'a '(the cat sat on the mat)) ==> (a cat sat on a mat) So the "the" should be replaced by "a"

Here is my code,

(defun replace (item new-item list)
 (cond ((null list)
          list
        ) 
       ((eq (first list) (item))
        ((rplaca list new-item)
         (replace (rest list))))
       ))
;rplace replace the first of the cons with obj
 ;(defparameter *some-list* (list* 'one 'two 'three 'four)) =>  *some-list*
 ;*some-list* =>  (ONE TWO THREE . FOUR)
 ;(rplaca *some-list* 'uno) =>  (UNO TWO THREE . FOUR)

When I compile it in aligra is giving me the following error

Error: Function position must contain a symbol or lambda expression: (RPLACA LIST NEW-ITEM)
[condition type: PARSE-ERROR]

I don't understand why is giving this error since the rplace function takes two arguments.

Upvotes: 1

Views: 513

Answers (1)

There are several different errors in your code:

  • item is not a function, so that you should not surround it with parentheses
  • your recursive call should repeat the same two first arguments as the original call
  • the recursive call should be made in all cases (and not only when the car was replaced)
  • you have extra parentheses around the rplaca call, which are the actual cause of the reported error
(defun replace (item new-item list)
  (cond ((null list)
         list) 
        ((eq (first list) item)
         (rplaca list new-item)
         (replace item new-item (rest list)))
        (t
         (replace item new-item (rest list)))))

(setq l '(a cat sat on a mat))
(replace 'a 'the l)
l ;; -> (the cat sat on the mat)

Also, as noted in comments, it is not customary to mute literals ; you might want to construct a new list instead, for example like this:

(defun replace-1 (item new-item list)
  (mapcar (lambda (car)
            (if (eq car item)
                new-item
              car))
          list))

(replace-1 'a 'the '(a cat sat on a mat))
;; -> (the cat sat on the mat)

Upvotes: 2

Related Questions