简体   繁体   中英

Scheme function for building list of even integers

I am trying to write a function in Scheme that takes a list as an argument and returns a list containing only the even integers from the argument list. After working through the problem, this is what I have come up with:

(define (even-list n)
    (if (even? car(n))
        (cons car(n) even-list(cdr(n)))
        (even-list cdr(n))
    )
)

To test my function even-list I have built a small list to pass as the argument to the function. However, when I run the code below, all that happens is that the list is outputted:

even-list (list 1 2 3 4 5 6 7 8 9 10)

It almost seems like it isn't even calling the function, as I replaced the then clause with "even" and "even" was never outputted. Any ideas?

Note that scheme/racket uses prefix notation, whereby any procedure being applied gets wrapped around opening and closing brackets (function-name arg1 arg2 ...) .

This means that car(n) , cdr(n) , even-list(...) etc. are invalid syntax, and should be replaced with (car n) , (cdr n) , (even-list ...) etc. respectively.

This is also why you are not seeing any changes in output when making modifications to your procedure even-list , because with simply writing

even-list (list 1 2 3 4 5 6 7 8 9 10)

you are calling an identifier ( even-list ) which may/may not be bound (in this case it is bound with the function definition), and the expression (list 1 2 3 4 5 6 7 8 9 10) . This expression is what is returning your list output, and any changes you make within even-list will not be reflected on this list, since you have not actually passed it as an argument to a procedure, but rather simply applied it using the list built-in procedure.

Once you fix the line to:

(even-list (list 1 2 3 4 5 6 7 8 9 10))

you will start to notice errors that stem from your procedure logic. For example, your recursive function has no base case, meaning that as the function recurses through the list, when it reaches a list of zero elements '() , it still attemps to apply (car n) , which is a contract violation on car since it is expecting a pair? for an argument.

Consider the following:

(define (even-list lst)
  (cond
    ((null? lst) empty)                           ; base case (empty? list)
    ((even? (car lst))                            ; even? first element
     (cons (car lst) (even-list (cdr lst))))   
    (else (even-list (cdr lst)))))

or, using built-in filter procedure:

(define (even-list lst)
  (filter even? lst))

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