Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching on a discriminated union

Tags:

f#

Is there any way to pattern match on discriminated union functions, e.g.:-

type Test =
  | A of string
  | B of int
  | C of char

let DefaultTest t =
  match t with
  | A(_) -> A(null)
  | B(_) -> B(0)
  | C(_) -> C('\u0000')

let a = A |> DefaultTest

Obviously this code isn't valid F# as DefaultTest accepts one parameter of type Test rather than 'a -> Test. Is there any way of achieving this without specifying a value for the discriminated union?

What I'm after, ultimately, is a function which inputs a function of type 'a -> Test and outputs Test(default value of 'a).

like image 241
ljs Avatar asked Apr 08 '09 14:04

ljs


1 Answers

I am not clear what you are after, but does this help?

type Foo =
    | A of int
    | B of string

let CallWithDefault f =
    let x = Unchecked.defaultof<_>
    f x

let defaultA = CallWithDefault A    
let defaultB = CallWithDefault B    
printfn "(%A) (%A)" defaultA defaultB 
like image 149
Brian Avatar answered Sep 27 '22 18:09

Brian