mwjackson
mwjackson

Reputation: 5451

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

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)

Upvotes: 30

Views: 28674

Answers (5)

Brian
Brian

Reputation: 118935

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

Upvotes: 48

Yin Zhu
Yin Zhu

Reputation: 17119

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.

Upvotes: 2

gradbot
gradbot

Reputation: 13862

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))

Upvotes: 5

Juliet
Juliet

Reputation: 81536

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

Upvotes: 50

Dario
Dario

Reputation: 49228

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

Upvotes: 1

Related Questions