我想从F#中的一个序列中提取单个项目,或者在没有或多个项目时发出错误。做这个的最好方式是什么?从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."))
看来工作,但它真的是最好的方法是什么?
编辑:正如我指出了正确的方向,我想出了以下内容:
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."))
我想这是一个更好一点。
你能提供一个样本序列,你在找什么? – 2009-05-05 17:17:46
我不觉得有必要。我想找到第一个值,并在出现多个错误时给出错误。就是这样 – erikkallen 2009-05-05 18:05:57
+1 - 你想要一个F#相当于一个有用的LINQ运算符(System.Linq.Enumerable.Single) - 通常情况就是这样! – 2009-05-25 09:53:05