Search code examples
ats

How to write a loop over a given list in ATS?


Suppose I have a list xs. How do I write the following style of loop in ATS:

foreach x in xs do process(x)

Solution

  • You can use the old DIY-style (also: the classical ATS style), that is to say, using a tail-recursive function. Here's an example:

    extern
    fun
    process (x: int): void
    fun
    loop {n:int} (xs: list(int, n)): void =
      case+ xs of
      | list_nil () => ()
      | list_cons (x, xs1) => let
        val () = process (x)
      in
        loop (xs1)
      end
    // end of [loop]
    

    You can run the full code online

    I think that this approach is preferable if none of the combinators or template functions provided in the libraries such as ATSLIB is suitable for your case.