F#如何根据谓词而不是固定长度来对序列进行窗口化 [英] F# how to Window a sequence based on predicate rather than fixed length
本文介绍了F#如何根据谓词而不是固定长度来对序列进行窗口化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
鉴于以下输入序列,我想生成所需的输出. 我知道,如果所有窗口的长度都是固定的,则可以使用Seq.window几乎获得所需的结果.但是,在这种情况下它们不是固定长度的,我想在遇到"a"时开始一个新序列. 标准馆藏图书馆有可能吗?
Given the following input sequence, I would like to generate the desired output. I know that Seq.window can be used to almost get the desired result if all the windows are a fixed length. However in this case they are not fixed legnth, I would like to start a new sequence whenever "a" is encountered. Is this possible with the standard collections library?
let inputSequence =
["a"; "b"; "c";
"a"; "b"; "c"; "d";
"a"; "b";
"a"; "d"; "f";
"a"; "x"; "y"; "z"]
let desiredResult =
[["a"; "b"; "c";]
["a"; "b"; "c"; "d";]
["a"; "b"; ]
["a"; "d"; "f";]
["a"; "x"; "y"; "z"]]
推荐答案
这是一种使用可变状态但非常简洁的方法:
Here's a way that uses mutable state but is pretty concise:
let mutable i = 0
[ for x in inputSequence do
if x = "a" then i <- i + 1
yield i, x ]
|> List.groupBy fst
|> List.map snd
|> List.map (List.map snd)
这篇关于F#如何根据谓词而不是固定长度来对序列进行窗口化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文