Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize Sequence from formatted Map

Tags:

f#

So I have a Map<int, Map<int, string>> data structure, and I can print them out well like so:

aMap 
|> Map.iter(fun key value -> value 
|> Map.iter(fun k v -> printf "Foo: %d\nBar: %d\nValue: %s" key k v))

This works fine, but I want to try and append Map elements with string formatting like above to a seq<string>

What would be the most effective way of doing this whilst still being "Functional"?

like image 956
Hayden Avatar asked Jan 27 '26 15:01

Hayden


1 Answers

You can always transform your map to a sequence: aMap |> Map.toSeq

You can also use Map.map for other transformations (instead of Map.iter).

Generally it helps to go through the reference section of the Collections you are using: https://msdn.microsoft.com/ja-jp/library/ee353880.aspx

EDIT:

aMap
|> Map.toSeq
|> Seq.collect(fun (k,v) ->
    v
    |> Map.toSeq
    |> Seq.map(fun (x,y) -> sprintf "Foo: %d Bar: %d Value: %s" k x y))
|> Seq.iter(printfn "%A")

Version 2:

aMap
|> Seq.collect(fun x ->
    x.Value
    |> Seq.map(fun y -> sprintf "Foo: %d Bar: %d Value: %s\n" x.Key y.Key y.Value))
|> Seq.iter(printfn "%A")

https://dotnetfiddle.net/Il5zv9

like image 55
s952163 Avatar answered Jan 30 '26 21:01

s952163



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!