在 F# 中将 StringBuilder 与计算表达式一起使用

Using StringBuilder with a computation expression, in F#

我有很多使用字符串生成器的代码,我正在寻找一种简化语法的方法。

我开始看这个片段:http://www.fssnip.net/7WR/title/Computation-expression-over-StringBuilder

首先,我对计算表达式的概念很模糊,但我从来没有写过,这是我希望通过使用这个片段更好地理解的东西。

代码段使用起来非常简单:

stringBuffer
    {
        "my first string\n"
        "and the second one\n"
        sprintf "hello %s" "thomas"
    }

这一切都很好,并输出一个字符串。

问题出现在处理列表的时候。 我有这样的代码:

myList |> Map.map (fun _ data -> data.DescribeIntoAString)

因为地图的缘故,这肯定行不通。我怎样才能使这项工作?

首先:从 Map.map 的用法(与 List.map 相对)看来,您的 myList 实际上是一个地图,而不是列表。

现在,您链接的代码片段确实提供了在计算生成器中使用一系列内容的示例:

let bytes2hex (bytes: byte array) : string =
    stringBuffer {
        for b in bytes -> b
    }

您可以使用此工具迭代您的地图。需要注意的一件事是,当 Map 被迭代时,元素类型是 KeyValuePair<_, _>,其值可以通过 .Value 属性:

访问
stringBuffer {
    for kvp in myList -> kvp.Value.DescribeIntoAString
}