If you just want to filter the list, the easiest option is to use function to write the standard pattern matching:
[ Foo; Bar; Foo ] |> List.filter (function Foo -> true | _ -> false)
If you want to write a more complex general function that checks the case and then does something else, then the simplest option (which will work in general) is to use a predicate that returns true or false :
let is cond item = if cond item then true else false // You can create a predicate using `function` syntax is (function Foo -> true | _ -> false) <argument>
In your specific example, you have a discriminatory union in which none of the cases has any parameters. This is probably an unrealistic simplification, but if you only care about discriminated associations without parameters, then you can simply use cases as values ββand compare them:
let is case item = if case = item then true else false
This last method will not work if you have a more complex discriminatory union in which some cases have parameters, so this is probably not very useful. For example, if you have a list of parameter values:
let opts = [ Some(42); None; Some(32) ] opts |> List.filter (is Some)
You can do various tricks using Reflection (to check for cases with the given name), and you can also use F # quotes to get a more pleasant and safe syntax, but I donβt think it is worth it because using pattern matching with Using function gives you a very clear code.
EDIT - Just out of curiosity, a solution that uses reflection (and it is slow and not safe, and no one should actually use it in practice unless you really know what you are doing) for example:
open Microsoft.FSharp.Reflection open Microsoft.FSharp.Quotations let is (q:Expr) value = match q with | Patterns.Lambda(_, Patterns.NewUnionCase(case, _)) | Patterns.NewUnionCase(case, _) -> let actualCase, _ = FSharpValue.GetUnionFields(value, value.GetType()) actualCase = case | _ -> failwith "Wrong argument"
It uses quotes to identify the case of the union, so you can write something like this:
type Case = Foo of int | Bar of string | Zoo [ Foo 42; Zoo; Bar "hi"; Foo 32; Zoo ] |> List.filter (is <@ Foo @>)