gpt4 book ai didi

list - Haskell中的递减范围

转载 作者:行者123 更新时间:2023-12-03 11:46:40 26 4
gpt4 key购买 nike

我对 Haskell 很陌生。有人可以解释为什么定义这样的列表会返回一个空列表

ghci>  let myList = [10..1]
ghci> myList
[]

但是,这可以正常工作。
ghci>  let myList = [10, 9..1]
ghci> myList
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

最佳答案

基本上,因为 [10..1]被翻译成 enumFromTo 10 1它本身具有通过获取小于 1 的所有元素来创建列表的语义这是从(包括)+1 向上计数(步长 10 )产生的.

鉴于 [10, 9..1]被翻译成 enumFromToThen 10 9 1将计数步长明确声明为 9-10 ,即 -1 (对于 +1 硬编码为 enumFromTo )

更准确的规范可以在 Haskell 报告(6.3.4 枚举类)中找到:

enumFrom       :: a -> [a]            -- [n..]
enumFromThen :: a -> a -> [a] -- [n,n'..]
enumFromTo :: a -> a -> [a] -- [n..m]
enumFromThenTo :: a -> a -> a -> [a] -- [n,n'..m]

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.

关于list - Haskell中的递减范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6806455/

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