range.carbon 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. // TODO: This library is not part of the design. Either write a matching
  5. // proposal or remove this.
  6. package Core library "range";
  7. import library "prelude/destroy";
  8. import library "prelude/iterate";
  9. import library "prelude/operators/arithmetic";
  10. import library "prelude/operators/as";
  11. import library "prelude/operators/comparison";
  12. import library "prelude/types/int";
  13. import library "prelude/types/int_literal";
  14. import library "prelude/types/optional";
  15. class IntRange(N:! IntLiteral()) {
  16. fn Make(start: Int(N), end: Int(N)) -> Self {
  17. return {.start = start, .end = end};
  18. }
  19. impl as Iterate where .CursorType = Int(N) and .ElementType = Int(N) {
  20. fn NewCursor[self: Self]() -> Int(N) { return self.start; }
  21. fn Next[self: Self](cursor: Int(N)*) -> Optional(Int(N)) {
  22. var value: Int(N) = *cursor;
  23. if (value < self.end) {
  24. ++*cursor;
  25. return Optional(Int(N)).Some(value);
  26. } else {
  27. return Optional(Int(N)).None();
  28. }
  29. }
  30. }
  31. private var start: Int(N);
  32. private var end: Int(N);
  33. }
  34. fn Range(end: i32) -> IntRange(32) {
  35. return IntRange(32).Make(0, end);
  36. }
  37. fn InclusiveRange(start: i32, end: i32) -> IntRange(32) {
  38. return IntRange(32).Make(start, end + 1);
  39. }