我想從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