newLISP Fan Club

Forum => newLISP newS => Topic started by: cormullion on January 06, 2006, 06:26:03 AM

Title: Call stack overflow in apply
Post by: cormullion on January 06, 2006, 06:26:03 AM
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?
Title:
Post by: Lutz on January 06, 2006, 01:50:18 PM
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
Title:
Post by: Dmi on January 06, 2006, 03:32:17 PM
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?
Title:
Post by: Lutz on January 06, 2006, 05:02:51 PM
... 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
Title:
Post by: Dmi on January 06, 2006, 05:32:10 PM
Thanks!

I'm not really rely on this, but it's useful to know.
Title:
Post by: cormullion on January 07, 2006, 05:41:32 AM
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!