在Haskell中减小范围 [英] Decrementing ranges in Haskell

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

问题描述

对于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 的元素从上向上计数(步长<$ c $ (含) 10



+1 $ c> [10,9..1] 被转换为 enumFromToThen 10 9 1 ,它明确指出计数步长为 9-10 ,即 -1 (它被硬编码为 +1 enumFromTo



更精确的规范可以在Haskell Report中找到(6.3.4 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]




对于类型 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 code> [e1,e1 + i,e1 + 2i,... e3] ,其中增量 i code> 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天全站免登陆