【发布时间】:2018-06-17 12:20:01
【问题描述】:
我需要从带有文本行的长序列中过滤数据。 文本行形成如下记录:
{
BEGINTYPE1
VAL1: xxx
VAL2: yyy
ENDTYPE1
// mix of record types including TYPE1
}
我需要在处理过程中保持状态:
- 找到记录类型,从而跳过其他文本
- 过滤相关值,直到找到记录结尾
- 继续 1
我只能用一个列表来做到这一点,因为一个序列似乎 用一种表达方式读到最后。 它“似乎”您不能处理序列的一部分并在另一个表达式中继续使用序列“指针”在它停止的位置? 所以我使用了一个列表。 我的问题,这个处理可以用一个序列来完成吗 使用标准功能,如 Skip、filter ... 等?
我的列表解决方案:
let patLst = [
"VAL1:" ;
"VAL2:" ;
// ..
]
let BeginRecord1 = "BEGINTYPE1"
let EndRecord1 = "ENDTYPE1"
let filter (lines:seq<string>) =
let llines = Seq.toList lines
let matchLine inp =
let rec loop pat =
match pat with
| [] -> None
| h::t ->
let m = Regex.Match(inp, h)
match m.Success with
| true -> Some (h)
| _ -> loop t
loop patLst
let rec findItem i l =
match l with
| [] -> []
| h::t -> if h=i then t
else findItem i t
let findItemsUntil u a l =
let rec loop a l =
match l with
| [] -> ([],a)
| h::t when h=u -> (t , ""::a)
| h::t -> match matchLine h with
| Some(m) -> loop (m::a) t
| None -> loop a t
loop a l
let rec loop a l =
match findItem BeginRecord1 l with
| [] -> List. rev a
| l2 -> let (l3,a) = findItemsUntil EndRecord1 a l2
loop a l3
llines |> loop [""] |> List.fold (fun a x -> a + "\n" + x) ""
}
【问题讨论】:
-
你能格式化你的代码吗?