如何从此列表中过滤空值? [英] How can I filter null values from this list?
问题描述
我按照以下步骤在列表中创建所有素数对:
I have the following procedure for creating all prime-pairs in a list:
(define (prime-pairs lst)
(define (split lst pos)
(list (drop-right lst pos) (take-right lst pos)))
(define (prime-pairs-iter n acc)
(cond ((= n 0) (filter (lambda (e) (not (null? e))) acc))
(else (prime-pairs-iter (- n 1)
(let ((s (split lst n)))
(if (and (prime? (list->number (car s)))
(prime? (list->number (cadr s))))
(append s acc)
acc))))))
(prime-pairs-iter (- (length lst) 1) '()))
(完整代码: https://gist.github.com/anonymous/b8cfcb0bf021be9ef9c8 )
我要prime-pairs
要做的是在lst
中创建由两个素数组成的每对列表.数字以列表格式表示,如下所示:11将为'(1 1)
.
What I want prime-pairs
to do is create a list of every pair in the lst
that consists of two primes. The numbers are represented in a list format as follows: 11 would be '(1 1)
.
不幸的是,当我运行这段代码时,(filter (lambda (e) (not (null? e))) acc))
似乎并没有从最终结果中删除'()
,最终我得到了一长串空值和想要的对.
Unfortunately, when I run this code the (filter (lambda (e) (not (null? e))) acc))
does not seem to remove the '()
from the end result, and I end up with a long list of empty values and the wanted pairs.
如果我使用(filter null? acc))
,则确实会保留一个空值列表.因此,另一种方法(过滤出实际值)确实可以工作.
If I use a (filter null? acc))
a list of empty values does remain. So the other way around (filtering out the actual values) does work.
如何过滤返回列表的空值?
How can I filter out the nulls of the returned list?
推荐答案
当前,您的prime-pairs
函数始终返回一个值:空列表或素数对.使用map
,如果不对map
的结果进行进一步的过滤,则无法避免空列表.
Currently, your prime-pairs
function always returns one value: either an empty list, or the prime pairs. Using map
, there is no way to avoid the empty lists, without doing further filtering on the result of the map
.
一种替代方法是返回结果的列表,并使用append-map
而不是map
.更改您的prime-pairs
以返回一个空列表,或者返回一个包含素数对的单例列表;这模拟返回零或一个值,而不总是返回一个值.像这样:
One alternative is to return a list of results, and use append-map
instead of map
. Change your prime-pairs
to return either an empty list, or a singleton list containing your prime pairs; this simulates returning zero or one value, rather than always one value. Like so:
(cond ((zero? n) (if (null? acc)
'()
(list acc)))
...)
现在,使用append-map
:
(append-map prime-pairs primes-list-split)
,您应该拥有想要的结果. (有关完整代码,请参见我的分叉要领.)
and you should have the results you seek. (See my forked gist for full code.)
这篇关于如何从此列表中过滤空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!