How to filter out false values from the list in racket
Asked Answered
M

1

8

I'm learning Racket (but probably answer will be similar in any Scheme and scheme-derived language) and wonder how to filter out false (#f) values from a given list. The best I came up with is:

(filter (lambda (x)
           (not (eq? x #false)))
        '("a" "b" #f 1 #f "c" 3 #f))

'("a" "b" 1 "c" 3) ;; output

However, I guess there has to be a simpler solution.

Marcionism answered 29/7, 2015 at 6:18 Comment(0)
E
12

You can just do

(filter identity '("a" "b" #f 1 #f "c" 3 #f))

as anything not #f is considered true.

Elinorelinore answered 29/7, 2015 at 8:13 Comment(2)
Also, you might see Racket code that uses values instead of identity (for example when someone is using #lang racket/base and doesn't want to (require racket/function) just to get identity).Hartwig
@GregHendershott +1 values also comes with R7RS.Academy

© 2022 - 2024 — McMap. All rights reserved.