2012-11-22 1 views
1

다른 기호 예 : ('a'(고양이가 매트에 앉은 고양이)를 바꿉니다) ==> (고양이가 매트에 앉았습니다) 그래서 "는" rplaca 함수 사용

(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) 

내가 aligra에서 컴파일 할 때, "a"는 여기

내 코드로 대체해야 나에게 다음과 같은 오류

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

내가 돈을주고 틀림없이 rplace 함수가 두 개의 인수를 취하는 이유는 무엇입니까?

답변

2

코드에서 몇 가지 오류가 있습니다 괄호로 둘러싸는 안 있도록

  • item는 함수가 아닙니다
  • 원본과 같은 두 첫번째 인수를 반복해야합니다 귀하의 재귀 호출
  • 모든 경우에 재귀 호출을 수행해야합니다 (자동차를 교체 할 때만이 아님)
  • rplaca 호출과 관련하여 여분의 괄호가 있습니다. 이는보고 된 실제 원인입니다 댓글에서 언급 한 바와 같이 오류
    (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) 
    

    또한

, 리터럴을 음소거 것이 관례 아니다; 다음과 같이 새 목록을 구성하는 것이 좋습니다.

(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) 
+0

또한 리터럴은 불변이므로, 리터럴은 불변이므로 상상해보십시오. (귀하의 목록에 추가하기 만하면됩니다.) –