Why is [1..n] not handled the same way as [n..1] in Haskell?

[a..b] desugars to enumFromTo a b. For standard numeric types (modulo a couple of quirks for floating), this keeps adding one until you are >= b. So where b < a this is empty.

You can change the increment by using the following syntax [a,a'..b] which then takes steps in increments of a'-a. So [10,9..1] will be what you want.


This is because of the way the sequence is defined in Haskell Report Arithmetic Sequences :

[ e1..e3 ] = enumFromTo e1 e3

and Haskell Report The Enum Class

The sequence enumFromTo e1 e3 is the list [e1,e1 + 1,e1 + 2, ... e3]. The list is empty if e1 > e3.

(emphasis added).


They are handled exactly the same way. You start from the first bound and count up.

Tags:

List

Haskell