[Haskell-beginners] Can fields in a record be optional?

Yitzchak Gale gale at sefer.org
Mon Jul 18 08:57:34 CEST 2011


Roger L. Costello wrote:
>> data Contract =
>>   Contract {
>>              currency  :: Currency
>>            , payments  :: Double
>>            , contracts :: [Contract]
>>            }
>>  deriving (Show)

David Virebayre wrote:
> I'm not sure I would model your datatype this way, I don't like the
> idea to put unnecessary undefined values in the case of subcontracts.
>
> data Contract = Contract  { currency :: Currency, payments :: Double }
>              | SubContract { contracts :: [Contract] }

I think Roger's original design is just fine.

There is nothing "undefined" about the empty list. Roger is
saying that every contract has a list of subcontracts. Lists can
be empty, and that is legitimate.

In effect, Roger has defined his collection of contracts to be
a rose tree, and this is the classic way to do that in Haskell.
Another option would be to be more explicit about that and
use Data.Tree from the containers[1] package, which is
included in the Haskell Platform.

Tree algorithms are often quite elegant.
We haven't seen the rest of Roger's program, but I'll
bet it looks really nice with his original definition.

Regards,
Yitz



More information about the Beginners mailing list