Inheriting a Model Using Programming Style Data Types

I recently used F # and tried to use the code functionally, rather than doing OOP again in a different syntax. I ran into a problem that I could solve with a combination of inheritance and discriminatory unions, but for which I am trying to find an idea of ​​a purely functional style.

What I want to simulate is something like this (modified to save the template, as I cannot use the actual code):

type Shape =
    | Rectangle of Size * Size
    | Circle of Diameter

So far, so good, but now I need to introduce a set of additional properties related to various types of shapes, for example:

type ShapeProperty =
    | Color of Shape * Color // Fine, valid for all shapes
    | Rotation of Shape * Angle // Wants to be Rotation of Rectangle * Angle
    | Details of Shape * int // Wants to be Detail of Circle * int

If instead of using the discriminatory union for Shape, I used the base class and inheritance, I could refer to the actual types and make sure that Rotation can only be applied to the Rectangle, not the Circle, but now I can’t, Is there a way to implement something similar, while maintaining purely functional data structures?

Edit:

My current solution is to separate the definition of individual shapes from the fact that the shapes are generally connected, for example:

type Rectangle = Rectangle of Size * Size // Or using a record type
type Circle = Circle of Diameter // Or using a record type
type Shape = RectangleShape of Rectangle | CircleShape of Circle

which means that I then have a type to reference in ShapeProperty:

type ShapeProperty =
    | Color of Shape * Color
    | Rotation of Rectangle * Angle
    | Details of Circle * int

This is a bit awkward, because now I need to encapsulate each shape in the Shape type to store them in the collection, but it gives me a way to express the type safety I need. Any improvements in this are welcome.

+3
1

, . , , , , .

( , - ), ( ), .

, , (LSP), , , . (.. " : ", : , , Cat: CatDog, , . .)

, : " OCaml?" , "O" ...

, () ( ). ADT ,

, : , : ,

type ShapeProperty =   | Foo of Shape   |   | Blah of Circle;;

, shape, (, ), - , , .

, YMMV .. Haskell ( ML) , " ", /, " " " ", .

, , , , , , , , , ( , , ).

, , , , - . "", , , ". , , , . , , int, , , , , , int?

+9

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


All Articles