3

I found nice little one example of Scala today. Something like:

(1 to 100) map { x =>   
  (x % 2, x % 6) match {  
    case (0,0) => "First"
    case (0,_) => "Second"    
    case (_,0) => "Third"    
    case _ => x toString    
  }
} foreach println

And i wonder if I could do something similar in C#. I tried to search on my own but it's hard since I don't know name of this expression. It seems pretty useful. So can I do this in C#?

3 Answers3

5

Pattern matching is not available in C#.

But you can use Nemerle .Net language which supports Pattern Matching and many other great stuff which C# doesn't support.

foreach (x in $[1 .. 100])
{
   Console.WriteLine(
     match((x % 2, x % 6))
     {
       | (0, 0) => "First"
       | (0, _) => "Second"
       | (_, 0) => "Third"
       | _      => x.ToString()
     })
}
NN_
  • 1,593
  • 1
  • 10
  • 26
3

It's called (functional) pattern matching, and is a hallmark of functional programming languages such as Scala, F#, and Haskell. http://codebetter.com/matthewpodwysocki/2008/09/16/functional-c-pattern-matching/ discusses how to simulate F#'s version of it in C#.

geekosaur
  • 59,309
  • 11
  • 123
  • 114
2

Since I don't know Scala, I can't verify that this does the same thing, but you can probably base your code off this.

Enumerable.Range(1, 100)
    .Select(x => new {original = x, two = x % 2, six = x % 6})
    .Select(x =>
    {
        if (x.two == 0 && x.six == 0)
            return "First";
        else if (x.two == 0)
            return "Second";
        else if (x.six == 0)
            return "Third";
        else
            return x.original.ToString();
    }).ToList().ForEach(s => Console.WriteLine(s));

Outputs:

1
Second
3
Second
5
First
7
Second
9
Second
...
Alex
  • 3,429
  • 4
  • 36
  • 66
  • Is that what the Scala code actually does? I don't get the Scala code, but I'm pretty sure you're code can never print "Third". (Quick check - it doesn't - http://ideone.com/redmN ) – Kobi Apr 03 '11 at 08:05
  • Nice feature. I'll change my code to reflect the Scala output. – Alex Apr 03 '11 at 08:12