gpt4 book ai didi

Haskell 范围和 float

转载 作者:行者123 更新时间:2023-12-03 07:05:08 24 4
gpt4 key购买 nike

为什么 Haskell 范围表示法对于 float 的行为与整数和字符不同?

Prelude> [1, 3 .. 10] :: [Int]
[1,3,5,7,9]
Prelude> [1, 3 .. 10] :: [Float]
[1.0,3.0,5.0,7.0,9.0,11.0]
Prelude> ['a', 'c' .. 'f']
"ace"

如果最后一个元素接近上限,我会理解,但这显然不是舍入问题。

最佳答案

语法[e1, e2 .. e3]确实是 enumFromThenTo e1 e2 e3 的语法糖,这是 Enum 中的函数类型类。

The Haskell standard其语义定义如下:

For the types Int and Integer, the enumeration functions have the following meaning:

  • The sequence enumFrom e1 is the list [e1,e1 + 1,e1 + 2,…].
  • The sequence enumFromThen e1 e2 is the list [e1,e1 + i,e1 + 2i,…], where the increment, i, is e2 − e1. The increment may be zero or negative. If the increment is zero, all the list elements are the same.
  • The sequence enumFromTo e1 e3 is the list [e1,e1 + 1,e1 + 2,…e3]. The list is empty if e1 > e3.
  • The sequence enumFromThenTo e1 e2 e3 is the list [e1,e1 + i,e1 +
    2i,…e3]
    , where the increment, i, is e2 − e1. If the increment is positive or zero, the list terminates when the next element would be greater than e3; the list is empty if e1 > e3. If the increment is negative, the list terminates when the next element would be less than e3; the list is empty if e1 < e3.

这几乎是您所期望的,但是 FloatDouble实例的定义不同:

For Float and Double, the semantics of the enumFrom family is given by the rules for Int above, except that the list terminates when the elements become greater than e3 + i∕2 for positive increment i, or when they become less than e3 + i∕2 for negative i.

我不太确定这样做的理由是什么,所以我能给你的唯一答案是它就是这样,因为它在标准中是这样定义的。

您可以通过使用整数进行枚举并转换为 Float 来解决此问题。之后。

Prelude> map fromIntegral [1, 3 .. 10] :: [Float]
[1.0,3.0,5.0,7.0,9.0]

关于Haskell 范围和 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7290438/

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