Reputation: 121
Is there a way to do this?
type EntryDetails =
| ADetails of TypeADetails
| BDetails of TypeBDetails
| ...
type Entry = { A, B, C, ... Details:EntryDetails}
let filter (list:list<Entry>) myType = List.filter (fun x -> x.Details is myType)
Please take note I would like myType to be a parameter and not hardcoded type.
I tried this but it obviously doesn't work:
let filterDetails (entry:Entry) detailType = match entry.Details with
| detailType -> true
| _ -> false
Upvotes: 1
Views: 472
Reputation: 11525
It's not an exact solution to your question, but it's pretty close and easy to implement -- how about using a partial active pattern with List.choose
, like so:
type EntryDetails =
| ADetails of int
| BDetails of byte
| CDetails of string
type Entry = { Foo : unit; Bar : unit; Details : EntryDetails; }
module Patterns =
let (|ADetails|_|) x =
match x.Details with
| ADetails _ -> Some x
| _ -> None
let (|BDetails|_|) x =
match x.Details with
| BDetails _ -> Some x
| _ -> None
let (|CDetails|_|) x =
match x.Details with
| CDetails _ -> Some x
| _ -> None
module internal Test =
let private testData =
let baseData = { Foo = (); Bar = (); Details = ADetails 0; }
[ { baseData with Details = ADetails 10; };
{ baseData with Details = BDetails 7uy; };
{ baseData with Details = BDetails 92uy; };
{ baseData with Details = ADetails 32; };
{ baseData with Details = CDetails "foo"; };
{ baseData with Details = BDetails 2uy; };
{ baseData with Details = ADetails 66; };
{ baseData with Details = CDetails "bar"; };
{ baseData with Details = CDetails "baz"; }; ]
let results =
testData
|> List.choose Patterns.(|ADetails|_|)
If you paste that code into fsi
, you should get the following output:
(* Snip ... removed irrelevant type signatures *)
module internal Test = begin
val private testData : Entry list =
[{Foo = null;
Bar = null;
Details = ADetails 10;}; {Foo = null;
Bar = null;
Details = BDetails 7uy;};
{Foo = null;
Bar = null;
Details = BDetails 92uy;}; {Foo = null;
Bar = null;
Details = ADetails 32;};
{Foo = null;
Bar = null;
Details = CDetails "foo";}; {Foo = null;
Bar = null;
Details = BDetails 2uy;};
{Foo = null;
Bar = null;
Details = ADetails 66;}; {Foo = null;
Bar = null;
Details = CDetails "bar";};
{Foo = null;
Bar = null;
Details = CDetails "baz";}]
val results : Entry list =
[{Foo = null;
Bar = null;
Details = ADetails 10;}; {Foo = null;
Bar = null;
Details = ADetails 32;};
{Foo = null;
Bar = null;
Details = ADetails 66;}]
end
As you can see, the Test.results
list is filtered so it only includes the Entry
items whose Details
field has type ADetails
.
Upvotes: 2