Python from Wise Guy's Viewpoint
Pascal Costanza
costanza at web.de
Sun Oct 26 16:37:58 EST 2003
Andreas Rossberg 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.
(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)))))
Session transcript:
? (let (x)
(declare (integer x))
(set-from-string x "4711")
(print x))
4711
? (let (x)
(declare (string x))
(set-from-string x "0815")
(print x))
"0815"
? (defmethod from-string-expansion ((to-type (eql 'symbol)) string)
`(intern ,string))
#<standard-method from-string-expansion ((eql symbol) t)>
? (let (x)
(declare (symbol x))
(set-from-string x "TEST")
(print x))
test
The macro delegates the decision which conversion function to use to the
generic function FROM-STRING-EXPANSION, but this is all executed at
compile time (as required for a compiled implementation of Common Lisp).
Pascal
P.S.: This is not ANSI Common Lisp, but uses a feature as defined in Guy
Steele's book "Common Lisp, The Language - 2nd Edition" (->
VARIABLE-INFORMATION). The code above works in Macintosh Common Lisp.
More information about the Python-list
mailing list