如何防止列表输出无效

How to prevent void in output of list

当我在列表中使用when时,#<void>经常不必要地出现。以下是使用 map 和 for/list.

的示例
;; using map    
(define lst '(0 0 0 1 1 1 2 2 2 3 3))
    (map (lambda (x)
             (when (equal? 2 x)
                 x
                 ))
           lst)   
;; expected => '(2 2 2)
;; output => '(#<void>  #<void>  #<void>  #<void>  #<void>  #<void>
;; 2  2  2  #<void>  #<void>)

;; using for/list
    (define my-list '(0 0 0 1 2 1 2 2 2))
     (for/list ([a (drop-right my-list 1)]
                           [b (cdr lst)]
                           [i (in-naturals)])
                  (when (> a b)
                    (list a b i)))
;; expected => '(2 1 4)
;; output => '(#<void> #<void> #<void> #<void> (2 1 4) #<void> #<void> #<void>)

当我改用 if 条件时,我没有任何其他东西可以用于 #false 状态。我该如何防止这些 #<void>?

在这些情况下,您不应使用 mapfor/list:它们将相同的操作应用于对象列表和 return 通过 获得的列表申请的所有结果。因此,由于 when 没有其他选择,当条件为假时,结果为 #<void>.

改用预定义运算符filter

(filter (lambda (x) (equal? x 2)) '(0 0 0 1 2 1 2 2 2))
;; => '(2 2 2 2)

Renzo 所述,如果您的目标实际上是过滤,则可以使用 filter。但是,还值得一提的是,您 可以 通过在循环中使用 #:when 子句来为此使用 for/list

(define lst '(0 0 0 1 1 1 2 2 2 3 3))
(define my-list '(0 0 0 1 2 1 2 2 2))

(for/list ([a (drop-right my-list 1)]
           [b (cdr lst)]
           [i (in-naturals)]
           #:when (> a b))
  (list a b i))

; => '((2 1 4))