c# - How to support structurally-typed in a nominal-typed language? -
in f#, nominative or structural?, answer said can trick f# work structurally-typed language via exotic mechanisms. how can so?
the "exotic mechanism" previous answer refers statically resolved type parameters. lets write functions take object of type has specific member. example, can write sayhello
function work object has name
member of type string
:
let inline sayhello (any : ^t) = let name = (^t : (member name : string) any) printfn "hello %s" name
this work 2 types nominally unrelated:
type person(name:string) = member x.name = name type animal(name:string) = member x.name = name sayhello (person("tomas")) sayhello (animal("bunny"))
that said, f# nominally typed language , relying on static member constraints unidiomatic. make code bad , you'll hit limitations of mechanism. nice feature some limited use cases, it's not primary abstraction mechanism in f#.
Comments
Post a Comment