Is there an open-source (non GPL) implementation of a functional version of .NET StringBuilder?

前端 未结 2 1916
感动是毒
感动是毒 2021-01-15 12:28

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

2条回答
  •  难免孤独
    2021-01-15 13:04

    I don't know about any implementation that would do exactly what you want. However, I don't think you can ever get O(1) complexity of inserting (at arbitrary index) and O(n) complexity of iteration over the results.

    If you're happy to sacrifice the complexity of insertion, then you can use just string as Daniel suggests. On the other side, if you're willing to sacrifice the complexity of toString, then you can make immutable data structure with O(1) insertion at any location by using a list of strings and indices:

    type InsertList = IL of (int * string) list 
    
    // Insert string 'str' at the specified index 
    let insertAt idx str (IL items) = IL (idx, str)::items
    
    // Create insert list from a string
    let ofString str = IL [str]
    

    The conversion to string is a bit more tricky. However, I think you can get O(n log n) complexity by using a mutable LinkedList and inserting individual characters at the right location by iterating over the insertions from the end. The use of LinkedList is going to be locallized to toString, so the data structure is still purely functional.

提交回复
热议问题