mixed_arity.carbon 926 B

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