Monday, January 10, 2011

F#'s Option nearly equals with C#'s Nullable types

If you have a experience writing Java programs, you would have thought that you want to put null value into primitive variables, at least once. In C#, you can do it with "Nullable types":

// bool
bool? nb = true; // you can set true,
nb = false; // false,
nb = null; // and null

// int
int? ni; // You can set zero,
ni = -1; // non-zero,
ni = null; // and null

In F#, the language on the .NET, You can also deal with same paradigm as "Option".

$ fsharpi

Microsoft (R) F# 2.0 Interactive build 2.0.0.0
Copyright (c) Microsoft Corporation. All Rights Reserved.

For help type #help;;

> let nothing : string option = None;;

val nothing : string option = None

> let something : string option = Some "Hello World";;

val something : string option = Some "Hello World"

> let puts str = System.Console.WriteLine(str.ToString());;

val puts : 'a -> unit

> Option.iter puts something;;
Hello World
val it : unit = ()
> Option.iter puts nothing;;  
val it : unit = ()

No comments:

Post a Comment