开发者

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

I'm trying this at th开发者_开发问答e 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)


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


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


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


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜