A similar understanding of the Haskell list with different results

I do not understand why these two similarities in the lists give different results:

Prelude> let t2s n= [ 1/(2*i) | i <- [1,3..n]] Prelude> t2s 0 [0.5] Prelude> let t2s n= [ (2*i) | i <- [1,3..n]] Prelude> t2s 0 [] 

I expected both to return [] in argument 0 . I must be missing something stupid ?!

+7
source share
2 answers

This is due to the fact that

 enumFromThenTo 1.0 3.0 0.0 

matters [1.0] . The enumFromThenTo specification for Floats can be found in section 6.3.4 http://www.haskell.org/onlinereport/haskell2010/haskellch6.html .

+6
source

First of all, I changed the name of your first t2s to t1s so that I can upload them to ghci at the same time. Look at the inferred types for each of them:

 [ts.hs:2:1-33] *Main> :t t1s t1s :: (Enum t, Fractional t) => t -> [t] [ts.hs:2:1-33] *Main> :t t2s t2s :: (Enum t, Num t) => t -> [t] [ts.hs:2:1-33] *Main> 

Note that t1s takes a Fractional argument, while t2s takes a Num value. This means that in t1s 0 value 0 is defined as a Double . On the other hand, the interpreter passes 0 as an Integer to t2s 0 . Since the type used for the argument is different, the behavior can be very surprising. In particular, you should use only Integral types when listing the list, as in [1,3..n] .

To fix this, you just need to provide explicit type signatures for both functions.

+7
source

All Articles