Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
717 views
in Technique[技术] by (71.8m points)

f# - Split item in list while keeping the order

I have a list of items looking something like this:

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

I need to split every item containing the word and into separate items and re-insert them into the list, while keeping the order. Is there any elegant and efficient way how to do this? Currently I am using a loop and mutable list for aggregation:

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

I have a suspicion that there is a better way to do this (more functional, less C#-y), but I cannot find out how to do it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Some one better at FP might come and improve this because I am also still learning things but here is my take.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...