Python from Wise Guy's Viewpoint
Andreas Rossberg
rossberg at ps.uni-sb.de
Tue Oct 28 08:37:34 EST 2003
Pascal Costanza wrote:
>
>> As an example of the kind of "overloading" (or type dispatch, if you
>> want)
>> you cannot express in dynamically typed lagnuages: in Haskell, you can
>> naturally define functions which are overloaded on their return type,
>> i.e.
>> you don't need any value at all at runtime to do the "dispatch". For
>> example, consider an overloaded function fromString, that produces
>> values of
>> potentially arbitrary types from strings.
>
> Wrong.
Not sure how the "wrong" relates to the quoted paragraph, but I guess
you mean my conjecture that you cannot dispatch on return types with
dynamic typing.
> (defmethod from-string-expansion (to-type string)
> (if (or (subtypep to-type 'sequence)
> (subtypep to-type 'character)
> (eq to-type t))
> `(coerce ,string ',to-type)
> `(coerce (read-from-string ,string) ',to-type)))
>
> (defmacro set-from-string (x string &environment env)
> (multiple-value-bind
> (bound localp declarations)
> (variable-information x env)
> (declare (ignore bound localp))
> (let ((type (or (cdr (assoc 'type declarations)) t)))
> `(setf ,x ,(from-string-expansion type string)))))
Interesting example, thanks for showing it. I'm not fluent enough in
Lisp to understand how this actually works but it does not seem to be
extensible in a compositional way (you have to insert all type cases by
hand). And does the resolution work transitively? I.e. if I write some
complex function f using fromString somewhere, performing arbitrary
calculations on its return value of type t, and returning something of a
type containing t, is all this code parametric in t such that I can call
f expecting arbitrary result types? All this would be automatic in Haskell.
Also note that your transcript shows that your approach indeed requires
*explicit* type annotations, while you would rarely need them when doing
the same thing in a language like Haskell.
Anyway, your code is complicated enough to make my point that the static
type system gives you similar expressiveness with less fuss.
- Andreas
--
Andreas Rossberg, rossberg at ps.uni-sb.de
"Computer games don't affect kids; I mean if Pac Man affected us
as kids, we would all be running around in darkened rooms, munching
magic pills, and listening to repetitive electronic music."
- Kristian Wilson, Nintendo Inc.
More information about the Python-list
mailing list