Haskell Record Field Dependency

data MyRecord = MyRecord {
  numberOfSides :: Int,
  shape :: Shape
}

Shapecan be a triangle, quadrilateral, etc. depending on numberOfSides.

My question is: these two fields are connected. Is there a “trigger” mechanism for updating another when updating one field? and if two fields are in conflict, report a type error?

Another related scenario:

data MyRecord = MyRecord {
  players      :: [Player],
  numOfPlayers :: Int
}

I want to somehow automatically calculate numberOfPlayersbased on size players.

PS: Is this related to GADT and dependent types ?

+4
source share
2 answers

Haskell, OO, . , , , , "", Haskell. , DRY ( , OO), , - , .

-- deriving (...) clauses and other boilerplate omitted for brevity

data Shape = Triangle | Quad | Pentagon | Other

data MyRecord = MyRecord Int

numSides :: Shape -> Int
numSides Triangle = 3
numSides Quad = 4
numSides Pentagon = 5
numSides Other = 0

shape :: Int -> Shape
shape 3 = Triangle
shape 4 = Quad
shape 5 = Pentagon
shape _ = Other

makeMyRecord :: Shape -> MyRecord
makeMyRecord = MyRecord . numSides

numberOfSides :: MyRecord -> Int
numberOfSides (MyRecord x) = x

shapeOf :: MyRecord -> Shape
shapeOf = shape . numberOfSides

Shape Enum Bounded, . Shape numSides Enum. MyRecord Int, , makeMyRecord', . , DRY, , "" .

+2

: . "" ? , ?

PS: - GADT ?

, GADT. Haskell, , numTypes :: Int -> Shape.

+1

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


All Articles