1

我刚开始在课堂上学习 lisp。我正在做一个家庭作业,其中我必须使用一些基本操作来编写一些非常基本的函数,例如 car、cdr、cons、append、reverse、atom、eq、equal 和 null。

所以这是我到目前为止的代码:

(defun union2 (l1 l2)
  (cond ((null l1) l2)
        ((member((car l1) l2)) (union2((cdr l1) l2)))
        (t (cons (car l1) (union2((cdr l1) l2)))))
  )

当我尝试运行测试时:

(union2 '(5 7 2 3 1) '(3 2 4 6 9))

我收到“错误:非法函数对象:(汽车 l1)”。我的印象是我正确地编写了代码。我究竟做错了什么?感谢您的时间。

4

2 回答 2

3

不要在参数列表周围加上额外的括号。

  • (member((car l1) l2))应该(member (car l1) l2)
  • (union2((cdr l1) l2))应该(union2 (cdr l1) l2)
于 2012-11-03T22:50:44.377 回答
1

尝试使用编译器,例如 SBCL:

* (defun union2 (l1 l2)
  (cond ((null l1) l2)
        ((member((car l1) l2)) (union2((cdr l1) l2)))
        (t (cons (car l1) (union2((cdr l1) l2)))))
  )
; in: DEFUN UNION2
;     ((CAR L1) L2)
; 
; caught ERROR:
;   illegal function call

;     (MEMBER ((CAR L1) L2))
; 
; caught WARNING:
;   The function was called with one argument, but wants at least two.

;     ((CDR L1) L2)
; 
; caught ERROR:
;   illegal function call

;     (UNION2 ((CDR L1) L2))
; 
; caught WARNING:
;   The function was called with one argument, but wants exactly two.

;     ((CDR L1) L2)
; 
; caught ERROR:
;   illegal function call

;     (UNION2 ((CDR L1) L2))
; 
; caught WARNING:
;   The function was called with one argument, but wants exactly two.
; 
; compilation unit finished
;   caught 3 ERROR conditions
;   caught 3 WARNING conditions
于 2012-11-03T21:41:36.060 回答