在保持顺序的同时拆分列表中的项目

f#

我有一个看起来像这样的项目列表:

let myList = [ "One"; "Two"; "Three and Four"; "Five"; "and Six"; "Seven and"; "Nine and Ten and Eleven" ]

我需要将包含单词的每个项目拆分and为单独的项目,然后将它们重新插入列表,同时保持顺序。有没有什么优雅有效的方法来做到这一点?目前我正在使用循环和可变列表进行聚合:

let mutable result = []
for item in myList do
  let split = item.Split("and", StringSplitOptions.RemoveEmptyEntries)
  for subItem in split do
    result <- subItem::result
    
List.rev result

我怀疑有更好的方法来做到这一点(更多功能,更少的 C#-y),但我不知道如何去做。

回答

一些更擅长 FP 的人可能会来改进这一点,因为我还在学习东西,但这是我的看法。

let myList = [ "One"; "Two"; "Three and Four"; "Five"; "and Six"; "Seven and"; "Nine and Ten and Eleven" ]

myList
|> Seq.collect (fun x -> x.Split("and", StringSplitOptions.RemoveEmptyEntries))
|> Seq.toList


以上是在保持顺序的同时拆分列表中的项目的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>