Re: tail call optimization



Bruno Haible wrote:
It's always a nice exercise to write such small functions yourself,
in a recursive way:

  (defun delete-nth-element (n l)
    (labels ((next (n l res)
		     (if (null l)
			 (reverse res)
			 (next (1- n) (cdr l)
			       (if (= n 0)
				   res
				   (cons (car l) res))))))
	(next (1- n) l '())))

A good compiler will flatten this into a loop.


Your notion of "good compiler" would not be useful in practice.
Namely, you are only thinking at the optimization quality of a
compiler, not at the debuggability of the resulting code.

If the compiler turns tail calls into recursion, some of the stack
frames are not present any more at runtime.  Which means, the
developer, when looking at the stack trace, doesn't have the complete
info.

Isn't that what traces are for (the complete info)? And stepping through the code (I'm not familiar with Lisp debugging yet, but I assume there is a stepping facility like in gdb for C) should also work just fine, since it's a loop after all.


[...]
The conclusion is: Code that assumes tail recursion elimination
makes it _impossible_ to _debug_ real big testcases.

Maybe.

Write it iteratively instead, and debuggability and testability are
reconciled.

The trouble is, not everything can nicely be written with loops. It might end up really awkward and you have to use trampolines and stuff, just like in Java or C.


--
No man is good enough to govern another man without that other's consent. -- Abraham Lincoln
.




Relevant Pages

  • Re: C03 abend when omitting CEE.SCEERUN from JCL
    ... The AMODE, RMODE, RENT, and RES information are link-edit information, not ... "compiler option" information. ... VS Cobol Program is actually OS/VS Cobol (amblist shows 5740CB103 as ... Do you mean VS COBOL II or OS/VS COBOL? ...
    (bit.listserv.ibm-main)
  • Re: Where are the Opteron F vs. Woodcrest reviews?
    ... (same typedef assumed) ... return res; ... sll %o1,7,%o5 ... Note that I'm not claiming that Sun's compiler is ...
    (comp.arch)
  • Re: void function returning value?
    ... > return res; ... >which is the following line within the 'Veld' class: ... >forward declaration of the friend function was done as follows: ... >Why is the compiler talking about a 'void' function? ...
    (comp.lang.cpp)
  • Re: passing a struct with an array by reference
    ... As res is of type MatlabWrap.micDataReturn which is decalred as struct, it means that res is ValueType. ... Value types gets allocated on stack, and because of that they have to be initialized befor they are first used, because the compiler doesn't make any assumptions about the res initial value. ... Because your method takes a ref parameter, then the compiler expects that this value is already initialized by you, and because it isn't, then it generate that error message. ...
    (microsoft.public.dotnet.languages.csharp)