Reputation: 9437
To create a list of 5 numbers, the following is possible :
[1..5]
One may also start from greatest to lowest:
[5,4..1]
But what does not make sense is that if you were to create a list as so, you get an empty list:
[5..1]
Is there perhaps an explanation as to why an empty list is returned for the last snippet? It does not makes sense to me why you have to specify the gap between each number, just as in the second snippet above.
If it works from lowest to greatest, I would assume it wouldn't be too hard to make the language work from greatest to lowest. Is there an underlying reason as to why Haskell does not allow for this, vulnerability issues perhaps?
Upvotes: 1
Views: 81
Reputation: 116174
The [n..m]
list enumerates those numbers x
such that n <= x && x <= m
. If m<n
, no such x
can exist, hence the result is empty.
Note that this convention helps when translating the idiomatic imperative loop
// Does nothing if m<n
for (int x=n; x <= m ; x++) { ... }
which could transform into
map (...) [n..m] -- or foldr, or ...
or even
forM_ [n..m] $ \x -> ...
This convention is shared with some other languages, e.g. Python, where range(n,m)
is roughly equivalent to [n..m-1]
. Indeed, range(1,1)
is empty, as well as range(1,0)
and range(1,-1)
and so on.
Upvotes: 4
Reputation: 12133
From Wikibooks, Arithmetic sequences are desugared as:
[1..5] → enumFromTo 1 5
[1,3..9] → enumFromThenTo 1 3 9
[1..] → enumFrom 1
[1,3..] → enumFromThen 1 3
So [5,4..1]
is desugared into enumFromThenTo 5 4 1
, but [5..1]
to enumFromTo 5 1
.
You could define them as you wish for your data types. The functions are part of Enum
type-class.
Upvotes: 3