今天我要找出有多少个质数适合Word8的范围,但是这个最琐碎的任务给了我一个意想不到的...缺少结果。

λ import Data.Numbers.Primes
λ import Data.Word
λ takeWhile (<= (maxBound :: Word8)) primes
[2,3,5,7,11,13,17,19,23,25,29,31,35,37,41,43,47,49,53,55,59,61,71,73,
77,79,83,85,89,95,97,101,103,107,109,115,119,121,125,127,133,137,139,
145,149,151,157,161,163,167,173,175,179,185,187,191,197,199,203,205,
209,215,217,223,235^CInterrupted.

如您所见,不仅评估不会终止,而且得出的数字也不都是质数!

我开始在案子周围跳舞:
λ maxBound :: Word8
255

λ takeWhile (<= 255) primes
[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,
97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181
,191,193,197,199,211,223,227,229,233,239,241,251]

λ takeWhile (<= (maxBound :: Word8)) [1..]
[1,2,3, {- ..., -} 253,254,255]
-- This of course works, so I do not present the consecutive
-- natural numbers inbetween 3 and 253.

λ takeWhile (<= 255) $ take 255 primes
[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,
97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181
,191,193,197,199,211,223,227,229,233,239,241,251]

λ takeWhile (<= (maxBound  :: Word8)) $ take 255 primes
[2,3,5,7,11,13,17,19,23,25,29,31,35,37,41,43,47,49,53,55,59,61,71,73,
77,79,83,85,89,95,97,101,103,107,109,115,119,121,125,127,133,137,139,
145,149,151,157,161,163,167,173,175,179,185,187,191,197,199,203,205,
209,215,217,223,235^CInterrupted.

因此,仅当我们避免使用takeWhilemaxBound时,primes才有效。

我该如何解释这些发现?

我使用最新的稳定stack快照和this primes library

最佳答案

您的问题很有趣,但是不在takeWhile中;它在primes中:

由于primes可以返回您想要的任何类型,因此其实现可能在内部静默使用该类型。因此,当您要求它返回Word8素数时,它会在内部失败:

λ take 20 (primes :: [Word8])
[2,3,5,7,11,13,17,19,23,25,29,31,35,37,41,43,47,49,53,55]

我想一种解决方法是对素数生成器使用固定类型(例如(primes :: [Int]),而只是fromIntegral您的极限值。并且可能还会向库提交错误。

关于haskell - “takeWhile (<= (maxBound::Word8)) primes”挂起,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46562276/

10-13 07:08