Sanchime.Functional/Sanchime.Test/Program.cs

53 lines
1.3 KiB
C#

using Sanchime.Functional.Products;
using Sanchime.Functional.Extensions;
using Sanchime.Toolkits;
// Test<int> test = new Test<int>();
// Console.WriteLine(test.Map((Test<int> x) => {x.Value = 2; return x;}).Value);
// Console.WriteLine(test.Value);
// foo(10);
// foo(Option.None);
// void foo(Option<int> option)
// {
// var res = option.Map(x => x + 2);
// res.WriteLine();
// }
// Option.Some(1).Map(x => (float)x + 1.2).Map(x => x.ToString()).Map(x => x.GetType().Name).WriteLine();
// 测试Option的Bind
var parse = (string s) => Int32.TryParse(s, out int i) ? Option.Some(i) : Option.None;
var foo = (string s) => s.Pipe(parse).Bind(Age.Of);
foo("111").WriteLine();
foo("aaa").WriteLine();
foo("123").WriteLine();
// 管道
foo("1ab").Pipe(x => Console.WriteLine(x));
public struct Age
{
private int _value;
public static Option<Age> Of(int age)
=> IsValid(age) ? Option.Some(new Age(age)) : Option.None;
private Age(int age)
{
if (!IsValid(age))
{
throw new ArgumentException("输入的年龄是无效的");
}
_value = age;
}
private static bool IsValid(int age)
=> age is (>= 0 and <= 150);
public override string ToString()
=> _value.ToString();
}