[clean-list] instances of toString

Martin Wierich martinw@cs.kun.nl
Fri, 03 Nov 2000 16:08:36 +0100


Hi Eli,

eli+@gs211.sp.cs.cmu.edu wrote:
> module testcase2
..
> instance toString [Foobar]      // better yet, [a] | toString a
>   where toString lis = foldl (\s x -> s +++ " " +++ (toString x)) "" lis
..
> But this doesn't compile.  How can I fix it?
> Error [testcase2.icl,10,toString ([])]: toString ([]) multiply defined symbol
> Error [testcase2.icl,9,toString]: toString ([]) already defined
> 
> I can't actually find where StdEnv is defining toString on lists
> (except on [a] | toChar a), but it must be in there and colliding with
> me, because when I skip StdEnv and do my own toString class, it compiles:

Well, you _have_ found where the StdEnv defines toString on lists. The Clean
compiler requires that for every instance in one scope the "top-level" instance
type must be different. So you can't define e.g. one instance on lists of Foobar
and another instance on lists of something else. Both would have the same
top-level type "list".

> module testcase3
> // don't import StdEnv
> 
> class toString a :: !a -> {#Char}
> 
> :: Foobar = Foo | Bar
> instance toString Foobar
>   where toString Foo = "Foo"
>         toString Bar = "Bar"
> 
> instance toString [a]  | toString a
>   where toString [h:t] = toString h     // BOGUS, but you get the idea
> 
> Start = toString [Foo, Bar]
> 
> Ultimately, I want to write a generic toString [a] | toString a.  How
> can I get there from here?

Your definition above is already a generic toString [a] | toString a. It works
on every list whose elements can be stringified. You just should not import the
conflicting definition from the StdEnv (use the "from ... import ..." mechanism
instead). In Clean 2.0 the toString instance on lists will be removed from the
StdEnv!

> I'm also curious how exactly the
> overloading resolution works, since it's counterintuitive to me that
> testcase2 can't seem to instantiate toString for any sort of list.

In testcase2 you have specified that the list elements have to be Foobars. Your
definition in testcase3 is less restrictive.

cheers
  Martin Wierich
  University of Nijmegen