Contributed by Mark Miller
Original E Version by Chris Rathman
#!/usr/bin/env e
#!/usr/bin/env rune
def makeRectangle(var x, var y, var width, var height) :any {
def rectangle {
# accessors for x & y coordinates
to getX() :any { return x }
to getY() :any { return y }
to setX(newx) :void { x := newx }
to setY(newy) :void { y := newy }
# move the x & y coordinates
to moveTo(newx, newy) :void {
rectangle.setX(newx)
rectangle.setY(newy)
}
to rMoveTo(deltax, deltay) :void {
rectangle.moveTo(rectangle.getX() + deltax,
rectangle.getY() + deltay)
}
# accessors for width & height
to getWidth() :any { return width }
to getHeight() :any { return height }
to setWidth(newwidth) :void { width := newwidth }
to setHeight(newheight) :void { height := newheight }
# draw the rectangle
to draw() :void {
print(`Drawing a Rectangle at:($x,$y)`)
println(`, width $width, height $height`)
}
}
return rectangle
}
def makeCircle(var x, var y, var radius) :any {
def circle {
# accessors for x & y coordinates
to getX() :any { return x }
to getY() :any { return y }
to setX(newx) :void { x := newx }
to setY(newy) :void { y := newy }
# move the x & y coordinates
to moveTo(newx, newy) :void {
circle.setX(newx)
circle.setY(newy)
}
to rMoveTo(deltax, deltay) :void {
circle.moveTo(circle.getX() + deltax,
circle.getY() + deltay)
}
# accessors for the radius
to getRadius() :any { return radius }
to setRadius(newradius) :void { radius := newradius }
# draw the circle
to draw() :void {
println(`Drawing a Circle at:($x,$y), radius $radius`)
}
}
return circle
}
def polymorph() :void {
# create some shape instances
def scribble := [makeRectangle(10, 20, 5, 6), makeCircle(15, 25, 8)]
# iterate through the list and handle shapes polymorphically
for ashape in scribble {
ashape.draw()
ashape.rMoveTo(100, 100)
ashape.draw()
}
# call a rectangle specific function
def rect := makeRectangle(0, 0, 15, 15)
rect.setWidth(30)
rect.draw()
}
polymorph()
|
Drawing a Rectangle at:(10,20), width 5, height 6 Drawing a Rectangle at:(110,120), width 5, height 6 Drawing a Circle at:(15,25), radius 8 Drawing a Circle at:(115,125), radius 8 Drawing a Rectangle at:(0,0), width 30, height 15 |