mixed_arity.carbon 875 B

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