问题
The example from this post has an example
open System.IO
let lines =
File.ReadAllLines("tclscript.do")
|> Seq.map (fun line ->
let newLine = line.Replace("{", "{{").Replace("}", "}}")
newLine )
File.WriteAllLines("tclscript.txt", lines)
that gives an error when compilation.
error FS0001: This expression was expected to have type
string []
but here has type
seq<string>
How to convert seq to string[] to remove this error message?
回答1:
Building on Jaime's answer, since ReadAllLines()
returns an array, just use Array.map
instead of Seq.map
open System.IO
let lines =
File.ReadAllLines("tclscript.do")
|> Array.map (fun line ->
let newLine = line.Replace("{", "{{").Replace("}", "}}")
newLine )
File.WriteAllLines("tclscript.txt", lines)
回答2:
You can use
File.WriteAllLines("tclscript.txt", Seq.toArray lines)
or alternatively just attach
|> Seq.toArray
after the Seq.map call.
(Also note that in .NET 4, there is an overload of WriteAllLines that does take a Seq)
回答3:
Personally, I prefer sequence expressions over higher-order functions, unless you're piping the output through a series of functions. It's usually cleaner and more readable.
let lines = [| for line in File.ReadAllLines("tclscript.do") -> line.Replace("{", "{{").Replace("}", "}}") |]
File.WriteAllLines("tclscript.txt", lines)
With regex replacement
let lines =
let re = System.Text.RegularExpressions.Regex(@"#(\d+)")
[|for line in File.ReadAllLines("tclscript.do") ->
re.Replace(line.Replace("{", "{{").Replace("}", "}}"), "$1", 1)|]
File.WriteAllLines("tclscript.txt", lines)
来源:https://stackoverflow.com/questions/6156358/converting-seqstring-to-string-in-f