Use function with argument of derived type (F #)

I have a class in my application - for simplicity, suppose it is defined as follows:

type baseType() = member this.A = 5. 

In addition, I have many functions that take objects of this type as an argument. Moreover, some of them take an array of this type:

 let myFun (xArr : baseType[]) = // ... do something inspirig ;) 

Now I realized that it would be nice to have another class that comes from "baseType". eg:.

 type inhType() = inherit baseType() member this.B = 8. 

However, I cannot use arrays of the inherited type with functions such as "myFun"

 let baseArr = [| baseType() |] let inhArr = [| inhType() |] myFun baseArr myFun inhArr // won't work 

which would be "nice to have." Is there an easy way to reuse my functions without making so many changes?

I assume that one solution is to display my array using, for example, the function (fun (d: inhType) -> d:> baseType), but I'm wondering if there is anything else.

+6
source share
2 answers

You need to annotate your function as accepting a flexible type .

 type A() = class end type B() = inherit A() let aArr = [| A() |] let bArr = [| B() |] // put # before type to indicate it a flexible type let f (x : #A[]) = () f aArr f bArr // works! 
+9
source

You can also populate array A instances of subtype B using type annotation:

 let bArr: A[] = [| B() |] 

This can be useful for one-time use or if the function is in a third-party library. Another common use is to create arrays in a box ( obj[] ).

+3
source

Source: https://habr.com/ru/post/951760/


All Articles