本文介绍了为什么这个代码返回空列表或失败?哈斯克尔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
primes :: [Int]
primes = sieve [2..]
sieve :: [Int] -> [Int]
sieve (p:xs)= p:sieve[x|x<-xs,x `mod` p /= 0]
f :: Int->Int
f n = head [x|x<-[0,(product (filter (<n) primes))..],x/=0,sum (map (x `mod`) [1..n]) == 0]
加载到GHCi
并键入f 20
失败...... plz help me
load into GHCiand type "f 20"fail...... plz help me
推荐答案
问题是用过滤器(< n)素数
。由于素数
是一个非常长的 very long1 list, this takes a long time to terminate since it doesn't know that (< n)
will eventually return False
for all primes past a certain point in the list, so it has to keep checking the entire list.
> filter (< 20) primes
[2,3,5,7,11,13,17,19^CInterrupted.
使用 takeWhile(< n)素数
取而代之。
Use takeWhile (< n) primes
instead.
> takeWhile (< 20) primes
[2,3,5,7,11,13,17,19]
1 由于 [Int]
类型,它是有限的。如果它是 [Integer]
,它将是无限的。
1 It's finite because of the type [Int]
. If it was [Integer]
, it would be infinite.
这篇关于为什么这个代码返回空列表或失败?哈斯克尔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!