I have this code:
def input1 = ['a','b','e','r','t']
input2 = ['v','n','m','y']
ans = []
def common(def element,def i) {
if (element == input2[i]) {
ans << element
return
} else {
common(element,++i)
}
}
for (i=0;i<input1.size();i++) {
common(input1[i],0)
}
which is generating Stack Overflow error. Why is this happening?
Edit:
I’m trying to create my own way of finding common element between two lists.
You never check if
iis greater than the length ofinput2, and in Groovy, getting beyond the length of aListreturnsnullSo on the first element, it will keep looping round
for ever-increasing values of
i, calling thecommonfunction every time, as it never matchesaGuessing at what you are trying to do, this can all be re-written as:
But it’s hard to be sure what you want, and you dont explicitly say.
Edit
One method of deep recursion that avoids Stack Overflows is to use Groovy’s trampoline method.
But I’d still use
intersectin this case, the above is just to show one of Groovy’s ways you can avoid too-deep recursion…