Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seq toDictionary

Tags:

f#

How do i construct a dictionary from a Seq. I dont seem to be able to get syntax right.

So i have a Seq and i would like to construct a dictionary from it, something like

Document

<Overrides>
  <token key="A" value="1"/>
  <token key="B" value="2"/>
  <token key="C" value="3"/>
  <token key="D" value="4"/>
  <token key="E" value="5"/>
  <token key="F" value="6"/> 





let elem = docs |> Seq.map(fun x -> x.Descendants(XName.op_Implicit "Overrides").Elements(XName.op_Implicit "token"))
            |> Seq.head
            |> Seq.iter(fun (k: XElement , v:XElement) ->  k.Attribute(XName.op_Implicit "key").Value, v.Attribute("value").Value) 

but get runtime error

Error 1 This expression was expected to have type XElement but here has type 'a * 'b

like image 482
netmatrix01 Avatar asked Mar 15 '12 12:03

netmatrix01


1 Answers

To build a dictionary from a seq, you generally use the dict function. It takes a seq of key/value tuples, so the problem boils down to producing this sequence of tuples. With System.Xml.Linq you navigate the XML get the attribute values in a sequence.

Here's the code:

let x = @"<Overrides>
  <token key='A' value='1'/>
  <token key='B' value='2'/>
  <token key='C' value='3'/>
  <token key='D' value='4'/>
  <token key='E' value='5'/>
  <token key='F' value='6'/>
  </Overrides>"

#if INTERACTIVE
#r "System.Xml"
#r "System.Xml.Linq"
#endif

open System.Xml.Linq

let docs = XDocument.Parse x

let elem = docs.Root.Descendants(XName.Get "token")
            |> Seq.map (fun x -> x.Attribute(XName.Get "key").Value, x.Attribute(XName.Get "value").Value)
            |> dict

Seq.head returns the first element of a sequence, it's not useful here unless you want to use it to get to the Overrides node.

Seq.iter applies a function to each element in a sequence much like a for/foreach loop, just for the side-effects of the function. It's not useful here unless you want to build the dictionary imperatively, i.e. add key/values to an already existing dictionary.

like image 165
Mauricio Scheffer Avatar answered Oct 06 '22 04:10

Mauricio Scheffer