Page 1 of 1

Call stack overflow in apply

Posted: Fri Jan 06, 2006 2:26 pm
by 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:

Code: Select all

(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?

Posted: Fri Jan 06, 2006 9:50 pm
by Lutz
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:

Code: Select all

> (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

Posted: Fri Jan 06, 2006 11:32 pm
by Dmi
What really causes stack overflow with apply?

does it means that

Code: Select all

(apply op '(1 2 3 4 5) 2)
is really translated to

Code: Select all

(op (op (op (op 1 2) 3) 4) 5)
before processing?

Posted: Sat Jan 07, 2006 1:02 am
by Lutz
... 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

Posted: Sat Jan 07, 2006 1:32 am
by Dmi
Thanks!
I'm not really rely on this, but it's useful to know.

Posted: Sat Jan 07, 2006 1:41 pm
by cormullion
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!