F#活动模式可以进行
let (|Even|Odd|) input = if input % 2 = 0 then Even else Odd
let TestNumber input =
match input with
| Even -> printfn "%d is even" input
| Odd -> printfn "%d is odd" input
TestNumber 7
一个糟糕的C#实现是
bool isOdd (int i) => (i % 2 == 1);
bool isEven(int i) => (i % 2 == 0);
string TestNumber(object n)
=> n switch
{
int x when isOdd(x) => $"{x} is Odd",
int x when isEven(x) => $"{x} is Even",
_ => $"{n} is Others"
};
var result = TestNumber(7);
是否有更好的c#实现/等价物?
更新:F#是";"更好";因为C#使用2个函数,而F#是1。
这是Fyodor Soikin评论的答案。
IntType GetType(int i) =>
i % 2 == 0? IntType.Even: IntType.Odd;
string TestNumber(int n) =>
GetType(n) switch {
IntType.Odd => $"{n} is Odd",
IntType.Even => $"{n} is Even",
};
var result = TestNumber(7);
enum IntType{Odd,Even};