Share via


Support for range in programming languages

DSCF2530

The .NET platform and the languages on top of it have limited or no support for range of values. Data ranges are one of the most common data-types and somehow it's not there. Funnily most programmers do not even seem to miss it (unless of course if you have used Ruby).

How would you specify a valid range of age and validate user data against it? If you know the maximum and minimum values, at max you'd define a MaxAge and MinAge consts and strew the code with if(age < MinAge|| age >MaxAge). Or maybe you'll define a class to encapsulate this and add a IsValid method.

However, in Ruby, Range is a standard DataType like say string. To do the above processing you'd do

 age = 1..120

print age.include?(50)
print age.include?(130)

 
print age === (50) # more easier way to do include? test using the === operator

So intuitively you create a range using start..stop.

Creating a range of data is also very simple. Say you want to generate the column numbers for an excel sheet, you'd do the following

 column = 'A'..'ZZ' 

column.to_a # creates an array of all the values

column.each {|v| puts "#{v}\n"}

Similarly ranges can be easily created for any class by implementing some special methods. On ruby the support of Range is in the compiler and makes the code very easy to develop and intuitive.

>>Cross posted here

Comments

  • Anonymous
    December 13, 2007
    PingBack from http://msdnrss.thecoderblogs.com/2007/12/14/support-for-range-in-programming-languages/

  • Anonymous
    December 13, 2007
    I guess the closest you can get, in C# at least, is a generic Range type, something like: public class Range<T> { public T Min { get; set; } public T Max { get; set; } public Range(T min, T max) { Min = min; Max = max; } public bool Includes(T value) { return (value >= Min && value <= Max); } } Then you can write code like: Range<int> age = new Range<int>(1, 120); Console.WriteLine(age.Includes(50)); Console.WriteLine(age.Includes(130)); Agreed, it's not quite as compact as the Ruby code, but it's not too bad!

  • Anonymous
    December 14, 2007
    That's just a type and can be used from any .NET language :)

  • Anonymous
    December 15, 2007
    The comment has been removed

  • Anonymous
    March 30, 2008
    Enumerable.Range is available in the System.Linq namespace. Enumerable.Range(1, 150) => 1..150