.NET StringBuilder的功能版本是否有开源(非GPL)实现? [英] Is there an open-source (non GPL) implementation of a functional version of .NET StringBuilder?

查看:150
本文介绍了.NET StringBuilder的功能版本是否有开源(非GPL)实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找StringBuilder或等效版本的功能性(非强制性)实现.我已经看到了几个功能数组的实现,但是它们并不原生支持插入.开源的非(L?A?)GPL奖金,F#的奖金,但我可以根据需要从Haskell/OCaml/SML进行翻译.

I'm looking for a functional (as in, non-imperative) implementation of StringBuilder or equivalent. I've seen a couple of functional arrays implementation, but they don't support insertion natively. Bonus for open-source, non-(L?A?)GPL, bonus for F#, but I can translate from Haskell/OCaml/SML if needed.

欢迎提出算法建议.

推荐答案

StringBuilder相对于string的优势是由于最小化了分配.它预分配了一个缓冲区,以避免为每个插入/追加分配.这需要可变性-某些对象必须拥有(并变异)缓冲区.

StringBuilders advantage over string is due to minimizing allocations. It pre-allocates a buffer to avoid allocating for every insert/append. This requires mutability--some object must own (and mutate) the buffer.

顺便说一句,System.String已经符合您的描述(我能做出的):它是不可变的,并支持串联,

Incidentally, System.String already fits (what I can make of) your description: it's immutable and supports concatenation, insertionMSDN, and removalMSDN.

托马斯的想法吸引了我.接受他的想法,这就是我的想法

Tomas' idea intrigued me. Taking his idea, here's what I came up with

type StringBuilder =
  private
  | Empty
  | StringBuilder of int * string * int * StringBuilder
  member this.Length =
    match this with 
    | Empty -> 0
    | StringBuilder(_, _, n, _) -> n
  override this.ToString() =
    let rec rev acc = function
      | Empty -> acc
      | StringBuilder(idx, str, _, bldr) -> rev ((idx, str)::acc) bldr
    let buf = ResizeArray(this.Length)
    for idx, str in rev [] this do buf.InsertRange(idx, str)
    System.String(buf.ToArray())

[<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]
[<RequireQualifiedAccess>]
module StringBuilder =
  let empty = Empty
  let length (bldr:StringBuilder) = bldr.Length
  let insert index str bldr = 
    if index < 0 || index > (length bldr) then invalidArg "index" "out of range"
    StringBuilder(index, str, str.Length + bldr.Length, bldr)
  let create str = insert 0 str empty
  let append str bldr = insert (length bldr) str bldr
  let remove index count (bldr:StringBuilder) = create <| bldr.ToString().Remove(index, count)

用法

let bldr = 
  StringBuilder.create "abcdef"
  |> StringBuilder.insert 1 "xyz"
  |> StringBuilder.append "123"
  |> StringBuilder.remove 1 2

bldr.ToString() //azbcdef123

它是持久性的,插入是O(1).

It's persistent and insertion is O(1).

这篇关于.NET StringBuilder的功能版本是否有开源(非GPL)实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆