“takeWhile(< =(maxBound :: Word8))primes”挂起

时间:2017-10-04 10:11:12

标签: haskell

今天我想知道有多少素数符合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.

因此,takeWhile仅在我们避开maxBoundprimes时才有效。

我如何解释这些发现?

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

2 个答案:

答案 0 :(得分:10)

你的问题非常有趣,但它不在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你的限制值。并且可能还会向库提交错误。

答案 1 :(得分:5)

实际问题是由Bartek Banachewicz发现的。

但请注意,谓词(<= (maxBound :: Word8)) 始终为真。 它相当于p其中:

p :: Word8 -> Bool
p x = x <= maxBound

现在,重要的是这里的x参数(原始代码中隐含的)是Word8。因此,我们将任意Word8Word8中可表示的最大数字进行比较。这总是如此!

如果您需要数字类型转换,则必须明确。 E.g。

takeWhile (<= fromIntegral (maxBound :: Word8)) (primes :: [Int])

现在,隐式xIntfromIntegral正确将256::Word8转换为256::Int