Generic higher order function

后端 未结 5 501
滥情空心
滥情空心 2020-11-30 11:55

Is there a reason why I can use a generic function with different type arguments when I pass it as a local value but not when passed as parameter? For example:



        
5条回答
  •  不知归路
    2020-11-30 12:30

    The reason for this is that when f is passed as parameter to g then the compiler will try to infer the type of f. Based on the usage of f in the body of function g, the compiler infers that the function is applied to both x and y that means that both x and y parameters has to be of same type and that is the type of the f parameter. In your code example you pass x as integer and that makes the compiler infer that y will also be of type integer.

    UPDATE:

    You can do something like:

    let g (f:obj -> obj) (x : 'a,y : 'b) = (f x :?> 'a ,f y :?> 'b)
    g id (1,"1") |> printfn "%A"
    

    The function f need to make sure it returns the same main type that it receives as obj type

提交回复
热议问题