EXPLICIT LAZY EVALUATION

The technique of explicit lazy evaluation uses an encapsulation of a function call, which can be passed around and evaluated at any point. This encapsulation also provides caching, so that the actual method call only happens (at most) once.

This technique is quite close to the approach used by Haskell that was mentioned in the introduction to this chapter. Unfortunately, it can’t be fully automatic in C#; instead, the encapsulating type must be specified explicitly in place of the “real” return type.

FCSlib provides a class Lazy<T>, which can be used as an encapsulation container for a function call:

image

public sealed class Lazy<T> {

  public Lazy(Func<T> function) {

    this.function = function;

  }

 

  public Lazy(T value) {

    this.value = value;

  }

 

  readonly Func<T> function;

  T value;

  bool forced;

  object forceLock = new object( );

  Exception exception;

 

  public T Force( ) {

    lock (forceLock) {

      return UnsynchronizedForce( );

    }

  }

 

  public T UnsynchronizedForce( ) {

    if (exception != null)

      throw exception;

    if (function != null && !forced) {

      try {

        value = function( );

        forced = true;

      }

      catch (Exception ex) {

        this.exception = ex;

        throw;

      }

    }

    return value;

  }

 

  public T Value { get { return Force( ); } }

 

  public bool IsForced { get { return forced; ...

Get Functional Programming in C#: Classic Programming Techniques for Modern Projects now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.