Document, Text, String Builder

If I wanted to use either Document, Text, or String Builder to perform a host a general functions which one of these builders would be the more functional option?

let doc = new Document()

// file or string must build or append here

doc.Save("dest.tmp")

Unless I’m looking at a different Document or Text class than you are, neither are really suitable as a “builder”.

which one of these builders would be the more functional option?

When you say “functional option,” are you referring to Functional Programming, or are you just generally asking which is going to work the best? If you’re looking for an FP option, you might want to consider making an array or list of strings and then accumulate them into a final string with String.Join or even just use File.WriteAllLines which takes an array anyway.

StringBuilder does not have an FP interface, but is a very efficient imperative programming approach for assembling a string through imperative statements (much better performance than +). In fact, String.Join is built using StringBuilder. (see string.cs (microsoft.com))

To answer - speed is an option only when imperative, otherwise counter imperative and generic immutability is a general focus. Right, now, I have this:

  let doc = File.CreateText(Filename)
    doc.WriteLine(Data)
    doc.Close()

But I like how this formula is shown with new Document() first, build or write, and then Save verses File.CreateText, write, and Close.

Here’s how you would do it with StringBuilder

let doc = 
  let sb = new StringBuilder ()
  sb.AppendLine (data)
  if f x then sb.AppendLine (g x)
  for y in ys do
    sb.AppendLine (y)
  string sb

File.WriteAllText (filename, doc)

Here’s how you would do it with just Arrays:

let docContents = 
  [| 
    yield data
    if f x then yield (g x)
    for y in ys do
      yield y
  |]


File.WriteAllLines (filename, docContents)

I don’t think that Document or Text will allow you to do this.

But I like how this formula is shown with new Document() first, build or write, and then Save verses File.CreateText, write, and Close.

I don’t understand what the differences are between the style you like and the style you dislike. Personally I’m more partial to the arrays approach because it performs roughly the same but avoids any mutable objects, but you can see from the code that they’re very similar in implementation. One advantage to both of these approaches is that you won’t get a partially-written file if it were to crash while assembling the contents. It only saves to the file once it’s done assembling everything.