vector_point_add_scale.carbon 997 B

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