[Haskell-beginners] How to nest arbitrary things
martin
martin.drautzburg at web.de
Mon Dec 21 17:00:06 UTC 2015
Am 12/21/2015 um 03:21 PM schrieb Frerich Raabe:
> 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.
>
That's fine. I'm happy not to be able to pack a truck into another truck. Only problem is that I don't know how to write
an "unpack" function, which removes one level of nesting. I can only write unpackTruck, unpackParcel ...
I suppose the ability to write a generic unpack function implies that there can be a generic pack function and then I
could pack a truck into another truck.
More information about the Beginners
mailing list