在 F# 中拆分序列 [英] Split seq in F#
问题描述
我应该通过元素的属性将seq
拆分为seq
.如果此属性等于给定值,则必须在该点拆分".我怎样才能在 FSharp 中做到这一点?
I should split seq<a>
into seq<seq<a>>
by an attribute of the elements. If this attribute equals by a given value it must be 'splitted' at that point. How can I do that in FSharp?
如果必须在该项目处拆分或不拆分,则向它传递一个返回布尔值的函数"应该会很好.
It should be nice to pass a 'function' to it that returns a bool if must be splitted at that item or no.
示例:输入序列:seq:{1,2,3,4,1,5,6,7,1,9}
当它等于 1 时,它应该在每个项目处被拆分,所以结果应该是:
Sample:
Input sequence: seq: {1,2,3,4,1,5,6,7,1,9}
It should be splitted at every items when it equals 1, so the result should be:
seq
{
seq{1,2,3,4}
seq{1,5,6,7}
seq{1,9}
}
推荐答案
您真正要做的就是分组——每次遇到值时创建一个新组.
All you're really doing is grouping--creating a new group each time a value is encountered.
let splitBy f input =
let i = ref 0
input
|> Seq.map (fun x ->
if f x then incr i
!i, x)
|> Seq.groupBy fst
|> Seq.map (fun (_, b) -> Seq.map snd b)
示例
let items = seq [1;2;3;4;1;5;6;7;1;9]
items |> splitBy ((=) 1)
再一次,更短,Stephen 有很好的改进:
Again, shorter, with Stephen's nice improvements:
let splitBy f input =
let i = ref 0
input
|> Seq.groupBy (fun x ->
if f x then incr i
!i)
|> Seq.map snd
这篇关于在 F# 中拆分序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!