Search code examples
schemeracketmit-scheme

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


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


Solution

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