Last active
December 13, 2019 06:43
-
-
Save nklbdev/bbf2b30420330fe661d0a6189ea65202 to your computer and use it in GitHub Desktop.
Primitive universal functional builder
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
public static class Building | |
{ | |
public static Func<T> Provide<T>(Func<T> provider) => provider; | |
public static Func<T> Provide<T>(T value) => () => value; | |
public static Func<T> With<T>(this Func<T> provider, Action<T> modifier) => | |
With(provider, modifier, out _); | |
public static Func<T> With<T>(this Func<T> provider, Action<T> modifier, out Func<T> thisStep) | |
{ | |
thisStep = () => | |
{ | |
var x = provider(); | |
modifier(x); | |
return x; | |
}; | |
return thisStep; | |
} | |
public static Func<T2> Turn<T1, T2>(this Func<T1> provider, Func<T1, T2> replacer) => | |
Turn(provider, replacer, out _); | |
public static Func<T2> Turn<T1, T2>(this Func<T1> provider, Func<T1, T2> replacer, out Func<T2> thisStep) | |
{ | |
thisStep = () => replacer(provider()); | |
return thisStep; | |
} | |
} | |
public static class Program | |
{ | |
public static void Main() | |
{ | |
var buildTrue = Building.Provide("") | |
.Turn(x => x + "asdf") | |
.Turn(x => x.ToUpper(), out var buildASDF) | |
.Turn(x => x == "ASDF"); | |
var buildFalse = buildTrue | |
.With(x => !x); | |
Console.WriteLine(buildASDF()); | |
foreach (var x in Enumerable.Range(0, 10)) | |
Console.WriteLine(x % 2 == 0 ? buildTrue() : buildFalse()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment