-
-
Save bleis-tift/5572581 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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