space_collisions.sf 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #!/usr/bin/ruby
  2. #
  3. ## Translation of: https://en.wikipedia.org/wiki/Multiple_dispatch#Perl_6
  4. #
  5. class StellarObject(Number mass) {
  6. method <=>(StellarObject arg) {
  7. self.mass <=> arg.mass;
  8. }
  9. method >(StellarObject arg) {
  10. self.mass > arg.mass
  11. }
  12. method <(StellarObject arg) {
  13. self.mass < arg.mass
  14. }
  15. }
  16. class Asteroid < StellarObject {
  17. has name = 'an asteroid'
  18. }
  19. class Spaceship(name='some unnamed spaceship') < StellarObject {
  20. }
  21. var destroyed = < obliterated destroyed mangled >;
  22. var damaged = ['damaged', 'collided with', 'was damaged by'];
  23. func collide(Asteroid a, Asteroid b) {
  24. say "two asteroids collided and combined into one larger asteroid of mass #{ a.mass + b.mass }";
  25. }
  26. func collide(a, b) {
  27. if (a > b) {
  28. collide(b, a)
  29. }
  30. elsif (a < b) {
  31. say "#{a.name} was #{destroyed.pick} by #{b.name}";
  32. }
  33. else {
  34. if (a.kind_of(Spaceship) && b.kind_of(Spaceship) && (a.mass == b.mass)) {
  35. var (n1, n2) = [a.name, b.name].shuffle...;
  36. say "#{n1} collided with #{n2}, and both ships were #{[destroyed.pick, 'left damaged'].pick}";
  37. }
  38. else {
  39. var (n1, n2) = [a.name, b.name].shuffle...;
  40. say "#{n1} #{damaged.pick} #{n2}";
  41. }
  42. }
  43. }
  44. var Enterprise = Spaceship(mass: 1, name: 'The Enterprise');
  45. collide(Asteroid(mass: 1), Enterprise);
  46. collide(Enterprise, Spaceship(mass: .1));
  47. collide(Enterprise, Asteroid(mass: 1));
  48. collide(Enterprise, Spaceship(mass: 1));
  49. collide(Asteroid(mass: 10), Asteroid(mass: 5));