[Haskell-beginners] How to nest arbitrary things

Frerich Raabe raabe at froglogic.com
Mon Dec 21 14:21:11 UTC 2015


On 2015-12-21 10:40, martin wrote:
> I was trying to model things which can contain other things. This is easy as 
> long as containers and the contained items
> all can be described in the same fashion. However when I want to model - say 
> -
> 
> 	trucks
> 	containing boxes
> 		containing parcels
> 			containing cans
> 
> and trucks, boxes, parcels and cans are not of the same type, then this 
> nested thing will become a type in its own right
> and it will be of a different type than trucks containing cans (which are 
> not wrappen in parcels ...)
> 
> As long as I can squeeze trucks, boxes ... into one type, possibly by using 
> a "container_type" attribute, there is no
> problem. Is this the only way to do this? Is there an idiom?

In addition to what the others wrote (I'd personally probably start with the 
'data Truck a = Truck [a]' idea) you could also use the type system to 
express the possible *legal* ways to nest the load of a truck, e.g.:

   -- A Can can't contain anything
   data Can = Can

   -- A Parcel consists of zero or more cans
   data Parcel = Parcel [Can]

   -- A Box can be empty or contain a mixture of cans and parcels
   data BoxContent = BCCan Can | BCParcel Parcel
   data Box = Box [BoxContent]

   -- A Truck can be empty or contain a mixture of cans, parcels and boxes
   data TruckConent = TCCan Can | TCParcel Parcel | TCBox Box
   data Truck = Truck [TruckContent]

This might be too annoying to deal with though, i.e. the gain of type safety 
is not big enough to actually follow this path.

-- 
Frerich Raabe - raabe at froglogic.com
www.froglogic.com - Multi-Platform GUI Testing


More information about the Beginners mailing list