Rm558
Rm558

Reputation: 4994

how c# pattern matching do things like f#'s active pattern

F# active pattern can do

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

a poor C# implementation is

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);

is there a better c# implementation/equivalent?

update: F# is "better" since C# uses 2 functions while F# is 1.

Upvotes: 0

Views: 196

Answers (1)

Rm558
Rm558

Reputation: 4994

this is an answer from a comment by 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};

Upvotes: 1

Related Questions