[Types-sig] polymorphic code (was: A challenge)

Greg Stein gstein@lyra.org
Tue, 21 Dec 1999 12:09:36 -0800 (PST)


On Mon, 20 Dec 1999, Martijn Faassen wrote:
>...
> Okay, but then I'll repeat the question I asked before:
> 
> class Foo:
>     def getIt(self)->String:
>         ...
> 
> class Bar:
>     def getIt(self)->String:
>         ...
> list = [Foo(), Bar()]
> 
> for el in list:
>     print el.doIt()
> 
> This wouldn't work, even though the interfaces are similar. This brings

I maintain that it will work :-)

[ assuming your doIt() is a typo, and you intended getIt() ]

>...
> * interfaces
> 
> Another way to do it is to use interfaces and say Foo and Bar both
> conform to some interface which supports doIt(). This was something we
> wouldn't discuss in this SIG, but can we in fact avoid it? 

We don't need any explicit interfaces to resolve the above code to
determine that it is type-safe. "el" has one of two types: Foo or Bar.
The (implicit) interface of each has a method named getIt that takes zero
parameters. In this case, the "print" statement can take any type, so we
don't even need to worry about the return types (even though they happen
to be the same).

Specifically: the type-checker does not have to unify the interface to
verify type-safety or type-checks, it merely needs to check that each
alternative for the type of "el" supports the required method and
signature.

Cheers,
-g

-- 
Greg Stein, http://www.lyra.org/