开发者

Collapse option type creation

开发者 https://www.devze.com 2023-04-04 05:21 出处:网络
If I specify function value as: let applyFirst f elements = if Seq.isEmpty elements then None else elements |> Seq.head |> f

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

精彩评论

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

关注公众号