Thomas
Thomas

Reputation: 12107

Using StringBuilder with a computation expression, in F#

I have a lot of code using string builders and I am looking for a way to simplify the syntax.

I started to look at this snippet: http://www.fssnip.net/7WR/title/Computation-expression-over-StringBuilder.

First, I am a vague general idea about computation expressions, but I have never written one and this is something I was hoping to understand better by using this snippet.

The snippet can be used very simply:

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

and this all works well, and outputs a string.

The question arises when processing lists. I have code like:

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

this will definitely not work because of the map. How can I make this work?

Upvotes: 0

Views: 196

Answers (1)

Fyodor Soikin
Fyodor Soikin

Reputation: 80744

First off: from the usage of Map.map (as opposed to List.map), it appears that your myList is actually a map, not a list.

Now, the snippet you linked does offer an example of using a sequence of something inside the computation builder:

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

You could use this facility to iterate over your map. One thing to notice is that when a Map is iterated over, the element type is KeyValuePair<_, _>, whose values can be accessed via the .Value property:

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

Upvotes: 1

Related Questions