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

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; ...

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