I want to extract one element from a sequence in F # or give an error if there is none or more than one. What is the best way to do this?
I currently have
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."))
This seems to work, but is this really the best way?
Edit: Since I was directed in the right direction, I came up with the following:
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."))
I think this is a little better.
functional-programming f # sequence
erikkallen
source share