f# - 序列到字典

标签 f#

我如何从 Seq 构建字典。我似乎无法正确使用语法。

所以我有一个 Seq,我想从中构建一个字典,比如

文档

<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) 

但得到运行时错误

错误 1 ​​此表达式应具有 XElement 类型,但此处具有类型 'a * 'b

最佳答案

要从 seq 构建字典,您通常使用 dict function .它需要一系列键/值元组,所以问题归结为生成这个元组序列。与 System.Xml.Linq您导航 XML 获取序列中的属性值。

这是代码:

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返回序列的第一个元素,除非您想使用它来到达 Overrides 节点,否则在这里没有用。

Seq.iter对序列中的每个元素应用一个函数,很像 for/foreach循环,只是为了函数的副作用。除非您想命令式地构建字典,否则它在这里没有用,即将键/值添加到已经存在的字典中。

关于f# - 序列到字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9719526/

相关文章:

f# - 如何使用命名空间或类型别名/缩写?

android - 使用 Xamarin Android 与 F# 和 ReactiveUI 时出现运行时错误

f# - 在不同的泛型实例中实现相同的接口(interface)

linq - 如何将 Expr <'a -> ' b> 转换为 Expression<Func<'a, obj>>

f# - Delay 在 Continuation monad 中到底是如何工作的以防止 stackoverflow?

generics - F#:如何对类型值进行模式匹配?

f# - 捕获键盘输入 Webshaper

f# - 在 F# 中将 (string * int) [] 写入文本文件

asynchronous - 来自代理/邮箱处理器的一般回复?

f# - 将变量绑定(bind)到 FSI 中的接口(interface)类型