折叠选项类型创建

时间:2011-09-13 04:58:05

标签: f# option type-inference pipeline

如果我将功能值指定为:

let applyFirst f elements = 
    if Seq.isEmpty elements then None else elements |> Seq.head |> f

然后F#将f类型推断为f: 'a -> b' option。没关系,我理解为什么F#将f的返回类型推断为'b option。但我希望ff: 'a -> 'b,可以通过更改applyFirst功能来完成:

let applyFirst f elements = 
    if Seq.isEmpty elements then None else elements |> Seq.head |> f |> Some

但是想知道是否有更优雅的方法来做到这一点?

1 个答案:

答案 0 :(得分:2)

你可以做到

let applyFirst f elems = elems |> Seq.tryPick (f >> Some)

但我认为我更喜欢

let applyFirst f elems = 
    if Seq.isEmpty elems then 
        None 
    else 
        Some( f(Seq.head elems) )

更具可读性。