简体   繁体   中英

Select certain items from a list in Racket

Let's say I want to get all the even numbers from a list in racket, I would do something like this:

(define (even lst)
  (map (λ(x) 
         (if (even? x) (append x) (append '()) )) lst))

When I use the input (even '(1 2 3 4)) what I actually get is '( () 2 () 4) instead of '(2 4) , which is the desired output.

Is there a way I can do this?

Here are two solutions:

#lang racket

(define (keep-even xs)
  (match xs
    ;; pattern              template
    [(cons (? even? x0) xs) (cons x0 (keep-even xs))]
    [(cons          x0  xs)          (keep-even xs)]
    ['()                    '()]))

(keep-even '(1 2 3 4 5 6 7 8))

The pattern is common, so the standard library has filter :

(filter even? '(1 2 3 4 5 6 7 8))

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