haskell - 在列表上使用范围运算符会导致无限扩展

标签 haskell

我目前正在通过“学一学 Haskell”学习 Haskell。

我正在查看列表并使用范围构建它们。

如果我有一个像这样的列表,我的想法是否正确

[2,4..20]

haskell 所做的是获取前两个元素之间的差异,然后将其与 4 相加以获得后续值?

这让我想到了下一点。我尝试了 [1,1..20],它导致了一个永无止境的列表扩展,因为 1-1 = 0,所以没有算术级数。

我的想法对吗?

最佳答案

Haskell Report是最终的引用。关于 arithmetic sequences 有这个说法:

Translation: Arithmetic sequences satisfy these identities:

[ e1.. ]      = enumFrom e1
[ e1,e2.. ]   = enumFromThen e1 e2
[ e1..e3 ]    = enumFromTo e1 e3
[ e1,e2..e3 ] = enumFromThenTo e1 e2 e3

where enumFrom, enumFromThen, enumFromTo, and enumFromThenTo are class methods in the class Enum as defined in the Prelude (see Figure 6.1).

The semantics of arithmetic sequences therefore depends entirely on the instance declaration for the type t. See Section 6.3.4 for more details of which Prelude types are in Enum and their semantics.

所以,我们应该去看看适当类型的 enumFromThenTo 方法。假设我们在这里谈论 Integer。关于预定义类型和类的章节有关于 Enum instances 的内容。 :

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.

所以,是的,你说的完全正确。

关于haskell - 在列表上使用范围运算符会导致无限扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21945103/

相关文章:

haskell - 如何在haskell中重新导出单个实体

haskell - 解开 Haskell State Monad

json - 如何使用 Aeson 将 Haskell ADT 序列化为整洁的 JSON?

haskell - Haskell Servant从处理程序获取当前路由/URL

Haskell 程序崩溃 - 无限递归? where语句错误?

haskell - 如何在 Haskell 中进行多行注释?

haskell - cabal 的依赖 hell 。真的是 hell

list - 给定一个字符串,获取元组列表(字符,字符连续出现多少次)-Haskell

haskell - 禁止 Haskell 中给定类型的记录更新

haskell - 如何组合返回 Bool 的函数