简体   繁体   中英

simple yes/no haskell list question

So I'm reading http://learnyouahaskell.com/starting-out as it explains lists, and using ghci on Vista 64. It says that [2,4..20] steps by 2 from 4 to 20. This works. It says [20,19..1] goes from 20 to 1, but doesn't explain. I take it that the first number is NOT the step, the step is the difference between the 1st and 2nd number. This is confirmed by [4,4..20] which hangs (no error message, must kill console). This is unlike operators like !! and take which check the index's range and give an error message.

My question is: is this a bug on Vista port or is that the way it's supposed to be?

[x,y..z] does indeed step from x to z by step yx . When yx is 0 this leads to an infinite list. This is intended behavior.

Note that if you use the list in an expression like take 20 [2,2..20] , ghci won't try to print the whole list (which is impossible with infinite lists of course) and it won't "hang".

Quoting this book :

[n,p..m] is the list of numbers from n to m in steps of pn.

Your list [4,4..20] "hangs", because you have a step of 4-4=0, so it's an infinite list containing only the number 4 ([4, 4, 4, 4...]).

Haskell allows infinite lists and as the Haskell is the "lazy evaluation language", meaning it will only compute what is necessary to give you the result, so the infinite structures are allowed in Haskell.

In Haskell you could compute something like "head[1..]". This is because Haskell only calculates what is required for the result. So in the example above it would generate only the first element of the infinite list (number 1) and head would return you this element (number 1). So, in that case program will terminate! However, if you calculate [1..] (infinite list) program won't terminate. Same applies to your example, you created an infinite list and there is no way of terminating it.

That syntax basically is derived from listing the whole list. [1,3,5,7,9,11,13,15,17,19] for example can be shortened by simply omitting the obvious parts. So you could say, if I specify the first two elements, it is clear how it would continue. So the above list equals to [1,3..19] .

It's worth noting that the .. syntax in lists desugars to the enumFrom functions given by the Enum typeclass:

http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#t:Enum

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM