Heisenbug
Heisenbug

Reputation: 39164

build a List from a Map through Map.iter function in F#

I have the following types:

type ColorCounter = 
    {

        Count : int
        Color : Microsoft.Xna.Framework.Color 

    }

let AvailableColors : Map<uint32,ColorCounter> = .....

I would like to iterate through the Map and return a List . I wrote the following function that doesn't compile:

let AvailableColorList(map : Map<uint32,ColorCounter>) : List<Microsoft.Xna.Framework.Color> = 
     let colorSeq = seq {

        map |> Map.iter (fun key col -> yield col.Color)  
     }
     colorSeq |> Seq.toList

I guess I'm doing something wrong with the syntax of the function passed to iter, but I've not find any suitable example that shows me how to do that.

Could anyone help me?What's my error? How can I fix the code above?

Upvotes: 1

Views: 1650

Answers (2)

Daniel
Daniel

Reputation: 47904

I think you want this

let AvailableColorList(map : Map<uint32,ColorCounter>) = 
    ResizeArray(map |> Seq.map (fun (KeyValue(_, col)) -> col.Color))

You're mixing a sequence comprehension and map, which are two different ways of doing the same thing.

You could also write it this way

let AvailableColorList(map : Map<uint32,ColorCounter>) = 
    ResizeArray([ for KeyValue(_, col) in map -> col.Color ])

Upvotes: 3

desco
desco

Reputation: 16782

let AvailableColors : Map<uint32,ColorCounter> = Map.empty
let colors = [ for (KeyValue(_, v)) in AvailableColors -> v ]

Upvotes: 2

Related Questions