Skip to content

Instantly share code, notes, and snippets.

@bleis-tift
Forked from anonymous/gist:5572563
Created May 14, 2013 00:04
Show Gist options
  • Save bleis-tift/5572581 to your computer and use it in GitHub Desktop.
Save bleis-tift/5572581 to your computer and use it in GitHub Desktop.
using System;
namespace LangExt.Playground
{
public sealed class LazyVal<T>
{
T value;
bool hasValue = false;
readonly Func<T> f;
public LazyVal(Func<T> f) { this.f = f; }
public T Value
{
get
{
if (hasValue) return value;
value = f();
hasValue = true;
return value;
}
}
public static implicit operator T(LazyVal<T> v) { return v.value; }
public static implicit operator LazyVal<T>(Func<T> f) { return new LazyVal<T>(f); }
public static implicit operator LazyVal<T>(T x) { return new LazyVal<T>(() => x); }
public LazyVal<U> Bind<U>(Func<T, LazyVal<U>> f)
{
return new LazyVal<U>(() => f(Value));
}
public U Map<U>(Func<T, U> f)
{
return new LazyVal<U>(() => f(Value));
}
public LazyVal<T> OrElse(LazyVal<T> v)
{
if (v.hasValue) return this;
else return v;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment