lists.nbt 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. use core::scalar
  2. fn len<A>(xs: List<A>) -> Scalar
  3. fn head<A>(xs: List<A>) -> A
  4. fn tail<A>(xs: List<A>) -> List<A>
  5. fn cons<A>(x: A, xs: List<A>) -> List<A>
  6. fn is_empty<A>(xs: List<A>) -> Bool = len(xs) == 0
  7. # We definitely want to make the following functions generic, but this is not yet possible.
  8. fn generate(n: Scalar, f: Fn[() -> Scalar]) -> List<Scalar> =
  9. if n == 0
  10. then []
  11. else cons(f(), generate(n - 1, f))
  12. fn map(f: Fn[(Scalar) -> Scalar], xs: List<Scalar>) -> List<Scalar> =
  13. if len(xs) == 0
  14. then []
  15. else cons(f(head(xs)), map(f, tail(xs)))
  16. fn cons_end(xs: List<Scalar>, x: Scalar) -> List<Scalar> =
  17. if is_empty(xs)
  18. then [x]
  19. else cons(head(xs), cons_end(tail(xs), x))
  20. fn reverse(xs: List<Scalar>) -> List<Scalar> =
  21. if len(xs) == 0
  22. then []
  23. else cons_end(reverse(tail(xs)), head(xs))
  24. fn sequence(n: Scalar) -> List<Scalar> =
  25. if n == 1
  26. then [0]
  27. else cons_end(sequence(n - 1), n - 1)
  28. fn foldl(f: Fn[(Scalar, Scalar) -> Scalar], acc: Scalar, xs: List<Scalar>) -> Scalar =
  29. if len(xs) == 1
  30. then f(acc, head(xs))
  31. else foldl(f, f(acc, head(xs)), tail(xs))
  32. fn const_5() -> Scalar = 5
  33. fn inc(x: Scalar) -> Scalar = x + 1
  34. fn add(x: Scalar, y: Scalar) -> Scalar = x + y
  35. fn mul(x: Scalar, y: Scalar) -> Scalar = x * y