Chris Arena
Chris Arena

Reputation: 1630

Scheme List Manipulation (Recursion)

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!

Upvotes: 4

Views: 3066

Answers (5)

Alaya
Alaya

Reputation: 3387

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

Upvotes: 0

soegaard
soegaard

Reputation: 31147

An alternative solution:

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

Upvotes: 1

John Clements
John Clements

Reputation: 17203

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.

Upvotes: 0

dbyrne
dbyrne

Reputation: 61011

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)))))))

Upvotes: 2

Jeremiah Willcock
Jeremiah Willcock

Reputation: 30969

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

Upvotes: 3

Related Questions