[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [sc-users] recursion




Am 28.12.2019 um 22:14 schrieb jonahgrose@xxxxxxxxx:

 I thought it'd be simple to code some recursion into a function but I was mistaken? 


As you mentioned recursion, my previous implementation was an iterative one. There are cases where a recursive version is more "elegant" (e.g. factorial), but it can also be more opaque. Anyway you can see that here it's a bit slower also.


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

~collatz_R.(23)

-> [ 23, 70, 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1 ]


{ ~collatz.(14121913).postln }.bench

{ ~collatz_R.(14121913).postln }.bench


Regards

Daniel

-----------------------------
http://daniel-mayer.at
-----------------------------