result list of map is one longer

This question already has an answer here:

  • Why does map return an additional element when using ranges in Haskell? 1 answer

  • As @duplode suggested, it has to do with how .. behaves with floating point vs. integers:

    Prelude> let x3 = [1,3..10] :: [Double]
    Prelude> length x3
    6
    Prelude> let x3 = [1,3..10] :: [Int]
    Prelude> length x3
    5
    

    Update in response to the comment...

    A definition like this in ghci:

    let xs = [1,3..11]
    

    is polymorphic. The .. is a shortcut for the enumFromThenTo function:

    let xs = enumFromThenTo 1 3 11
    

    The result is polymorphic - the above expression has type:

    ghci> :t xs
    x3 :: (Enum t, Num t) => [t]
    

    If you just print it out, Haskell chooses to type is as [Integer] , and you get:

    [1,3,5,7,9]
    

    Here the Integer version of enumFromThenTo is being used.

    However, if you apply a floating point operation to the list, Haskell interprets it as [Double] , and then it becomes one element longer for the reasons explained above:

    ghci> map (+ 0.0) x3
    [1.0,3.0,5.0,7.0,9.0,11.0]  -- length 6 now!
    

    So the map operation "changes" the length of the list only because it changes the interpretation of its type which changes which enumFromThenTo function is called to construct it.

    Upshot: A list defined like [1,3..11] does not have known length until its type is determined.

    链接地址: http://www.djcxy.com/p/87992.html

    上一篇: 底部为其默认值

    下一篇: 地图的结果列表是一个更长的时间