Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generic function in F#

Tags:

f#

I'm writing some kind of serialization library (for purpose of learning F#). And now I stuck with this:

Suppose we already have serialization functions for some basic types:

type StoreOps =
    static member inline store(x:int) = ...
    static member inline store(x:int64) = ...
    static member inline store(x:float) = ...
    static member inline store(x:float32) = ...
    static member inline store(x:bool) = ...
    static member inline store(x:string) = ...
    ....

Now I want to implement generic function to store any array of basic types:

let inline store(x:'T[]) = 
        x |> Array.iter StoreOps.store

, but compiler can't compile it (error message says: A unique overload for method 'store' could not be determined based on type information prior to this program point).

What is a right way to implement such functions in F#? Because I don't want to copy-paste N equal functions for int[], bool[], float[]...

like image 295
qehgt Avatar asked Mar 20 '26 20:03

qehgt


1 Answers

First of all, you probably don't need inline on the definitions which take arguments of a particular type. Secondly, the short answer is probably "there's no good way to do that". However, if you're willing to tolerate horrible hacks, you can do something like:

type StoreOps = 
    ... // everything you've currently got

let inline storeArray< ^t, ^u when (^t or ^u) : (static member store : ^u -> unit)> arr = 
    arr 
    |> Array.iter (fun x -> ((^t or ^u) : (static member store : ^u -> unit) x))

type StoreOps with
    static member inline store arr = storeArray<StoreOps,_> arr

You can also make the storeArray helper private (using let inline private storeArray... if you don't want it exposed.

like image 101
kvb Avatar answered Mar 23 '26 20:03

kvb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!