How do I concatenate a list of strings in F#?

f#
24,974

Solution 1

Not exactly what you're looking for, but

let strings = [| "one"; "two"; "three" |]
let r = System.String.Concat(strings)
printfn "%s" r

You can do

let strings = [ "one"; "two"; "three" ]
let r = strings |> List.fold (+) ""
printfn "%s" r

or

let strings = [ "one"; "two"; "three" ]
let r = strings |> List.fold (fun r s -> r + s + "\n") ""
printfn "%s" r

Solution 2

> String.concat " " ["Juliet"; "is"; "awesome!"];;
val it : string = "Juliet is awesome!"

Solution 3

I'd use String.concat unless you need to do fancier formatting and then I'd use StringBuilder.

(StringBuilder(), [ "one"; "two"; "three" ])
||> Seq.fold (fun sb str -> sb.AppendFormat("{0}\n", str))

Solution 4

just one more comment,

when you are doing with string, you'd better use standard string functions.

The following code is for EulerProject problem 40.

let problem40 =
    let str = {1..1000000} |> Seq.map string |> String.concat ""
    let l = [str.[0];str.[9];str.[99];str.[999];str.[9999];str.[99999];str.[999999];]
    l |> List.map (fun x-> (int x) - (int '0')) |> List.fold (*) 1

if the second line of above program uses fold instead of concat, it would be extremely slow because each iteration of fold creates a new long string.

Solution 5

System.String.Join(Environment.NewLine, List.to_array messages)

or using your fold (note that it's much more inefficient)

List.reduce (fun a b -> a ^ Environment.NewLine ^ b) messages
Share:
24,974
Akshay Nalawade
Author by

Akshay Nalawade

Antipodean turtle stacker.

Updated on October 05, 2020

Comments

  • Akshay Nalawade
    Akshay Nalawade about 3 years

    I'm trying this at the moment, but I haven't quite got the method signature worked out... anyone? messages is a field of seq[string]

    let messageString = List.reduce(messages, fun (m1, m2) -> m1 + m2 + Environment.NewLine)