4
votes

The basic problem here is, when given a list, to return all elements of that list other than the last element. For example, given (a b c d) --> return (a b c). I essentially have the function, it's just the Scheme syntax that I'm having trouble with and Google isn't being very friendly. I'm not sure if I'm using cons correctly.

(define all-but-last
  (lambda (x)

   (if (null? (cdr x)) 
      ('()))
   (cons ((car x) (all-but-last(cdr x)))
)))

Someone who's knowledgeable with r5rs scheme syntax would be helpful. Thanks!

5

5 Answers

3
votes

If you remove the extra parentheses around the '() and arguments to cons, the code will work (for non-empty input lists).

2
votes

Using DrRacket with Language R5RS, this works:

(define all-but-last
  (lambda (x)
   (if (null? x)
     '()
     (if (null? (cdr x)) 
       '()
       (cons (car x) (all-but-last(cdr x)))))))
1
votes

An alternative solution:

(define (all-but-last xs)
  (reverse 
    (rest
      (reverse xs))))
0
votes

See the answers to this question:

removing last element of a list(scheme)

Also, I'm going to tag this one as "homework". If it's not, let me know and I'll remove it.

0
votes

if you pass '() to your function, I think you should give error message other than return '()