generic_with_two_params.carbon 1.3 KB

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