# Re: [sc-users] recursion

```Just a small point of coding style.

On Sun, Dec 29, 2019 at 6:16 AM <daniel-mayer@xxxxxxxx> wrote:
> ((num == 1) or: { count >= limit }).if

If you look at other programming languages, constructions like
"if(condition) true-block false-block" (with numerous syntax
variations -- different ways of denoting the true and false branches)
are common.

So a new user might look at this and think, why does SC write it bass-ackwards?

Answer: You don't have to. SC supports the syntax `if((num == 1) or: {
count >= limit }) { true stuff... } { false stuff... }`.

Technically, `if` can be implemented as a method call, no different
from 1.0.rand -- so it's completely valid to write
`(condition-expression).if`. I used to do it this way, and there are
still instances of that in my older public code.

My personal opinion is that this is not ideally readable. (One
concrete reason is that the crucial keyword `if` ends up being buried
in the middle of a line.)

~collatz_R = { arg num, col, limit = 1000, count = 0;
if((num == 1) or: { count >= limit }) {
} {
~collatz_R.(
if(num.even) { num.div(2) } { num * 3 + 1 },
col,
limit,
count + 1
)
}
};

Oh, let's play with the code a bit. `col = col.add(num);` appears in
both branches -- it will be done in both the true or false cases --
so, move it outside the if. Then the "true" branch is empty, so,
invert the condition:

(
~collatz_R = { arg num, col, limit = 1000, count = 0;
if((num != 1) and: { count < limit }) {
// maybe a minor bug here:
// need to capture the recursion result
col = ~collatz_R.(
if(num.even) { num.div(2) } { num * 3 + 1 },
col,
limit,
count + 1
)
};
col
};
)

For fun/simplicity, you can drop the "count" argument as well by
having "limit" count down:

(
~collatz_R = { arg num, col, limit = 1000;
if((num != 1) and: { limit > 0 }) {
col = ~collatz_R.(
if(num.even) { num.div(2) } { num * 3 + 1 },
col,
limit - 1
)
};
col
};
)

hjh

_______________________________________________
sc-users mailing list

info (subscription, etc.): http://www.birmingham.ac.uk/facilities/ea-studios/research/supercollider/mailinglist.aspx
archive: https://listarc.bham.ac.uk/marchives/sc-users/
search: https://listarc.bham.ac.uk/lists/sc-users/search/

```