[Haskell-beginners] How to nest arbitrary things

David McBride toad3k at gmail.com
Mon Dec 21 14:07:57 UTC 2015


Personally I'd try to use the type system, if possible.

data Box a = Box [a]
data Parcel a = Parcel [a]
data Can = Can


data Truck a = Truck {
  tname :: String,
  truckContents :: [a]
}

oneboxoftwocanstruck :: Truck (Box Can)
oneboxoftwocanstruck = Truck "Truck of Boxes of Cans" [Box [Can,Can]]

onecantruck :: Truck Can
onecantruck = Truck "Truck of Cans" [Can]

This gets some of the type safety without bogging you down too much.  You
can still end up with parcels with trucks in them, but it's not too bad.
At least cans are just cans, and functions can be written for trucks that
only work on trucks, for example.

On Mon, Dec 21, 2015 at 4:40 AM, martin <martin.drautzburg at web.de> wrote:

> Hello all,
>
> 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?
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20151221/35c6d307/attachment.html>


More information about the Beginners mailing list