Crystal: Calling Range(_, Nil)#size hangs in runtime

Created on 5 Sep 2019  路  10Comments  路  Source: crystal-lang/crystal

Code below is enough to kill the compiler:

(0..).size

Infinite Iterators are having the same issue btw:

[1, 2, 3].cycle.size
feature stdlib

Most helpful comment

Advice: always do crystal build foo.cr and then ./foo to see whether it's a compiler bug or just hangs at runtime.

All 10 comments

It looks like it hangs at runtime, which I guess is expected, though we could try to detect it somehow... it's really hard, though.

Advice: always do crystal build foo.cr and then ./foo to see whether it's a compiler bug or just hangs at runtime.

I guess we could overload #size in these 2 cases.

We could. It would also hang when doing map, or select or any of the other enumerable methods.

could we have another class called InfiniteIterator subclassed from Iterator for cases like this?

This is expected behaviour. Every language will hang if you try and perform an infinite amount of work. What would #size return? Infinity isn't an integer.

For this specific case, Range#size could at least raise when end is nil.

It would probably make sense to override this method anyway, because for the most common use case with integers, the size can be calculated directly. It doesn't need to iterate through the elements as Enumerable#size does.

It would be nice to have an Infinity to return. I think Float is the object that has an infinity but maybe the Int classes should have one for cases like this.

@wontruefree IMO if anything Infinity should be moved into the Number struct instead.

@wontruefree Int has no concept of infinity, so it can't be a valid return value. And it's not really useful here either.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

lgphp picture lgphp  路  3Comments

costajob picture costajob  路  3Comments

pbrusco picture pbrusco  路  3Comments

grosser picture grosser  路  3Comments

asterite picture asterite  路  3Comments