I have a discriminated union type:
type F =
| A of int
| B of float
Suppose I have a list of F that has been filtered to yield only objects of type A:
let listOfAs=list.filter (fun f -> match f with | A(f') -> true | _ -> false)
How can I work with the resulting list of F without requiring pattern matches everywhere in my code? The compiler doesn't like a direct cast, eg
list.map (fun f -> int f) listOfAs
You cannot really cast discriminated union value - the type of
F
is a different thing than the typeint
(it is not like C union where they have the same binary representation).So, the easiest solution is to write a function that takes
list<F>
and returnslist<int>
containing only theint
values that were wrapped in theA
case.To do this, you can use
List.choose
(instead ofList.filter
). This lets you specify a projection where you can returnNone
(meaning skip the value) orSome v
(meaning return valuev
as part of the resulting list):