Call stack overflow in apply

Started by cormullion, January 06, 2006, 06:26:03 AM

Previous topic - Next topic

cormullion

I'm trying to learn 'apply' with the third argument, and I think I'm doing something wrong, because I get call stack overflows:


(define (longer s1 s2)
(if (>= (length s1) (length s2))
s1
s2))
(apply longer (parse (read-file "a-text-file.txt") { |n} 0) 2)


-> call stack overflow : length <132EC>



even with small files of a thousand words or so.



Is this not a good use of 'apply'? Where is it stacking up?

Lutz

#1
yes, 'apply' has a stack limit, you could change that when starting up newlisp using the -s commandline option, but I believe for what you are trying to do, you don't need it.



If you are looking for the longest string in your parsed text you could just sort it by length this way:



> (set 'txt "this is an example for corumullion")
"this is an example for corumullion"

> (first (sort (parse txt { |n} 2) (fn (x y) (> (length x) (length y)))))
"corumullion"
>


when sorting, you can tell 'sort' what function to use when sorting. In this case:

(fn (x y) (> (length x) (length y))



This is a typical LISP thing: passing a function as a parameter to another function.



Lutz

Dmi

#2
What really causes stack overflow with apply?



does it means that
(apply op '(1 2 3 4 5) 2)
is really translated to
(op (op (op (op 1 2) 3) 4) 5)
before processing?
WBR, Dmi

Lutz

#3
... in effect yes, but the implementation is iterative and leaves the possibility to free stack space on the go. With a little bit more work 'apply'-reduce can be made independent of stack size; it is on my todo list, but I have not done anything because the only ones using it seemed to be Eddier, myself and few others and our problems didn't require as much stack space.



Lutz

Dmi

#4
Thanks!

I'm not really rely on this, but it's useful to know.
WBR, Dmi

cormullion

#5
Thanks. I was actually trying to learn how to use apply-reduce, rather than trying to find the longest word (which as you say is easier another way), and this was as example that sprang to mind.



I suppose I was thinking of a kind of analogue to Ruby's inject method, which does something similar. Although, I think that apply-reduce isn't really doing what it appears to be doing - as a user I think it's traversing a list and remembering a value, but it's probably not doing that at all ... :-)



I'll probably play safe and think of dolist rather than apply-reduce at the moment!