C#对函数式编程支持的库,支持.net framework,从neget上下载
Option<T>:避免处理空指针
cs
private Option<int> Parse(string v)
{
if (int.TryParse(v, out int i))
return new Some<int>(i);
return Option<int>.None;
}
Option<int> res = Parse("123w");
res.IfNone(() => { Debug.WriteLine("error"); });
if (res.IsNone)
{
Debug.WriteLine("failed");
}
else
{
Debug.WriteLine(res.Value<int>());
}
Either<left, right>:函数式的Error处理
cs
private Either<string, int> ParseInt(string v)
{
if(int.TryParse(v, out var i))
{
return i;
}
return "parse error";
}
private Either<string, int> SafeAdd(int v1, int v2)
{
return v1 + v2;
}
private Either<string, int> SafeDiv(int v1, int v2)
{
if (v2 == 0)
return "Div 0 error";
return v1 / v2;
}
Either<string, int> res02 = ParseInt("23").Bind(v3 => SafeAdd(v3, 10)).Bind(v4 => SafeDiv(v4, 0)).Bind(v5 => SafeAdd(v5, 10));
int addResult;
string error;
var resBool = res02.Match(
Right: x=> { addResult = x; return true; },
Left: eInfo=> { error = eInfo; return false; }
);
var trupleList = new List<(string, int)> { ("a", 1), ("b", 2) };
Map<string, int> map = new Map<string, int>(trupleList);
var v = map.Find("a").Map(v1=>v1 * 2);
var v2 = map.Find("c");
var i = v.Value();
var mapRes = v2.Match(
Some: x=> true,
None: false
);
Match:对Option或Either结果进行解析,见上例
Map:对Option、集合进行映射
Bind:从Option中提取数据后继续执行Map操作
Language-Ext库提供了如上支持,让C#可按函数式编程思路组合多个纯函数。