Colebacha2
Colebacha2

Reputation: 47

Add elements to list and return list in Scheme

I'm trying to define a function that accepts a list of letters and returns the list with the last element removed. I'm fairly new to scheme so I'm not sure if this can be accomplished without creating a variable inside the function. So far I've started with:

define funct (lambda (x) 
    (let (list '() )
     (if ( < (length x) 2 ) list (append ( list (car x))

Am I able to just slap on a recursive call like this:

(if ( < (length x) 2 ) list (append ( list (car x)) (set x (cdr x)) lambda (x))

Or is this wildly wrong?

Upvotes: 1

Views: 1348

Answers (1)

uselpa
uselpa

Reputation: 18917

Wildly wrong, yes.

The reasoning would be as follows:

  1. if the list is empty, or just has 1 element, return the empty list
  2. otherwise, keep the first element and repeat with the rest of the list (recursion)

In code:

(define funct
  (lambda (lst)
    (if (or (null? lst) (null? (cdr lst)))
        '()
        (cons (car lst) (funct (cdr lst))))))

Testing:

> (funct '())
'()
> (funct '(a))
'()
> (funct '(a b))
'(a)
> (funct '(a b c))
'(a b)
> (funct '(a b c d))
'(a b c)

Upvotes: 1

Related Questions