tuple_vector_add_scale.carbon 940 B

12345678910111213141516171819202122232425262728293031323334353637383940
  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. // NOAUTOUPDATE
  6. package ExplorerTest api;
  7. interface Vector {
  8. fn Add[self: Self](b: Self) -> Self;
  9. fn Scale[self: Self](v: i32) -> Self;
  10. }
  11. class Point {
  12. var x: i32;
  13. var y: i32;
  14. extend impl as Vector {
  15. fn Add[self: Point](b: Point) -> Point {
  16. return {.x = self.x + b.x, .y = self.y + b.y};
  17. }
  18. fn Scale[self: Point](v: i32) -> Point {
  19. return {.x = self.x * v, .y = self.y * v};
  20. }
  21. }
  22. }
  23. fn AddAndScaleGeneric[T:! Vector](t: (T, T), s: i32) -> T {
  24. var m: auto = t[0].Add;
  25. var n: auto = m(t[1]).Scale;
  26. return n(s);
  27. }
  28. fn Main() -> i32 {
  29. var a: Point = {.x = 1, .y = 1};
  30. var b: Point = {.x = 2, .y = 3};
  31. var p: Point = AddAndScaleGeneric((a, b), 5);
  32. return p.x - 15;
  33. }
  34. // CHECK:STDOUT: result: 0