9e094e36792e0aaecca1ff9a71578e9d30acd809 872 B

123456789101112131415161718192021222324252627282930313233343536
  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: 25
  7. package ExplorerTest api;
  8. class List {
  9. choice Node {
  10. Nil,
  11. Cons(i32, Self*)
  12. }
  13. var node: Node;
  14. // Creates a list of `Cons(n, Cons(n - 1, ... Cons(1, Nil) ... ))`.
  15. fn Make(n: i32) -> Self {
  16. return {
  17. .node = if n == 0 then Node.Nil else Node.Cons(n, heap.New(Make(n - 1)))
  18. };
  19. }
  20. // Returns the sum of values in the list plus the value of `a`.
  21. fn Sum[self: Self](a: i32) -> i32 {
  22. match (self.node) {
  23. case Node.Nil => { return a; }
  24. case Node.Cons(b: i32, rest: Self*) => { return rest->Sum(a + b); }
  25. }
  26. }
  27. }
  28. fn Main() -> i32 {
  29. var l: List = List.Make(5);
  30. return l.Sum(10);
  31. }