Right notation to recurse over a sequence or list

115 Views Asked by At

I have a function $f(x, a)$ which is invoked over all the elements of a sequence feeding the result to the next call, with $x$ being the next element in the list and $a$ the accumulated result. What is the correct (and popular) notation to write this properly?

Lets say $F(p, a)$ is the recursive function which takes the sequence, $p$, and runs $f(x, a)$ on each element of $p$.

I was thinking of defining it something like this:

$F(p, a) = \begin{cases} a & \text{if } p = \langle \rangle\\ f(F(\langle x_1, ..., x_{n-1} \rangle, a), x_n) & \text{if } p = \langle x_1, ..., x_n \rangle \end{cases} $

But for some reason it seems incorrect for the case when $p$ has just one element. Is there a better way to define it? Maybe some way of denoting the head and tail of the list?

1

There are 1 best solutions below

4
On BEST ANSWER

You have the concept of folding. Your definition seem to be right for me. It's the right fold. Note, that there is also left folding:

$$ F(p,a) = \begin{cases} a & ; p=[] \\ F([x_1,\ldots,x_{n-1}], f(x_n, a)) & ; p = [x_1, \ldots, x_n]; n \ge 1 \end{cases} $$

EDIT: You can also define it with the colon operator (which is the concatenation of an element to a list):

$$ F(p,a) = \begin{cases} a & ; p=[] \\ F(xs, f(x, a)) & ; p = x : xs \end{cases} $$

That's the way it is usually done in haskell...