Search code examples
recursionschemeracketconsr5rs

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!


Solution

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