How to create a function that receives a list and creates a new list in Scheme

356 Views Asked by At

I'm trying to create a function called evenElememt that takes a list as a parameter and appends all the elements in even positions to a new list and displays the new list.

My attempt:

(define newList '())

(define elementHelper
  (lambda lst
      ((cdr lst)
      (cons newList (car lst))
      (elementHelper(cdr lst)))
  )
)

(define evenElement
  (lambda (lst)
    (cond
      ((null? lst) ())
      ((null? (cdr lst)) ())
      (else (elementHelper lst)
            (display lst))
    )
  )
)

Example output: if I enter (evenElement '('a 'b 'c 'f 't 'y)), the output should be (b f y).

2

There are 2 best solutions below

0
Flux On BEST ANSWER

This is essentially the same as Can I print alternate elements of a list in Racket?, except that you want to print even positions (1-indexed) instead of odd positions.

(define (even-positions lst)
  (cond ((null? lst)
         '())
        ((null? (cdr lst))
         '())
        (else
          (cons (second lst)
                (even-positions (cddr lst))))))

(even-positions '(a b c f t y)) returns '(b f y).

Then, this is the function you are looking for:

(define (display-even-positions lst)
  (display (even-positions lst)))
0
Barmar On

You don't need elementHelper. Just make evenElement return the result instead of displaying it.

You also don't need the global variable newList. The function should construct the result as it goes.

(define evenElement
  (lambda (lst)
    (cond
     ((null? lst) '())
     ((null? (cdr lst)) '())
     (else (cons (car (cdr lst)) 
           (evenElement (cdr (cdr lst)))))
     )
    )
  )

(display (evenElement '(a b c f t y)))