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

I tried to solve a problem that required the maximum value of the list after the function was displayed. The list is a range from a to b, where a> b or b> a. Since Haskell can also define shrinking lists, I thought I didn't need to check if a> b was there, and there was no need to throw borders to b..a. The function looks something like this:

f a b = maximum . map aFunction $ [a..b]

But if the list is reduced, i.e. a> b, then Haskell gives me an exception:

Prelude.maximum: empty list

Thus, for some reason, a decreasing list passes an empty list to the maximum function. Why is this?

I know what maximumis defined in terms foldl1 maxand what foldl1needs a non- [10..1]empty list, but I do not know why such a list as is empty when passed foldl1.

+5
source share
3 answers

[a..b]desugars up enumFromTo a b. For standard numeric types (modulo a pair of quirks for swimming), this adds it until you become >= b. So where b < ais it empty.

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

+15
source

, Haskell:

[e1..e3] = enumFromTo e1 e3

Haskell Enum

enumFromTo e1 e3 [e1, e1 + 1, e1 + 2,... e3]. , e1 > e3.

( ).

+5

They are handled in exactly the same way. You start from the first border and count.

+3
source

All Articles