|
Not all the ways through it, but a good intro. On first glance, your example: (decimal | DivideByZeroException) Divide(decimal n, decimal d) => n / d;
Isn't that far off from what is pretty easily done in C#: using System.Runtime.CompilerServices;
(decimal? , DivideByZeroException?) Divide(decimal n, decimal d) {
try {
return (n / d, null);
} catch {
return (null, new DivideByZeroException());
}
}
Divide(6, 2).Switch(
(result) => Console.WriteLine($"6 /2 is {result}"),
(ex) => Console.WriteLine("This is an exception!")
);
Divide(6, 0).Switch(
(result) => Console.WriteLine($"6 /2 is {result}"),
(ex) => Console.WriteLine("This is an exception!")
);
public class DivideByZeroException : Exception;
public static class TupleExtension {
public static void Switch<T, E>(this ValueTuple<T, E> tuple, Action<T> action1, Action<E> action2) {
if (tuple.Item1 is null && tuple.Item2 is null) {
} else if (tuple.Item1 is null) {
action2(tuple.Item2);
} else {
action1(tuple.Item1);
}
}
}
(Sharing for folks who aren't familiar with C# Tuple types and extension methods) |
(btw, you're looking through the Monads For The Rest Of Us tutorial, but the the State Monad For The Rest Of Us tutorial is the one linked to this thread)