出于教育原因,我尝试在 C# 中实现 F# 中的选择和选项类型。这是受到《真实世界函数式编程》一书和一些博客文章的启发,例如:http: //bugsquash.blogspot.de/2011/08/refactoring-to-monadic-c-applicative.html和http://tomasp。 net/blog/idioms-in-linq.aspx/。
我想让它工作,但我不知道如何实现选择类型的扩展(Bind、Map、SelectMany,...):
public static void Division()
{
Console.WriteLine("Enter two (floating point) numbers:");
(
from f1 in ReadDouble().ToChoice("Could not parse input to a double.")
from f2 in ReadDouble().ToChoice("Could not parse input to a double.")
from result in Divide(f1, f2).ToChoice("Cannot divide by zero.")
select result
)
.Match(
x => Console.WriteLine("Result = {0}", x),
x => Console.WriteLine("Error: {0}", x));
}
public static Option<double> Divide(double a, double b)
{
return b == 0 ? Option.None<double>() …Run Code Online (Sandbox Code Playgroud)