gpt4 book ai didi

haskell - "takeWhile (<= (maxBound::Word8)) primes"挂起

转载 作者:行者123 更新时间:2023-12-02 18:48:19 25 4
gpt4 key购买 nike

今天我想要找出有多少个素数符合 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 .

最佳答案

你的问题很有趣,但它不在takeWhile中;它位于素数中:

由于 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com