Converting seq<string> to string[] in F#

与世无争的帅哥 提交于 2019-12-24 10:12:42

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!