parameterized.carbon 1009 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  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(Scalar:! Type) {
  11. fn Zero() -> Self;
  12. fn Add[me: Self](b: Self) -> Self;
  13. fn Scale[me: Self](v: Scalar) -> Self;
  14. }
  15. class Point {
  16. var x: i32;
  17. var y: i32;
  18. impl Point as Vector(i32) {
  19. fn Zero() -> Point {
  20. return {.x = 0, .y = 0};
  21. }
  22. fn Add[me: Point](b: Point) -> Point {
  23. return {.x = me.x + b.x, .y = me.y + b.y};
  24. }
  25. fn Scale[me: Point](v: i32) -> Point {
  26. return {.x = me.x * v, .y = me.y * v};
  27. }
  28. }
  29. }
  30. fn AddAndScaleGeneric[T:! Type, U:! Vector(T)](a: U, s: T) -> U {
  31. return a.Add(U.Zero()).Scale(s);
  32. }
  33. fn Main() -> i32 {
  34. var a: Point = {.x = 2, .y = 1};
  35. var p: Point = AddAndScaleGeneric(a, 5);
  36. return p.x - 10;
  37. }