Generic higher order function

后端 未结 5 496
滥情空心
滥情空心 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:32

    Here's the inline magic. Let's take kvb's code and define a single gmap function that handles all cases:

    let inline gmap f (x, y) = f $ x, f $ y
    
    type One = One with static member ($) (One, x) = 1  // Example1 ConvertAll
    type Id  = Id  with static member ($) (Id , x) = x  // Example2 PassThrough
    
    type SeqSingleton  = SeqSingleton  with static member ($) (SeqSingleton , x) = seq [x]
    type ListSingleton = ListSingleton with static member ($) (ListSingleton, x) = [x]
    type ListHead      = ListHead      with static member ($) (ListHead, x) = List.head x
    
    // Usage
    let pair1 = gmap One ("test", true)
    let pair2 = gmap Id  ("test", true)
    let pair3 = gmap SeqSingleton  ("test", true)
    let pair4 = gmap ListSingleton ("test", true)
    let pair5 = gmap ListHead (["test";"test2"], [true;false])
    
    let pair6 = ("test", true) |> gmap ListSingleton |> gmap ListHead
    
    (* results
    val pair1 : int * int = (1, 1)
    val pair2 : string * bool = ("test", true)
    val pair3 : seq * seq = (["test"], [true])
    val pair4 : string list * bool list = (["test"], [true])
    val pair5 : string * bool = ("test", true)
    val pair6 : string * bool = ("test", true)
    *)
    

    UPDATE

    It's also possible to use the even more generic gmap function defined here then it will also work with n-uples (n < 9).

提交回复
热议问题