Reputation: 289
I made a program in Common Lisp and I am trying to make it work in Scheme as well, but it is not working. I am new to Scheme and MIT/GNU Scheme. Here is the code in Common Lisp. It is working fine in Lispworks:
(defun removeAdjc (L) (cond ((null L) L)
(t (cond ((equal (car L) (cadr L)) (removeAdjc (cdr L)))
(t (append (list (car L)) (removeAdjc (cdr L))))))))
Here is the code that I used for Scheme:
(define (removeAdjc L)
(if (null? L) L
(if (equal? (car L) (cadr L)) (removeAdjc (cdr L))
(append (list (car L)) (removeAdjc (cdr L)))
) ))
This is what I get when trying it on MIT/GNU Scheme:
Upvotes: 1
Views: 898
Reputation: 27404
The reason of the error is that you check only the end of the list, with (null? L)
, while you should check also if the list has one element (since you are doing (cadr L)
). So a correct definition could be:
(define (removeAdjc L)
(cond ((null? L) L)
((null? (cdr L)) L)
((equal? (car L) (cadr L)) (removeAdjc (cdr L)))
(else (cons (car L) (removeAdjc (cdr L))))))
Note that in Common Lisp (cadr nil)
returns nil
, and this is the reason for which the error does not appear in that language.
Upvotes: 9
Reputation:
In Common Lisp, it is legal to take the car
and cdr
of ()
(aka nil
): (car '())
is ()
and similarly for cdr
. This is not the case in Scheme. In particular, in your code, you're trying to take the cadr
of something without first checking whether the cdr
is ()
: you need to check for that.
Upvotes: 4