Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this Haskell program diverge?

Tags:

haskell

Looks like a strange difference between [1,2,3] and [1..3].

Using runghc on the following prints out one "True" and then hangs forever: why? (I'm using 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!

Note, the above implementation of Binary for DiffTime is wrong; but that is beside the point.

like image 726
sinelaw Avatar asked Dec 11 '14 11:12

sinelaw


1 Answers

Thanks to otulp from #haskell, here's the reason:

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

Which happens because of the Enum instance for DiffTime

Changing elipsis to this fixes the problem:

elipsis = map fromIntegral ([1..10] :: [Int])
like image 75
sinelaw Avatar answered Nov 10 '22 19:11

sinelaw