Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# iteration over a Dictionary

Tags:

f#

I'm just starting with F# and I want to iterate over a dictionary, getting the keys and values.

So in C#, I'd put:

IDictionary resultSet = test.GetResults;
foreach (DictionaryEntry de in resultSet)
{
    Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value);
}

I can't seem to find a way to do this in F# (not one that compiles anyway).

Could anybody please suggest the equivalent code in F#?

Cheers,

Crush

like image 936
Crush Avatar asked Jul 16 '10 17:07

Crush


1 Answers

What is the type of your dictionary?

If it is non-generic IDictionary as your code snippet suggests, then try the following (In F#, for doesn't implicitly insert conversions, so you need to add Seq.cast<> to get a typed collection that you can easily work with):

for entry in dict |> Seq.cast<DictionaryEntry> do
  // use 'entry.Value' and 'entry.Key' here

If you are using generic IDictionary<'K, 'V> then you don't need the call to Seq.cast (if you have any control over the library, this is better than the previous option):

for entry in dict do
  // use 'entry.Value' and 'entry.Key' here

If you're using immutable F# Map<'K, 'V> type (which is the best type to use if you're writing functional code in F#) then you can use the solution by Pavel or you can use for loop together with the KeyValue active pattern like this:

for KeyValue(k, v) in dict do
  // 'k' is the key, 'v' is the value

In both of the cases, you can use either for or various iter functions. If you need to perform something with side-effects then I would prefer for loop (and this is not the first answer where I am mentioning this :-)), because this is a language construct designed for this purpose. For functional processing you can use various functions like Seq.filter etc..

like image 69
Tomas Petricek Avatar answered Sep 28 '22 05:09

Tomas Petricek