F# と C# の記法比較

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

unit 型

unit 型 Unit Type

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

unit 型は、特定の値を持たないことを示す型です。unit 型には値が 1 つだけあり、他の値が存在しない場合や不要な場合のプレースホルダーとして機能します。

F#

// The value of the unit type.
()

すべての F# の式は、評価して値にする必要があります。 式で目的の値が生成されない場合は、unit 型の値が使用されます。 unit 型は、C#、C++ などの言語の void 型に似ています。

ということなので、F# で () を返している関数は void にしておけばよい。

F#

let function1 x y = x + y
// The next line results in a compiler warning.
function1 10 20 
// Changing the code to one of the following eliminates the warning.
// Use this when you do want the return value.
let result = function1 10 20
// Use this if you are only calling the function for its side effects,
// and do not want the return value.
function1 10 20 |> ignore

F# の場合、戻り値を無視するには明示的に ignore を指定することになる。 C# の場合は、無視しても警告はでない。

C#

int function1(int x, int y) { return x + y; }

void test()
{
    // 警告は出ない
    function1(10, 20);
    // 戻り値を取得
    var result = function1(10, 20);
    // 戻り値を無視する
    function1(10, 20);
}