Search code examples
f#pipelineoption-typetype-inference

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 applyFirst 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?


Solution

  • 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.