Wednesday, February 6, 2008

F# union types in C#

An other name for union types is discriminated unions.
I was interested what a union type looks and behaves in C#.
I build small demo applcation:
private void nudTest_ValueChanged(object sender, EventArgs e)
{
int x = Convert.ToInt32(nudTest.Value);

if(PsA.resultOfVote(x).IsYes())
{
lblResult.Text = "Yes";
}

if(PsA.resultOfVote(x).IsNo())
{
lblResult.Text = "No";
}

if(PsA.resultOfVote(x).IsMaybe())
{
lblResult.Text = PsA.resultOfVote(x).Maybe1.ToString();
}
}
image
image
image
The object created by F# looked like this:
image
I called the dll PsA.

Monday, February 4, 2008

F# union type

A new thing in F# for a C# programmer  is a union type. At first I thought it was an enumeration (enum).


#light

type YesNo =
    | Yes
    | No

let resutlOfQuestion x =
    if x then
        Yes
    else
        No
//val resutlOfQuestion : bool -> YesNo

resutlOfQuestion true;;
//> val it : YesNo = Yes
resutlOfQuestion false;;
//> val it : YesNo = No

But wait, there is more:

#light
type YesNoMaybe =
    | Yes
    | No
    | Maybe of int
    
let resultOfVote x =
    if x = 0 then
        No
    elif x >= 100 then
        Yes
    else
        Maybe x
        
resultOfVote 0;;
//> val it : YesNoMaybe = No
resultOfVote 50;;
//> val it : YesNoMaybe = Maybe 50
resultOfVote 120;;
//> val it : YesNoMaybe = Yes 

 

So a union type is a garbage can, you could put in everything you like (or don’t like).

F# by example

At the moment I am preparing new version of the OoxAcceleratorRss program.

I build previous version with C# and was quite successful and wanted to improve it. I ran into some problems which are html-related and I got stuck. I had to design and build a better html parser. One that is able to correct all kinds of html errors.

I read that one of the features of F# is the lexer and the parser. So I intend to learn F#.

Total Pageviews