简体   繁体   English

转换序列<string>到 F# 中的字符串 []</string>

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

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?如何将 seq 转换为 string[] 以删除此错误消息?

Building on Jaime's answer, since ReadAllLines() returns an array, just use Array.map instead of Seq.map基于 Jaime 的回答,由于ReadAllLines()返回一个数组,只需使用Array.map而不是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)

You can use您可以使用

File.WriteAllLines("tclscript.txt", Seq.toArray lines)

or alternatively just attach或者只是附加

|> Seq.toArray

after the Seq.map call.在 Seq.map 调用之后。

(Also note that in .NET 4, there is an overload of WriteAllLines that does take a Seq) (另请注意,在 .NET 4 中,确实需要 Seq 的 WriteAllLines 过载)

Personally, I prefer sequence expressions over higher-order functions, unless you're piping the output through a series of functions.就个人而言,我更喜欢序列表达式而不是高阶函数,除非您通过一系列函数来传递 output。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM