Implementing simple business model in Haskell
data-modeling, haskell
Solution
Here's a naive approach:
data Station = Station Train [Train]
data Train = Train Station Station [Station]
You should never have to create an uninitialized object. For example, here's a couple sample values:
grandCentral = Station regional [national]
bestWestern = Station regional [national]
regional = Train grandCentral bestWestern []
national = Train grandCentral bestWestern []
However, there's a lot of drawbacks to this approach; observing the in-heap cycles is impossible from within the pure subset of Haskell, so updating or using these pieces of data is tricky. The usual workaround is to model your pointers explicitly.
type TrainMap = Map TrainId Train
type StationMap = Map StationId Station
type TrainId = Int -- use newtype for more compiler checks at
type StationId = Int -- the cost of more programmer annoyance
data Train = Train StationId StationId [StationId]
data Station = Station TrainId [TrainId]
Problem
Supose we have a very simple model: `Station` has at least one `Train` `Train` has at least two `Station`s The model has to allow to check what stations any given train visits and to check what trains visit a particular station. How to model it in Haskell? I am a Haskell newbie, so please correct me: once an object is created, you cannot modify it - you can only make a new object based on that one (~immutability). Am I right? If so, I'll have to create a lot of temporary variables with semi-initialized objects (during deserialization or even in unit tests). Basically what I need is an example of modeling domain classes in Haskell - after reading "Learn you a haskell.." I still have no idea how to use this language.