【发布时间】:2011-11-21 04:47:47
【问题描述】:
我需要一个类似Seq.head 的函数,但在序列为空时返回None 而不是抛出异常,即seq<'T> -> 'T option。
有很多方法可以做到这一点。这里有几个:
let items = Seq.init 10 id
let a = Seq.tryFind (fun _ -> true) items
let b = Seq.tryPick Some items
let c = if Seq.isEmpty items then None else Some (Seq.head items)
let d =
use e = items.GetEnumerator()
if e.MoveNext() then Some e.Current
else None
b 是我使用的那个。两个问题:
- 有没有特别惯用的方法来做到这一点?
- 由于没有内置的
Seq.tryHead函数,这是否表明这不是必需的、不常见的,或者没有函数更好地实现?
更新
tryHead has been added to the standard library in F# 4.0。
【问题讨论】:
-
下面库FSharpx.Collectionsfsprojects.github.io/FSharpx.Collections中有一个Seq.tryHead@