FSharpPlus icon indicating copy to clipboard operation
FSharpPlus copied to clipboard

Add more string functions - StringBuilder extension

Open cannorin opened this issue 6 years ago • 5 comments

Description

https://github.com/fsprojects/FSharpPlus/issues/158#issuecomment-512607693

For the StringBuilder extension, it will be used like below with the String.build function from my String.fs:

let s =
  String.build (fun builder ->
    builder.printfn "%s" "hello"
    builder.printfn "%i%i" 4 2
    ...
  )

The motivation to use this extension is to avoid the repetitive use of ignore caused by the fact StringBuilder's Write and WriteLine returns the StringBuilder for method chaining. Also, sb.WriteLine(sprintf "%i" 42).WriteLine(sprintf "%s" "foo").ToString() looks odd and ugly imo, but this might be just a personal impression.

https://github.com/fsprojects/FSharpPlus/issues/158#issuecomment-512721780

the build and the StringBuilder functions looks nice to me, but let's open another issue for StringBuilder extensions as at the moment we don't have any of them, and it might require more discussion.

Referece implementation:

From cannorin/prelude.fs:


let build (builder: StringBuilder -> unit) =
  let sb = new StringBuilder()
  builder sb
  sb.ToString()

type StringBuilder with
  member inline this.printf format =
    Printf.kprintf (fun s -> this.Append s |> ignore) format

  member inline this.printfn format =
    Printf.kprintf (fun s -> this.AppendLine s |> ignore) format

cannorin avatar Jul 29 '19 10:07 cannorin

Have you seen the new proposal of adding a string computation expression?

Looks like it will cover this.

gusty avatar Jul 30 '19 00:07 gusty

I didn't notice this exists: https://github.com/fsharp/fslang-suggestions/issues/775 and it looks nice. If it gets approved then we don't need to add this, I think.

cannorin avatar Jul 30 '19 04:07 cannorin

It's an interesting suggestion. I could imagine that using some custom CE with a few custom verbs to help with templating could be quite helpful.

wallymathieu avatar Jul 30 '19 16:07 wallymathieu

I propose let's put in hold for now, for the above reasons plus it looks to me like that proposal it's gonna be approved. If it's declined we can add something, either this original proposed code, or the builder from @vasily-kirichenko if he agrees.

gusty avatar Jul 31 '19 22:07 gusty

Perhaps something to try out in a separate repository to see what's possible?

wallymathieu avatar Aug 01 '19 06:08 wallymathieu