Thankyou, LLB and Tomasp. I also got a response from Brian, in the other forum where I raised the question.

It can be done either by matching on the LHS of the let binding, or by augmenting the type with a member function for the purpose. I think I'll probably do both.

(apologies for my original cross-post).
--------------------------------------------------------------------------------------------------------------

brianmcn's response from "Books, tutorials, .."

You have to match, but you can encapsulate the matching in a function. E.g

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 

type Foo =
    | I of int
    | S of string
    with
        member this.GetInt() =
            match this with
            | I(x) -> x
            | _ -> failwith "oops"
        member this.GetString() =
            match this with
            | S(s) -> s
            | _ -> failwith "oops"

let myFooInt = I 42
let fooVal = myFooInt.GetInt()
By on 8/29/2009 6:38 PM ()

Hi,

You can use the function Option.get to get the value (or raise an exception).

If you declare your own sum type, you can use member extensions (so that you can write SomeN.n).

By on 8/29/2009 4:05 AM ()

Hi,
in general case, you can use the discriminated union cases in patterns in "let" bindings as well. This is similar to "match" expressions, but you're matching the value agains only one case:

1
2
3
4
 
type Union = Foo of int | Bar of string;;
let v = Foo(42);;
let (Foo num) = v;;

Note that you'll get a warning on the last line, because the compiler cannot verify (in general) whether the code can fail or not. The "Option.get" function uses exactly this technique, but the warning is hidden inside the function.

By on 8/29/2009 4:18 AM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper