gpt4 book ai didi

haskell - 为什么这个 Haskell 程序会出现分歧?

转载 作者:行者123 更新时间:2023-12-03 10:57:45 25 4
gpt4 key购买 nike

看起来 [1,2,3] 和 [1..3] 之间有一个奇怪的区别。

在下面使用 runghc 会打印出一个“True”,然后永远挂起:为什么? (我使用的是 ghc 7.8.3)

module Main where

import Data.Functor((<$>))
import Data.Time.Clock(DiffTime)
import Data.Binary(Binary(..), encode, decode, Get)
import Data.Int(Int64)

instance Binary DiffTime where
put x = put (truncate (x * 10^12) :: Int64)
get = ((/ 10^12) . fromIntegral) <$> (get :: Get Int64)

prop_getput_difftime :: DiffTime -> Bool
prop_getput_difftime x = x == ((decode . encode $ x) :: DiffTime)

explicit :: [DiffTime]
explicit = [1,2,3,4,5,6,7,8,9,10]

elipsis :: [DiffTime]
elipsis = [1..10]

main :: IO ()
main = do
print $ all prop_getput_difftime explicit
print $ all prop_getput_difftime elipsis -- diverges!

注意,上面的 Binary for DiffTime 的实现是错误的;但这无关紧要。

最佳答案

感谢#haskell 的otulp,原因如下:

Prelude> take 3 [1..2] :: [Data.Time.DiffTime]
[1s,1.000000000001s,1.000000000002s]

这是因为 Enum DiffTime 的实例

更改 elipsis这解决了问题:
elipsis = map fromIntegral ([1..10] :: [Int])

关于haskell - 为什么这个 Haskell 程序会出现分歧?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27421598/

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