F# - Function like List.find but search for any of a Dictionary's keys
f#
Solution
A function for this almost feels like overkill. You can do this in one line using a list comprehension:
[for x in [9;4;5] do if dict1.ContainsKey x then yield dict1.[x]]
Edit:
After re-reading your question, I realized the above was not quite what you are looking for.
let rec findAValue l =
match l with
| [] -> None
| x::xs -> if dict1.ContainsKey x then Some(dict1.[x]) else findAValue xs
or more succinctly:
let rec findAValue = function
| [] -> None
| x::xs -> if dict1.ContainsKey x then Some(dict1.[x]) else findAValue xs
even more succinctly:
let findAValue = List.tryPick (fun x-> if dict1.ContainsKey x then Some(dict1.[x]) else None)
let highPerformanceFindAValue = List.tryPick (fun x-> match dict1.TryGetValue x with
| true, value->Some(value)
| _ -> None)
In the case where no value is found the result is `None` otherwise it's `Some(value)`.
Problem
I want to create an F# function like List.find, but instead of searching for a single value, I want to search for any of the keys of a dictionary and return the corresponding dictionary value. For example, this is a (poor) implementation of what I am trying to do. ``` let dict1=dict[(1,"A");(2,"B");(3,"C");(4,"D");(5,"E");(6,"F")] let findInDict l = let mutable found=false let mutable value="" for elem in l do let f,v=dict1.TryGetValue(elem) value<-if f && not found then v else value found<-if not found then f else found value findInDict [9;2;5] > val dict1 : System.Collections.Generic.IDictionary<int,string> val findInDict : l:seq<int> -> string val it : string = "B" ``` What would be a functional equivalent?