Skip to content

Instantly share code, notes, and snippets.

@ppanyukov
Created June 28, 2011 18:38
Show Gist options
  • Save ppanyukov/1051835 to your computer and use it in GitHub Desktop.
Save ppanyukov/1051835 to your computer and use it in GitHub Desktop.
F# function to join sequence of strings using a delimiter without conversion to array
open System
open System.Text
/// Join a sequence of strings using a delimiter.
/// Equivalent to String.Join() but without arrays.
let join (items : seq<string>) (delim : string) =
// Collect the result in the string builder buffer
// The end-sequence will be "item1,delim,...itemN,delim"
let buff =
Seq.fold
(fun (buff :StringBuilder) (s:string) -> buff.Append(s).Append(delim))
(new StringBuilder())
items
// We don't want the last delim in the result buffer, remove
buff.Remove(buff.Length-delim.Length, delim.Length).ToString()
@derekthecool
Copy link

Hi thanks for this example!!
I have created a modified version based on your example

/// Join a sequence of strings using a delimiter.
let join (delim : string) (items : seq<'items>) =
    System.String.Join(delim, items)


// Example calls
// Join string array by spaces
printfn "%s" (join " " ["This"; "is"; "some"; "text"])

// Join int list on "-" and call from a pipeline
[1..10]
|> join "-"
|> printfn "%s"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment