Sanchime.Functional/Sanchime.Test/Program.cs

67 lines
1.5 KiB
C#
Raw Normal View History

2022-05-14 17:25:18 +08:00
using Sanchime.Functional.Products;
using Sanchime.Functional.Extensions;
2022-05-08 14:57:11 +08:00
using Sanchime.Toolkits;
2023-01-09 21:12:00 +08:00
try
2023-01-08 17:22:25 +08:00
{
2023-01-09 21:12:00 +08:00
void foo(Option<int> option)
{
var res = option.Map(x => x + 2);
res.WriteLine();
}
"预计打印Some(12)".WriteLine();
foo(10);
"预计打印None".WriteLine();
foo(Optional.None);
"预计打印Some(String)".WriteLine();
Optional.Some(1)
.Map(x => x + 1.2)
.Map(x => x.ToString())
.Map(x => x.GetType().Name)
.WriteLine();
2022-05-14 17:25:18 +08:00
// 测试Option的Bind
2023-01-09 21:12:00 +08:00
var parse = (string s) => Int32.TryParse(s, out int i) ? Optional.Some(i) : Optional.None;
var foo1 = (string s) => s.Pipe(parse).Bind(Age.Of);
"预计打印Some(111)".WriteLine();
foo1("111").WriteLine();
"预计打印None".WriteLine();
foo1("aaa").WriteLine();
"预计打印Some(123)".WriteLine();
foo1("123").WriteLine();
2022-05-14 17:25:18 +08:00
// 管道
2023-01-09 21:12:00 +08:00
"预计打印None".WriteLine();
foo1("1ab").Pipe(x => x.WriteLine());
}
catch (Exception ex)
{
ex.Message.WriteLine();
ex.StackTrace.WriteLine();
}
2022-05-08 17:06:05 +08:00
public struct Age
2022-05-08 14:57:11 +08:00
{
2022-05-08 17:06:05 +08:00
private int _value;
public static Option<Age> Of(int age)
2023-01-09 21:12:00 +08:00
=> IsValid(age) ? Optional.Some(new Age(age)) : Optional.None;
2022-05-08 14:57:11 +08:00
2022-05-08 17:06:05 +08:00
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();
}