开发者

Collapse option type creation

If I specify function value as:

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

then F# infers the f type as f: 'a -> b' option. It's ok, I understand why F# infers f's return type as 'b option. But I want f to be f: 'a -> 'b, and it can be done by changing applyFirst function:

let applyFi开发者_如何学Crst f elements = 
    if Seq.isEmpty elements then None else elements |> Seq.head |> f |> Some

But wonder if there's some more elegant way to do this?


You can do

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

But I think I prefer

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

as more readable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜