Consider I have two different library types:
type Foo = { foo : string }
type Bar = { bar : int32 }
I want to implement generic function zoo
that will work for either Foo
or Bar
instances. And I cannot change Foo
and Bar
because they are part of library code.
Here's my first attempt using type extensions and inline function as explained here:
// Library.fs
module Library
type Foo = { foo : string }
type Bar = { bar : int32 }
// Program.fs
type Foo with
static member zoo (f : Foo) = "foo"
type Bar with
static member zoo (b : Bar) = "bar"
let inline zoo (x : ^t) =
(^t : (static member zoo : ^t -> string) x)
let f = zoo { foo = "1" } // error FS0001: The type 'Foo' does not support the operator 'zoo'
Why don't inline function definition relies on type extensions? How could I solve my problem without changing of the initial Foo
and Bar
type definitions?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…