f# 元组 item1 的 Seq

标签 f# f#-interactive

我不明白为什么会收到以下错误:

> let x = "ABCDAACCECFG"|>Seq.sort|>Seq.groupBy (fun x->x);;
val x : seq<char * seq<char>>

> x;;
val it : seq<char * seq<char>> =
  seq
    [('A', seq ['A'; 'A'; 'A']); ('B', seq ['B']);
     ('C', seq ['C'; 'C'; 'C'; 'C']); ('D', seq ['D']); ...]

> (x|> Seq.head).GetType();;
val it : System.Type =
  System.Tuple`2[System.Char,System.Collections.Generic.IEnumerable`1[System.Char]]
    {Assembly = mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;
     AssemblyQualifiedName = "System.Tuple`2[[System.Char, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Collections.Generic.IEnumerable`1[[System.Char, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
...
     DeclaredProperties = [|Char Item1;
                            System.Collections.Generic.IEnumerable`1[System.Char] Item2;
                            Int32 System.ITuple.Size|];
...;}

> x|> Seq.map (fun x -> x.Item1, x.Item2)|>dict;;

  x|> Seq.map (fun x -> x.Item1, x.Item2)|>dict;;
  ------------------------^^^^^

stdin(123,25): error FS0039: The field, constructor or member 'Item1' is not defined.

在我看来,x 是一个元组序列,其中每个元组都有一个 Item1 (Char) 和 Item2 (seq Char) 属性。我想把它变成一本字典。

显然,我错过了一些东西。谁能帮助我理解我做错了什么以及如何改正?

最佳答案

F# 似乎不像 C# 那样从底层元组中显示 Item1 和 Item2 属性。我尝试了以下方法,似乎没有错误。

使用函数 fst 和 snd:

x|> Seq.map (fun x -> fst x, snd x) |> dict

使用模式匹配:

x|> Seq.map (function (key, value) -> (key, value)) |> dict

显然不使用 Seq.map 也能工作:

x |> dict

关于f# 元组 item1 的 Seq,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45788272/

相关文章:

f# - 矩阵的内存不足异常

f# - 如何让 FSI 在 NET5 下工作并让愚蠢的 stackoverflow 消息 "Title cannot contain ..."闭嘴?

.net - 在 Visual Studio 中使用 x64 库的 F# 类型提供程序

F# multiple when 守卫在模式匹配中使用分组模式

f# - 可能的 F# 交互式 PInvoke 错误

f# - 如果列表为空,如何修复 List.head 中的异常 hell

f# - 在 F# 中将字符串转换为键值对

f# - 在 .fsproj 中为 .NET core 指定程序集版本

f# - 使用列表匹配绑定(bind)值(没有编译器警告)

F# zip 实现