Wednesday, May 9, 2012

F# Choice

Today I was puzzled by the Choice type. I thought it was two values in a structure. Actually it was one union-like structure and only store one value. I did not want to stop on my mistake and want to explore more. And I find the Choice is choice-sensitive even their type is same. Unlike C++, the value share the same memory storage.

See the below code:

open System

let a : Choice< int, int > = Choice2Of2 1

let f = function
        | Choice1Of2 e -> printfn "1 %A" e
        | Choice2Of2 e -> printfn "2 %A" e

f a

it outputs 2 1 because it goes to the highlighted route.

No comments: