generic_with_two_params.carbon 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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 Point1 {
  13. var x: i32;
  14. var y: i32;
  15. impl Point1 as Vector {
  16. fn Add[self: Point1](b: Point1) -> Point1 {
  17. return {.x = self.x + b.x, .y = self.y + b.y};
  18. }
  19. fn Scale[self: Point1](v: i32) -> Point1 {
  20. return {.x = self.x * v, .y = self.y * v};
  21. }
  22. }
  23. }
  24. class Point2 {
  25. var x: i32;
  26. var y: i32;
  27. impl Point2 as Vector {
  28. fn Add[self: Point2](b: Point2) -> Point2 {
  29. return {.x = self.x + b.x + 1, .y = self.y + b.y + 1};
  30. }
  31. fn Scale[self: Point2](v: i32) -> Point2 {
  32. return {.x = self.x * v * 2, .y = self.y * v * 2};
  33. }
  34. }
  35. }
  36. fn ScaleGeneric[U:! Vector](c: U, s: i32) -> U {
  37. return c.Scale(s);
  38. }
  39. fn AddAndScaleGeneric[T:! Vector, V:! Vector](a: T, b: V, s: i32) -> (T, V) {
  40. return (ScaleGeneric(a.Add(a), s),
  41. ScaleGeneric(b.Add(b), s));
  42. }
  43. fn Main() -> i32 {
  44. var a: Point1 = {.x = 1, .y = 1};
  45. var b: Point2 = {.x = 2, .y = 3};
  46. var (p: Point1, q: Point2) = AddAndScaleGeneric(a, b, 5);
  47. return q.x - p.x - 40;
  48. }