List with mixed parameterized types

Given a type with a type parameter, is it possible to create a list containing values ​​with mixed specific types? See code below. Everything works fine until I try to create list2 where some elements have an int for data and others have a float. Is there any way to do this? My attempt on list3 does not compile.

type Holder<'data> = {
    Data : 'data
    Name : String
}

let intVal =
    {Data = 23;
    Name = "Bill"}

let intVal2 =
    {Data = 29;
    Name = "Cindy"}

let floatVal =
    {Data = 23.0;
    Name = "John"}

let list1 = [intVal; intVal2]
let list2 = [intVal; floatVal]
let list3 : Holder<'a> list = [intVal; floatVal]
+4
source share
1 answer

When creating a list, list items must be of the same type. This means that you cannot create a list containing Holder<int>and Holder<float>.

If you want to create a mixed type list, you can either define a discriminatory union:

type Value = 
  | Float of Holder<float>
  | Int of Holder<int>

And create a list of types Valueusing:

let list = [Int intVal; Float floatVal]

, (, Name) . :

type IHolder = 
  abstract Name : string

type Holder<'data> = 
  { Data : 'data
    Name : string }
  interface IHolder with
    member x.Name = x.Name

Holder<_>, IHolder:

let list = [intVal :> IHolder; floatVal :> IHolder]
for h in list do printfn "%s" h.Name

, . , , .

+6

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


All Articles