1
votes
(define (create-polygon ptlist)
  (if (null? ptlist) 0
      (append (list (make-seg (car ptlist) (cadr ptlist))) (create-polygon (cdr ptlist)))))

My problem is whenever I try to run this program it gives contract violation error. I know that you can't car or cdr empty lists but I'm checking if it's empty or not. So what is the problem here?

1

1 Answers

1
votes

Consider the following:

(define lst '(1))

(null? lst)
=> #f

(cadr lst)
=> cadr: contract violation

As you can see, the contract violation occurs because (null? lst) only checks whether the list is currently empty. But if you use cadr, which is (car (cdr lst)), then you have to check whether (cdr lst) is empty as well.

So, your if statement needs to check both (null? ptlist) and (null? (cdr ptlist)), preferrably using cond.