Search code examples
seriesrebolrebol3red-lang

Inverse of `split` function: `join` a string using a delimeter


IN Red and Rebol(3), you can use the split function to split a string into a list of items:

>> items: split {1, 2, 3, 4} {,}
== ["1" " 2" " 3" " 4"]

What is the corresponding inverse function to join a list of items into a string? It should work similar to the following:

>> join items {, }
== "1, 2, 3, 4"

Solution

  • There is an old modification of rejoin doing that

    rejoin: func [
        "Reduces and joins a block of values - allows /with refinement." 
        block [block!] "Values to reduce and join" 
        /with join-thing "Value to place in between each element" 
    ][ 
        block: reduce block 
        if with [ 
            while [not tail? block: next block][ 
                insert block join-thing 
                block: next block
           ] 
           block: head block 
        ] 
        append either series? first block [ 
           copy first block
        ] [
           form first block
        ] 
        next block 
    ]
    

    call it like this rejoin/with [..] delimiter

    But I am pretty sure, there are other, even older solutions.