Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if a value is a specific instance of a discriminated union

Tags:

f#

If I have a discriminated union

type Result<'T,'U> =
| Success of 'T
| Failure of 'U

Then I can create a pattern matching function to test for success

let success = function
    | Success(_) -> true
    | _ -> false

Can I create this as a one liner, something like this?

let success = fun x -> x = Success(_)

This last line doesn't compile, but I think it demonstrates my intent

like image 530
Pete Avatar asked Oct 23 '25 14:10

Pete


1 Answers

There is no easy way to do so, but you could do it via reflection. Using the isUnionCase function from this answer, we can write:

let success = isUnionCase <@ Success @>

For this particular case, I think the success function is succinct enough to be qualified as one-liner:

let success = function Success _ -> true | _ -> false

As @Daniel said, compiler-generated Is* functions should be exposed. There is a related suggestion on User Voice, perhaps you should vote so that it is implemented in F# 4.0.

like image 67
pad Avatar answered Oct 26 '25 10:10

pad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!