44 ms·
On the off chance that you know C# and Linq: // A Box that holds stuff public class BoxOfStuff<TStuff> { public TStuff Value { get; private
by ilitirit 9y ago
On the off chance that you know C# and Linq:
// A Box that holds stuff
public class BoxOfStuff<TStuff>
{
public TStuff Value { get; private set; }
public BoxOfStuff(TStuff value)
{
Value = value;
}
}
// Class that holds methods for working with Boxes of stuff
public static class Ext
{
// Takes something and puts it in a box
public static BoxOfStuff<TStuff> PutInABox<TStuff>(this TStuff thingToPutInTheBox)
{
return new BoxOfStuff<TStuff>(thingToPutInTheBox);
}
// Converts a Box containing one thing into a Box containing something else
public static BoxOfStuff<TOtherStuff> ConvertBox<TStuff, TOtherStuff>(this BoxOfStuff<TStuff> theBoxItself,
Func<TStuff, BoxOfStuff<TOtherStuff>> functionThatConvertsTheBox)
{
return functionThatConvertsTheBox(theBoxItself.Value);
}
}
// Class that holds a string value
public class StringHolder
{
public string Value;
public StringHolder(string value)
{
Value = value;
}
public override string ToString()
{
return Value;
}
}
var result = new StringHolder("A random string").PutInABox()
.ConvertBox(randomString => new Random((int)DateTime.Now.Ticks).Next().PutInABox()
.ConvertBox(randomNumber => (Guid.NewGuid()).PutInABox()
.ConvertBox(guid => ($"{randomString}, {randomNumber}, {guid}").PutInABox())));
Console.WriteLine(result);
// Compare the above result to this:
public static class LinqExt
{
public static IEnumerable<T> ToEnumerable<T>(this T t)
{
return new List<T> { t };
}
}
var linqResult = new StringHolder("A random string").ToEnumerable()
.SelectMany(randomString => new Random((int)DateTime.Now.Ticks).Next().ToEnumerable()
.SelectMany(randomNumber => Guid.NewGuid().ToEnumerable()
.SelectMany(guid => ($"{randomString}, {randomNumber}, {guid}").ToEnumerable())));
Console.WriteLine(linqResult);
BoxOfStuff + PutInABox + ConvertBox = Monad.
This is analogous to:
IEnumerable + ToEnumerable (the Identity function) + SelectMany (the Bind function). To be honest, this is a fairly loose, non-rigorous definition even by programming standards, but if you've used LINQ before it should give you an idea of how useful Monads can be and how they can be used.
LINQ works the way it does because of Monads. In fact, if I were to add a Map function (Select) to BoxOfStuff and rename ConvertBox to SelectMany, I could use query syntax eg.
var result = from thing in myBoxOfStuff
select thing.ToString();