How to maintain a structurally typed language with a generic type?

In F #, Nominal or Structural? , the answer said that I can trick F # to work like a structured language through some exotic mechanisms. How can i do this?

+3


source to share


1 answer


The "exotic mechanism" referenced in the previous answer is probably statically resolved type parameters . This allows you to write functions that take any type of object that has a specific member. For example, you can write a function sayHello

that will work on any object that has a Name

type member string

:

let inline sayHello (any : ^T) = 
  let name = (^T : (member Name : string) any)
  printfn "Hello %s" name

      

This will now work with two types that are nominally unrelated:



type Person(name:string) = 
  member x.Name = name

type Animal(name:string) = 
  member x.Name = name

sayHello (Person("Tomas"))
sayHello (Animal("Bunny"))

      

However, F # is primarily a typed language, so relying too much on static member constraints would be uniomatic. This will make your code look bad and you are likely to run into mechanism limitations. This is a nice feature for some limited use cases, but it's not the main abstraction mechanism in F #.

+8


source







All Articles