Haskell 中的递减范围 [英] Decrementing ranges in Haskell

查看:20
本文介绍了Haskell 中的递减范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 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-10code>,即-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]

<块引用>

对于类型IntInteger,枚举函数的含义如下:

  • 序列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 <,则列表为空e3.

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]

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 中的递减范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆