如何在 COND 中不 return 任何东西

How to not return anything in a COND

所以我在 lisp 中制作这个函数,在 cond 部分基本上如果满足条件,我 return 一个包含 2 个值的列表,如果不满足条件, 我不想 return 任何东西!在这里:

(defun lista-dos-aprovados (turma)
  (mapcar (lambda (aluno)
            (cond ((> (media-notas (notas aluno)) 9.5)
                   (list (first aluno) (second aluno)))
                  (t nil)))
          turma))

名称是葡萄牙语,但我认为这在这里并不重要。我想做的是当代码到达 (t nil) 部分时,我不希望它在我的列表中写入 NIL 。我尝试没有 T 条件或在 T 之后将其留空,但它仍然总是写 NIL.

您可以删除 mapcar 结果中的 nil,例如:

(defun lista-dos-aprovados (turma)
  (remove nil
          (mapcar (lambda (aluno)
                    (cond ((> (media-notas (notas aluno)) 9.5)
                           (list (first aluno) (second aluno)))
                          (t nil)))
                  turma)))

并注意您可以将函数简化为:

(defun lista-dos-aprovados (turma)
  (remove nil
          (mapcar (lambda (aluno)
                    (when (> (media-notas (notas aluno)) 9.5)
                      (list (first aluno) (second aluno))))
                  turma)))

或者您可以使用 loop:

(defun lista-dos-aprovados (turma)
  (loop for aluno in turma 
     when (> (media-notas (notas aluno)) 9.5)
     collect (list (first aluno) (second aluno))))