First class lazy Interval

Sean Reque seanthenewt at yahoo.com
Fri Feb 27 07:53:41 PST 2009


I think Ruby is a good example of a good way to implement intervals. Ruby exposes them as a class object, so that you can instantiate them as Range.new(min,max), and a Range object iterable and can easily be converted to an array. It also supports inclusion testing. The only thing it doesn't do is allow one to specify a step in the object itself, at least as of 1.8. (One CAN step over a range with the step function, but this doesn't help for things like inclusion testing). In addition to exposing a class interface that is consistent with the rest of the language, the ruby language itself allows one to define ranges using the .. notation as extra syntactic sugar.

I really like Ruby's combination of defining constructs in the language consistently so that they looko the same as user-defined objects, and then adding syntactic sugar on top to make the language more pleasant.  Regular expressions are another example of how Ruby does this. Ruby allows one to instantiate regular expressions the same way in as in python, as they are implemented as a Regexp class, but Ruby also supports instantiating them using perl's syntax, which underneath the hood is just creating a Regexp object. The advantage of the perl-like syntax is that editors and IDEs can aid a user with syntax highlighting, whereas when creating a regular expression with a string no such help can be given.  

Doing things similarly in D, one could implement intervals in a library form in a similar manner as Daniel did, and then add support in the language for the syntax bearophile described. Of course, this would require that D would impose that at least certain things got implemented in a standard library, whereas D currently doesn't do if I understand correctly.. 



More information about the Digitalmars-d mailing list