Does implementing a procedure in a single pass mean non-recursive? Or does it mean that the procedure should never recur on the same information twice?
I ask this because I was under the impression that it was the first definition, but now I have stumbled across a homework problem that I can't figure out without using recursion but says "complete in a single pass".
A "single pass" means that each element in a collection of elements (be it: a list, an array, a set, a vector, a map, a tree, a graph, a string, etc.) is visited ("iterated over") once and only once - it doesn't matter if the procedure is recursive or iterative. For example, the following recursive procedure in Scheme adds all the elements in a list in a single pass:
(define (sum lst)
(if (null? lst)
0
(+ (car lst)
(sum (cdr lst)))))
The same procedure can be written in a tail recursive fashion - meaning: when the recursive call happens inside another procedure, is its final action; it may produce a return value which is then immediately returned by the calling procedure. Anyway, only a single pass is executed over the elements in the list:
(define (sum lst)
(let loop ((lst lst)
(acc 0))
(if (null? lst)
acc
(loop (cdr lst) (+ (car lst) acc)))))
Compare the above two examples with this code in Java: it's an iterative method, but once again a single pass is performed over the array:
int sum(int[] array) {
int acc = 0;
for (int x : array)
acc += x;
return acc;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With