从F#中的列表中提取单个元素

时间:2009-05-05 16:50:07

标签: 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."))

它似乎有效,但它真的是最好的方式吗?

编辑:当我指出正确的方向时,我想出了以下内容:

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."))

我想这有点好看。

6 个答案:

答案 0 :(得分:4)

以现有序列标准函数的风格完成

#light

let findOneAndOnlyOne f (ie : seq<'a>)  = 
    use e = ie.GetEnumerator()
    let mutable res = None 
    while (e.MoveNext()) do
        if f e.Current then
            match res with
            | None -> res <- Some e.Current
            | _ -> invalid_arg "there is more than one match"          
    done;
    match res with
        | None -> invalid_arg "no match"          
        | _ -> res.Value

你可以做一个纯粹的实现,但它最终会通过箍跳到正确和有效(在第二场比赛中快速终止真的需要一个标记'我发现它已经'')

答案 1 :(得分:3)

序列有一个查找功能。

val find : ('a -> bool) -> seq<'a> -> 'a

但是如果你想确保seq只有一个元素,那么做一个Seq.filter,然后取过滤器后的长度并确保它等于1,然后取头。全部在Seq中,无需转换为列表。

编辑: 另外,我 建议检查结果的 tail 是否为空(O(1),而不是使用函数length( O(n))。尾部不是seq的一部分,但我认为你可以找到一种模拟该功能的好方法。

答案 2 :(得分:1)

使用此:

> let only s =
    if not(Seq.isEmpty s) && Seq.isEmpty(Seq.skip 1 s) then
      Seq.hd s
    else
      raise(System.ArgumentException "only");;
val only : seq<'a> -> 'a

答案 3 :(得分:1)

使用现有的库函数有什么问题?

let single f xs = System.Linq.Enumerable.Single(xs, System.Func<_,_>(f))

[1;2;3] |> single ((=) 4)

答案 4 :(得分:0)

我的两分钱......这适用于选项类型,所以我可以在我的自定义monad中使用它。可以很容易地修改,但改为使用例外

let Single (items : seq<'a>) =
    let single (e : IEnumerator<'a>) =
        if e.MoveNext () then
            if e.MoveNext () then
                raise(InvalidOperationException "more than one, expecting one")
            else
                Some e.Current
        else
            None
    use e = items.GetEnumerator ()
    e |> single

答案 5 :(得分:0)

更新的答案是使用Seq.exactlyOne引发ArgumentException