[ACCEPTED]-How do I concatenate a list of strings in F#?-f#

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

0

Score: 47

Not exactly what you're looking for, but

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

You 1 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
Score: 4

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

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

just one more comment,

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

The following code is for EulerProject 4 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 3 program uses fold instead of concat, it 2 would be extremely slow because each iteration 1 of fold creates a new long string.

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

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

List.reduce (fun a b -> a ^ Environment.NewLine ^ b) messages

More Related questions