Arc Forumnew | comments | leaders | submitlogin
Racket Scheme problem
1 point by Delian112 5236 days ago | 2 comments
So I was try a program from SICP, which takes a list a value and returns the number of ways to make change for the value based on the ones in the list... this went fine till I tried running it, at which point it told me: car: expects argument of type <pair>; given '() the code I used is: (define (List-coins Val Coin) (cond ((= 0 Val) 1) ((< Val 0) ) (else (+ (List-coins (- Val (car Coin)) Coin) (if (null? Coin) 0 (List-coins Val (cdr Coin)))))))

anyone have any ideas?



3 points by waterhouse 5236 days ago | link

aw is correct, though I feel like answering your question anyway. Your function, indented nicely:

  (define (List-coins Val Coin)
    (cond ((= 0 Val) 1)
          ((< Val 0))
          (else (+ (List-coins (- Val (car Coin)) Coin)
                   (if (null? Coin)
                       0
                       (List-coins Val (cdr Coin)))))))
This function will recurse until either Val is 0 or negative, or Coin is '()/null/the empty list. However, if Coin is the empty list, then your function will evaluate to

  (+ (List-coins (- Val (car Coin)) Coin)
     (if ...))
which contains a call to (car Coin), which throws the error that you observe. Instead, you should put the (null? Coin) check earlier, probably in the cond expression:

  (define (List-coins Val Coin)
    (cond ((= 0 Val) 1)
          ((< Val 0))
          ((null? Coin) 0)
          (else (+ (List-coins (- Val (car Coin)) Coin)
                   (List-coins Val (cdr Coin))))))
This still won't work, because there's no else-clause in the ((< Val 0)) part of cond. In that case, Val is negative, and there's no way to meaningfully make change by adding more coins, so it should return 0. Adding this in:

  (define (List-coins Val Coin)
    (cond ((= 0 Val) 1)
          ((< Val 0) 0)
          ((null? Coin) 0)
          (else (+ (List-coins (- Val (car Coin)) Coin)
                   (List-coins Val (cdr Coin))))))
which appears to be a correct definition.

-----

1 point by aw 5236 days ago | link

This is a forum for the Arc language. For help programming in Racket, see http://racket-lang.org/community.html

-----