O'Reilly logo

Functional Programming in C#: Classic Programming Techniques for Modern Projects by Oliver Sturm

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

RANGES

Many use cases for sequences are based on simple calculations and conditions, and the syntax required to use the Functional.Sequence function in these cases is still a bit more complicated than it has to be for simple things. The answer to this is the Range, which is a name for a type of sequence that has a start and an end and typically uses simple data types. These are not restrictions as such, since FCSlib ranges support overriding all these elements with custom ones, resulting in an alternative syntax for sequences — but the idea is that for common use cases, things are going to be easier through the use of a particular predefined range type.

Range<T> is a class defined in the FCSlib.Data namespace. There are implementations of ranges on the Internet that don’t use classes at all, but their disadvantage is that they cannot be used (as easily) for certain functionality like checking whether a particular value is within the range or not. Here are the first few lines of the class Range<T>:

public class Range<T> : IRange<T> {

  public Range(T start, T end, Func<T, T> getNext, Comparison<T> compare) {

    this.start = start;

    this.end = end;

    this.compare = compare;

    this.sequence = Functional.Sequence<T>(getNext, start,

      v => compare(getNext(v), end) > 0);

  }

 

  public Range(T start, T end, Func<T, T> getNext) :

    this(start, end, getNext, Compare) { }

 

  private static int Compare<U>(U one, U other) {

    return Comparer<U>.Default.Compare(one, other); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required