F # discriminé union picking 0 ou 1 à partir d'une liste
-
27-09-2019 - |
Question
Etant donné un programme de cartographie où je la carte à partir d'un tableau de chaînes à une union discriminée, je veux choisir une instance d'un type particulier DU. Je sais qu'il y aura 0 ou 1 cas. Y at-il une façon plus intelligente de le faire que cela?
type thing = { One:int; Two:int; Three:int}
type data =
| Alpha of int
| Bravo of thing
| Charlie of string
| Delta of Object
//generate some data
let listData = [
Alpha(1);
Alpha(2);
Bravo( { One = 1; Two = 2; Three = 3 } );
Charlie("hello");
Delta("hello again")]
//find the 0 or 1 instances of bravo and return the data as a thing
let result = listData
|> List.map( function | Bravo b -> Some(b) | _ -> None)
|> List.filter( fun op -> op.IsSome)
|> (function | [] -> None | h::t -> Some(h.Value))
Merci
La solution
Qu'en est-
let result =
listData
|> List.tryPick (function | Bravo b -> Some b | _ -> None)
Autres conseils
List.tryFind fera l'affaire:
let result = listData
|> List.tryFind (function | Bravo b -> true | _ -> false)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow