F# と C# の記法比較

MSDN F# リファレンスを使い C# と記法を比較する

タプル

タプル Tuples

ネタ元 http://msdn.microsoft.com/ja-jp/library/dd233200.aspx

タプルには、2 個タプル、3 個タプルなどがあり、型が同じである場合と異なる場合があります。

// Tuple of two integers.
( 1, 2 ) 

// Triple of strings.
( "one", "two", "three" ) 

// Tuple of unknown types.
( a, b ) 

// Tuple that has mixed types.
( "one", 1, 2.0 ) 

// Tuple of integer expressions.
( a + 1, b + 1) 

Tuple of unknown types 以外は、new Tuple で作成する。

// Tuple of two integers.
var t1 = new Tuple<int, int>(1, 2);
// Triple of strings.
var t2 = new Tuple<string, string, string>("one", "two", "three");
// Tuple that has mixed types.
var t4 = new Tuple<string, int, double>("one", 1, 2.0);
// Tuple of integer expressions.
int a = 10, b = 20;
var t5 = new Tuple<int, int>(a + 1, b + 1);

個別の値の取得

次のコードに示すように、パターン マッチを使用して、タプルの要素の名前へのアクセスおよび割り当てを行うことができます。

let print tuple1 =
   match tuple1 with
    | (a, b) -> printfn "Pair %A %A" a b

パターンマッチではないが、C# では .Item1, .Item2 でタプルの要素を取得する。

public void print( Tuple<int,int> t )
{
    Console.WriteLine("Pair {0} {1}", t.Item1, t.Item2);
}

次のように、let 束縛で組のパターンを使用できます。

let (a, b) = (1, 2)

C# の場合はタプルを作成して、.Item1, .Item2 で取得すればよい。

var t = Tuple.Create<int, int>(1, 2);
int a = t.Item1, b = t.Item2;

タプルの 1 つの要素のみが必要な場合は、ワイルドカード文字 (アンダースコア) を使用して、不要な変数の新しい名前が作成されないようにすることができます。

let (a, _) = (1, 2)

C# の場合は .Item1 だけ取ればよい。

var t = Tuple.Create<int, int>(1, 2);
int a = t.Item1;

fst 関数および snd 関数はそれぞれ、タプルの最初の要素と 2 番目の要素を返します。

let c = fst (1, 2)
let d = snd (1, 2)

これも .Item1, .Item2 を使えばよい。

let third (_, _, c) = c

C# の場合は、.Item3 で取得する。

var t = Tuple.Create<int, int>(1, 2, 3);
int c = t.Item3;

タプルの使用

タプルによって、関数から複数の値を返す便利な方法が提供されます。

let divRem a b = 
   let x = a / b
   let y = a % b
   (x, y)

2つの値を戻すためにタプルを使うのは C# でも使うことができる。

public Tuple<int, int> DivRem(int a, int b)
{
    int x = a / b;
    int y = a % b;
    return new Tuple<int, int>(x, y);
}

タプルは、通常の関数構文が意味する関数の引数が暗黙でカリー化されないようにする場合に、関数の引数として使用することもできます。

let sumNoCurry (a, b) = a + b

この手法は C# のメソッドを呼び出すときにも使う。

タプル型の名前

タプルである型の名前を記述する場合は、* 記号を使用して要素を区切ります。 (10, 10.0, "ten") のように、int、float、および string で構成されるタプルについては、次のように型を記述します。

int * float * string

スペースは -> で、タプルは * で、表現する。「関数プログラミング」では、スペースは →(矢印) 、タプルは ×(直積)で表す。