How to access the same label from more then one record type?
Is it possible to have one function call the same label from different
record types? For example lets say there are two records, defined below
type Pen = {
Diameter: float
InkColor: string
}
type Pencil = {
Diameter: float
Hardness: int
Blackness: int
}
Can I make a function to access the Diameter label from either record
type? Right now if I define a pen and pencil, the compiler is confused on
which record type to use. Problem is I don't want the compiler to pick a
type, of if it does pick something, allow the use of both types. The
example wont compile because it expects a pen.
let black_pen = {
Diameter = 0.7
InkColor = "Black"
}
let mechanical_pencil = {
Diameter = 0.5
Hardness = 1
Blackness = 2
}
let getDiameter writing_utility =
let {Diameter = dia} = writing_utility
dia
printf "%A" (getDiameter black_pen)
My only options I see now are:
Combine the records with an enumerated type to tell which is what object.
Then pattern match
Use classes instead to use inherit
Use a dynamic type and reflection to check the label and type
It would be nice if I could use generics for something like this:
let getDiameter writing_utility =
let {Diameter<float> = dia} = writing_utility
dia
This was as long as the record has a label "Diameter" and is a float, it
will return the value.
No comments:
Post a Comment