这是一个天真的方法:
data Station = Station Train [Train]
data Train = Train Station Station [Station]
您永远不必创建未初始化的对象。例如,这里有几个示例值:
grandCentral = Station regional [national]
bestWestern = Station regional [national]
regional = Train grandCentral bestWestern []
national = Train grandCentral bestWestern []
但是,这种方法有很多缺点。从 Haskell 的纯子集中观察堆内循环是不可能的,因此更新或使用这些数据很棘手。通常的解决方法是显式地为您的指针建模。
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]