问题描述
我对 Haskell 很陌生.有人可以解释一下为什么定义这样的列表会返回空列表
ghci>让 myList = [10..1]ghci>我的清单[]
但是这可以正常工作.
ghci>让 myList = [10, 9..1]ghci>我的清单[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
基本上,因为 [10..1]
被翻译成 enumFromTo 10 1
,它本身具有通过从(包括)10向上计数(步长为
+1
)而得到小于 1
的所有元素来创建列表的语义代码>.
而 [10, 9..1]
被转换为 enumFromToThen 10 9 1
,它明确指出计数步长为 9-10
code>,即-1
(对于enumFromTo
,它被硬编码为+1
)
可以在 Haskell Report (6.3.4 The Enum Class) 中找到更准确的规范:
enumFrom :: a ->[一个..]enumFromThen :: a ->->[a] -- [n,n'..]enumFromTo :: a ->->[a] -- [n..m]enumFromThenTo :: a ->->->[a] -- [n,n'..m]
对于类型Int
和Integer
,枚举函数的含义如下:
序列
enumFrom e1
是列表[e1,e1+1,e1+2,...]
.序列
enumFromThen e1 e2
是列表[e1,e1+i,e1+2i,...]
,其中增量i,是 e2-e1.增量可能为零或负数.如果增量为零,则所有列表元素都相同.序列
enumFromTo e1 e3
是列表[e1,e1+1,e1+2,...e3]
.如果e1 >,则列表为空.e3
.序列
enumFromThenTo e1 e2 e3
是列表[e1,e1+i,e1+2i,...e3]
,其中增量,i
,就是e2-e1
.如果增量为正数或零,则当下一个元素大于e3
时,列表终止;如果e1 >,则列表为空e3
.如果增量为负,则列表在下一个元素小于e3
时终止;如果e1 .
I am very new to Haskell. Could someone please explain why defining a list like this returns an null list
ghci> let myList = [10..1]
ghci> myList
[]
However this works correctly.
ghci> let myList = [10, 9..1]
ghci> myList
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Basically, because [10..1]
is translated to enumFromTo 10 1
which itself has the semantics to create a list by taking all elements less-than 1
which result from counting upward (with step-size +1
) from (including) 10
.
Whereas [10, 9..1]
is translated to enumFromToThen 10 9 1
which explicitly states the counting step-size as 9-10
, i.e. -1
(which is hard-coded to +1
for enumFromTo
)
A more accurate specification can be found in the Haskell Report (6.3.4 The Enum Class):
enumFrom :: a -> [a] -- [n..]
enumFromThen :: a -> a -> [a] -- [n,n'..]
enumFromTo :: a -> a -> [a] -- [n..m]
enumFromThenTo :: a -> a -> a -> [a] -- [n,n'..m]
这篇关于Haskell 中的递减范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!