Defaults in datatype definitions

Johannes Waldmann joe@isun.informatik.uni-leipzig.de
Tue, 9 Jan 2001 09:46:31 +0100 (MET)


Below are some suggestions for extensions to Haskell records.

These are just naive ideas.
Of course the extensions should integrate nicely
w.r.t. the existing syntax, type system, and module system. 

Perhaps you can point me to opinions and research 
on what has already been done, or to why it should not, or can not.


1) I would like to write down default values for record components

    data Foo = Foo { x :: Bar; y :: Baz; x = some_expression }

We can do this for methods in type classes, so why not here.


2) With classes, we can do even more: in the default method,
we can access other methods.

This suggests that the above example should in fact read

    data Foo = Foo { x :: Bar; y :: Baz; x = \ self -> some_expression }

where `self' might occur in some_expression. that is, 
the default value of  `me.x ' gets computed by applying a function to  `me'.


3) I want to be able, in modules that use the type, 
to add more components (with defaults) to the type:

This would avoid lengthy recomputations (at the cost of additional space). 
Imagine the difference between

    data Tree a = Node { key :: a, children :: [ Tree a ] }
    size t = 1 + sum (map size (children t))

and

    data Tree a = Node { key :: a, children :: [ Tree a ]
			, size :: Integer
			, size = \ self -> 1 + sum (map size (children self)) }

when you have one large tree and frequently need sizes of subtrees.
(by the way, what type does `size' have now - 
do we write `Integer' or `Tree a -> Integer'?)

yes, I can do this manually, replacing `Node' by a smart constructor
that computes and stores the size. What I don't like about this
is that I have to know in advance (i. e. at the moment I define the type)
what functions I want to be "cached" this way. 
Imagine `size' as some more complicated function, 
only defined many modules later.

Of course I see that this would be difficult to implement
w.r.t. separate compilation. But I would be happy with a compiler
that ignores the "cache" specs during single-module compilations,
but honors them when doing a full rebuild of a set of modules.
I imagine that inter-module inlining behaves similar.

-- 
-- Johannes Waldmann ---- http://www.informatik.uni-leipzig.de/~joe/ --
-- joe@informatik.uni-leipzig.de -- phone/fax (+49) 341 9732 204/252 --