Updating map multiple times in F#

Viewed 385

Let's say I have a map M:Map<int, bool> (initially empty). I want to update this time. I have a list L = [1 .. 100] and for each element in this list, I want to set the corresponding value in M false. So something like, [1 .. 100] |> List.map (fun x -> M.Add(x, false)). But M.Add() returns a new map every time and the updates are not reflected. How can I do this update in an idiomatic F# way?

2 Answers

You can use a fold for this:

let m = [1 .. 100] 
        |> List.fold( fun (acc:Map<int,bool>) x -> acc.Add(x, false)) Map.empty

A fold takes an accumulator and the current value as parameters. You can here use the Add method to return the updated Map.

For your specific scenario you may also consider a dictionary:

let m2 = [1 .. 100] 
         |>List.map(fun x->(x,false))
         |>dict

I think I got a working solution. Instead of declaring a Map first and then updating it (which would return a new Map every time), I constructed a list first and then converted the list to a Map.

[1 .. 100]
|> List.map
   (fun x ->
       (x, false)
   )
|> Map.ofList

I don't know if this solution is any good as I'm fairly new to F#. I'll be glad to know if this solution can be improved.

Related