Reputation:
Suppose I have a list xs. How do I write the following style of loop in ATS:
foreach x in xs do process(x)
Upvotes: 3
Views: 159
Reputation: 935
This is a POOR solution one needs to avoid!
A beginner of functional programming often does list traversal using the list_get_at
function (which overloads the symbol []
). For instance, it is fairly common to see code that does more or less what the following line does:
(length(xs)).foreach()(lam i => process(xs[i])) // O(n^2)-time
This is EXTREMELY inefficient. Calling list_get_at
inside a loop is almost always a bad idea!
Upvotes: 0
Reputation: 935
A combinator-based solution (for a list0
-value):
(xs).foreach()(lam x => process(x))
In ATS, foreach
is overloaded with many functions that do some form of sequence traversal.
There is also iforeach
if the position of each element is needed:
(xs).iforeach()(lam (i, x) => process(i, x))
Upvotes: 0
Reputation: 1101
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.
Upvotes: 1