This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Coordinate(x, y) { | |
shared Integer x; | |
shared Integer y; | |
shared actual String string => "Coordinate(``x``,``y``)"; | |
} | |
class Car(shared String name, position) { | |
shared variable Coordinate position; | |
shared void moveUp() => position = Coordinate(position.x, position.y + 1); | |
shared actual String string => "``name`` located at ``position``"; | |
} | |
void repeat(Integer times, Anything action()) { | |
for (i in 1..times) { | |
action(); | |
} | |
} | |
/** | |
this demo prints | |
car1 located at Coordinate(5,20) | |
car1 located at Coordinate(5,30) | |
car2 located at Coordinate(0,40) | |
car2 located at Coordinate(0,50) | |
**/ | |
void higherorder_demo() { | |
Car car1 = Car("car1",Coordinate(5,20)); | |
print(car1); | |
//now we can move our car 10 times up like this | |
for (i in 1..10) { | |
car1.moveUp(); | |
} | |
print(car1); | |
//or we just call the higher order function repeat | |
Car car2 = Car("car2",Coordinate(0,40)); | |
print(car2); | |
repeat(10, car2.moveUp); | |
print(car2); | |
} |
No comments:
Post a Comment