Search code examples
optimizationlambdaf#inlineinlining

Are all the lambda argument automatically inlined in F#


This post from F# News states that F# can inline a function passed as an argument. Is it always the case? Does it happen automatically?


Solution

  • The answer is no. If you have a function like the following, lambdas do not get inlined. In the following code lambdas are invoked using FSharpFunc<,>.InvokeFast()

    let fold f s l = 
        let rec loop acc l =
            match l with []->acc |h::t->loop (f acc h) t
        loop s l
    
    let list = [1;2;3;4]
    
    list|>fold (fun acc x->x+acc) 0|>printfn "%d"
    list|>fold (fun acc x->x*acc) 1|>printfn "%d"
    

    But if you mark fold function as inline situation changes. Not only fold function gets inlined, but lambdas get inlined as well. I used .NET Reflector to confirm that.