Reputation: 2765
I have a list of tuples:
(string * (int * int)) list
let st = [("a1",(100,10)); ("a2",(50,20)); ("a3",(25,40))]
Where I want to make a function which returns a bool on a few conditions: Both the ints have to be more than 0 and the strings in the list have to be distinct.
So far I have:
let rec inv st = List.forall (fun (a,(n,p)) -> n>0 && p>0) st
But I'm having trouble figuring out how to find out if all the strings in the list are distinct. Any hints?
Upvotes: 1
Views: 321
Reputation: 26174
Use distinctBy
:
let inv st =
List.length (List.distinctBy fst st) = List.length st && List.forall (fun (a,(n,p)) -> n>0 && p>0) st
or you can combine both checks in a single pipeline:
let inv st =
st
|> List.filter (fun (_,(n,p)) -> n>0 && p>0)
|> List.distinctBy fst
|> List.length
|> (=) (List.length st)
Upvotes: 6
Reputation: 80744
The shortest way would be to just compile the list of all distinct strings (via List.distinct
) and see if it ended up the same size as the original list:
let allDistinctStirngs = st |> List.map fst |> List.distinct
let allStringsAreDistinct = List.length st = List.length allDistinctStrings
Upvotes: 1