using System.Collections.Generic; namespace Modbus.Utility { /// /// Functional utility methods. /// public static class FunctionalUtility { /// /// Memoizes the given function. /// public static Func Memoize(Func generator) { bool hasValue = false; T returnValue = default(T); return delegate { if (!hasValue) { returnValue = generator(); hasValue = true; } return returnValue; }; } /// /// Memoizes the given function. /// public static Func Memoize(Func generator) { return Memoize(generator, delegate(TInput input) { return input; }); } /// /// Memoizes the given function. /// public static Func Memoize(Func generator, Func keySelector) { Dictionary cache = new Dictionary(); return delegate(TInput input) { TOutput output; if (!cache.TryGetValue(keySelector(input), out output)) { output = generator(input); cache.Add(keySelector(input), output); } return output; }; } } }