Musing - Algebraic types? (was Tuples...)
Greg Ewing
greg at cosc.canterbury.ac.nz
Wed Apr 12 22:56:48 EDT 2000
The recent discussion about lists vs. tuples got me
thinking about algebraic types. It was mentioned that
an alternative to tuples was to define a class with
an appropriate __init__ method. This is true, but it
can get tedious writing __init__ methods that do
nothing but stuff their arguments into instance
variable.
So I was thinking about a shorthand syntax for
defining such classes, based on the way that algebraic
types are defined in Haskell-like languages. Maybe
something like
class Statement(ParseNode) = (
IfStatement(expr, then_stmts, else_stmts),
WhileStatement(expr, body),
ForStatement(var, expr, body)
)
which would be equivalent to writing
class Statement(ParseNode):
pass
class IfStatement(Statement):
def __init__(self, expr, then_stmts, else_stmts):
self.expr = expr
self.then_stmts = then_stmts
self.else_stmts = else_stmts
etc. etc.
Then, of course, we're going to want to be able to
unpack these:
IfStatement(b, t, e) = my_if_statement
would be equivalent to
b = my_if_statement.expr
t = my_if_statement.then_stmts
e = my_if_statement.else_stmts
and to be really useful we want some sort of case-statement
with unpacking:
switch my_statement:
case IfStatement(b, t, e):
...
case WhileStatement(b, s):
...
case ForStatement(v, e, s):
...
(expansion left as an exercise for the reader - this post
is long enough already!)
What think ye all?
--
Greg Ewing, Computer Science Dept,
+--------------------------------------+
University of Canterbury, | A citizen of NewZealandCorp, a |
Christchurch, New Zealand | wholly-owned subsidiary of USA Inc. |
greg at cosc.canterbury.ac.nz +--------------------------------------+
More information about the Python-list
mailing list