eri*_*len 6 f# functional-programming sequence
我想从F#中的序列中提取单个项目,或者如果没有或多个则提供错误.做这个的最好方式是什么?
我现在有
let element = data |> (Seq.filter (function | RawXml.Property (x) -> false | _ -> true))
|> List.of_seq
|> (function head :: [] -> head | head :: tail -> failwith("Too many elements.") | [] -> failwith("Empty sequence"))
|> (fun x -> match x with MyElement (data) -> x | _ -> failwith("Bad element."))
Run Code Online (Sandbox Code Playgroud)
它似乎有效,但它真的是最好的方式吗?
编辑:当我指出正确的方向时,我想出了以下内容:
let element = data |> (Seq.filter (function | RawXml.Property (x) -> false | _ -> true))
|> (fun s -> if Seq.length s <> 1 then failwith("The sequence must have exactly one item") else s)
|> Seq.hd
|> (fun x -> match x with MyElement (_) -> x | _ -> failwith("Bad element."))
Run Code Online (Sandbox Code Playgroud)
我想这有点好看.
序列有查找功能。
val find : ('a -> bool) -> seq<'a> -> 'a
Run Code Online (Sandbox Code Playgroud)
但如果你想确保seq只有一个元素,那么做一个Seq.filter,然后取filter后的长度并确保它等于1,然后取头。全部在Seq中,无需转换为列表。
编辑:顺便说一句,我建议检查结果的尾部length是否为空(O(1),而不是使用函数(O(n))。尾部不是 seq 的一部分,但我认为您可以找到一种模拟该功能的好方法。