问题
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) '()))
(Full code: https://gist.github.com/anonymous/b8cfcb0bf021be9ef9c8)
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)
.
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.
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?
回答1:
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
.
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)))
...)
Now, use append-map
:
(append-map prime-pairs primes-list-split)
and you should have the results you seek. (See my forked gist for full code.)
来源:https://stackoverflow.com/questions/31909685/how-can-i-filter-null-values-from-this-list