Saturday, November 19, 2011

F# ≥ C# (Tuple and Swap)

F#, as a new language, has something C# cannot easily do. That's what I really love F#, which makes the concise and less bug. Let me give some samples about how F# can do better than C#. Today is the first post for swap and tuple

swap is the simplest operation I could think of. Now I want a general swap function can handle any type. For C# version, object type or generic function can be used. But no matter what,  a temporary variable is needed. Now F# can do something simpler:

          let swap(a,b) = (b,a)
       
the passing parameter is (a,b) and the return value is (b,a). Is that simple?!

One thing always confused me is that (a,b) is a special type called tuple. So the function swap actually takes a single parameter whose type is tuple.

The tuple support more than 2 parameters, so you can do something like:

       let swap2(a,b,c,d,e) = (a,c,b,e,d)

to swap any element in a tuple in a way you prefer.



No comments: