简体   繁体   中英

Write a scheme that returns a list of even numbers

Write a Scheme function that returns the list of even numbers in a given list of integer numbers.The list may not be simple,nested lists can occur and you need to find the even numbers inside those.

(DEFINE (evenlist numberlist) using this as a body and getting the result sth like this (DEFINE (evenlist numberlist) Result:(2 4 6 4)

(define (evenlist numberlist)
  (cond
    ((null? numberlist) '())
    (else(not (= 0 (modulo (numberlist) 2))(evenlist(car numberlist))))
    ))

this is what i have done , i am new to lisp so dont blame me :(

You have to do a bit more of work if the input list is an arbitrarily nested list of lists. This is the standard template to process such lists (cases: empty list, non-list or a list of lists), plus additional logic to flatten the result (that's why append is used here):

(define (evenlist numberlist)
  (cond ((null? numberlist) '())
        ((not (pair? numberlist))
         (if (even? numberlist) (list numberlist) '()))
        (else
         (append (evenlist (car numberlist))
                 (evenlist (cdr numberlist))))))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM