tuple_vector_add_scale.carbon 936 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. //
  5. // AUTOUPDATE
  6. // CHECK:STDOUT: result: 0
  7. package ExplorerTest api;
  8. interface Vector {
  9. fn Add[self: Self](b: Self) -> Self;
  10. fn Scale[self: Self](v: i32) -> Self;
  11. }
  12. class Point {
  13. var x: i32;
  14. var y: i32;
  15. impl Point as Vector {
  16. fn Add[self: Point](b: Point) -> Point {
  17. return {.x = self.x + b.x, .y = self.y + b.y};
  18. }
  19. fn Scale[self: Point](v: i32) -> Point {
  20. return {.x = self.x * v, .y = self.y * v};
  21. }
  22. }
  23. }
  24. fn AddAndScaleGeneric[T:! Vector](t: (T, T), s: i32) -> T {
  25. var m: auto = t[0].Add;
  26. var n: auto = m(t[1]).Scale;
  27. return n(s);
  28. }
  29. fn Main() -> i32 {
  30. var a: Point = {.x = 1, .y = 1};
  31. var b: Point = {.x = 2, .y = 3};
  32. var p: Point = AddAndScaleGeneric((a, b), 5);
  33. return p.x - 15;
  34. }