c# - How is F#'s static bound constraints implemented? -
in f#, can perform black-magic voodoo1 , perform static typed constraints ensure function called on types have member constraints. example:
module collection let inline init s = let collection = new ^t() let add e = (^t : (member add : 'a -> unit) collection, e) seq.iter add s collection
this function can called type has add<'a>
has signature 'a -> unit
.
usage:
let a:list<_> = collection.init {1..10} let b:synchronizedcollection<_> = collection.init {1..10} |> seq.iter (fun x -> printf "%a " x) b |> seq.iter (fun x -> printf "%a " x)
output:
1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10
i'm interested in taking advantage of kind of functionality in c# application, have no idea kind of pitfalls or trouble can expect trying this.
in interest of avoiding x-y problem, have wcf generated client hacked manually edited mess. not using not option reasons. many types have member properties same name different types , no common type, interest in type of generic constraint.
is functionality in f# viable solution problem? how implemented? know c# can nothing this...
1not really, don't know how, question.
in f#, static member constraints (which name of voodoo) implemented inlining code of init
function each time called , generating specialized code each use.
in general, .net generic constraints not rich enough express member constraints , cannot directly mapped ordinary .net generic constraints.
when write:
let a:list<_> = collection.init {1..10} let b:synchronizedcollection<_> = collection.init {1..10}
the compiler replace collection.init
body of function , replace call written using static member constraint call concrete add
method of concrete type. if call appears in generic function concrete type cannot determined, not allowed.
i think use f# , static member constraints simplify working code many types share properties without deeper relationship. however, static member constraints f# specific , there no way of defining helper functions using them called c#. have write larger portion of client in f# (and perhaps expose nice clean api hides underlying types).
Comments
Post a Comment