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).

No comments:

Total Pageviews