<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://blogs.msdn.com/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>Fabulous Adventures In Coding : JScript</title><link>http://blogs.msdn.com/ericlippert/archive/tags/JScript/default.aspx</link><description>Tags: JScript</description><dc:language>en-US</dc:language><generator>CommunityServer 2.1 SP1 (Build: 61025.2)</generator><item><title>Why Doesn't C# Implement "Top Level" Methods?</title><link>http://blogs.msdn.com/ericlippert/archive/2009/06/22/why-doesn-t-c-implement-top-level-methods.aspx</link><pubDate>Mon, 22 Jun 2009 18:39:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9797817</guid><dc:creator>Eric Lippert</dc:creator><slash:comments>58</slash:comments><comments>http://blogs.msdn.com/ericlippert/comments/9797817.aspx</comments><wfw:commentRss>http://blogs.msdn.com/ericlippert/commentrss.aspx?PostID=9797817</wfw:commentRss><description>&lt;DIV class=mine&gt;
&lt;P&gt;C# requires that every method be in some class, even if it is a static method in a static class in the global namespace. Other languages allow "top level" functions. A&lt;A class="" href="http://stackoverflow.com/questions/1024171/why-c-is-not-allowing-non-member-functions-like-c/1027853#1027853" mce_href="http://stackoverflow.com/questions/1024171/why-c-is-not-allowing-non-member-functions-like-c/1027853#1027853"&gt; recent stackoverflow post asks why that is.&lt;/A&gt;&lt;/P&gt;
&lt;P&gt;I am asked "why doesn't C# implement feature X?" all the time. The answer is always the same: because no one ever designed, specified, implemented, tested, documented and shipped that feature. All six of those things are necessary to make a feature happen. All of them cost huge amounts of time, effort and money. Features are not cheap, and we try very hard to make sure that we are only shipping those features which give the best possible benefits to our users given our constrained time, effort and money budgets.&lt;/P&gt;
&lt;P&gt;I understand that such a general answer probably does not address the specific question. &lt;/P&gt;
&lt;P&gt;In this particular case, the clear user benefit was in the past not large enough to justify the complications to the language which would ensue. By restricting how different language entities nest inside each other we (1) restrict legal programs to be in a common, easily understood style, and (2) make it possible to define "identifier lookup" rules which are comprehensible, specifiable, implementable, testable and documentable. &lt;/P&gt;
&lt;P&gt;By restricting method bodies to always be inside a struct or class, we make it easier to reason about the meaning of an unqualified identifier used in an invocation context; such a thing is always an invocable member of the current type (or a base type).&amp;nbsp;&lt;/P&gt;
&lt;P&gt;Now, JScript.NET has this feature. (And in fact, JScript.NET goes even further; you can have program statements "at the top level" too.) A reasonable question is "why is this feature good for JScript but bad for C#?"&lt;/P&gt;
&lt;P&gt;First off, I reject the premise that the feature is "bad" for C#. The feature might well be good for C#, just not &lt;EM&gt;good enough&lt;/EM&gt; compared to its costs (and to the &lt;EM&gt;opportunity cost&lt;/EM&gt; of doing that feature &lt;EM&gt;instead of a more valuable feature&lt;/EM&gt;.) The feature might become good enough for C# if its costs are lowered, or if the compelling benefit to customers becomes higher.&lt;/P&gt;
&lt;P&gt;Second, the question assumes that the feature is good for JScript.NET. Why is it good for JScript.NET?&lt;/P&gt;
&lt;P&gt;It's good for JScript.NET because JScript.NET was designed to be a "scripty" language as well as a "large-scale development" language. "JScript classic"'s original design as a scripting language requires that "a one-line program actually be one line". If your intention is to make a language that allows for rapid development of short, simple scripts by novice developers then you want to minimize the amount of "ritual incantations" that must happen in every program. In JScript you do not want to have to start with a bunch of using clauses and define a class and then put stuff in the class and have a Main routine and blah blah blah, all this ritual just to get Hello World running.&lt;/P&gt;
&lt;P&gt;C# was designed to be a large-scale application development language geared towards pro devs from day one; it was never intended to be a scripting language. It's design therefore encourages enforcing the &lt;EM&gt;immediate&lt;/EM&gt; organization of even small chunks of code into &lt;EM&gt;components&lt;/EM&gt;. &lt;STRONG&gt;C# is a component-oriented language.&lt;/STRONG&gt; We therefore want to encourage programming in a component-based style and discourage features that work against that style.&lt;/P&gt;
&lt;P&gt;This is changing. "REPL" languages like F#, long popular in academia, are increasing in popularity in industry. There's a renewed interest in "scripty" application programmability via tools like Visual Studio Tools for Applications. These forces cause us to re-evaluate whether "a one line program is one line" is a sensible goal for hypothetical future versions of C#. Hitherto it has been an explicit non-goal of the language design.&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;(As always, whenever I discuss the hypothetical "next version of C#", keep in mind that we have not announced any next version, that it might never happen, and that it is utterly premature to think about feature sets or schedules. All speculation about future versions of unannounced products should be taken as "for entertainment purposes only" musings, not as promises about future offerings.)&lt;/STRONG&gt;&lt;/P&gt;
&lt;P&gt;We are therefore &lt;EM&gt;considering&lt;/EM&gt; adding this feature to a hypothetical future version of C#, in order to better support "scripty" scenarios and REPL evaluation. When the existence of powerful new tools is predicated upon the existence of language features, that is points towards getting the language features done.&lt;/P&gt;
&lt;P&gt;UPDATE: &lt;A class="" href="http://blogs.msdn.com/ericlippert/archive/2009/06/24/it-already-is-a-scripting-language.aspx" mce_href="http://blogs.msdn.com/ericlippert/archive/2009/06/24/it-already-is-a-scripting-language.aspx"&gt;More thoughts on considerations motivating this potential change here&lt;/A&gt;.&lt;/P&gt;&lt;/DIV&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9797817" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/ericlippert/archive/tags/JScript+.NET/default.aspx">JScript .NET</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/JScript/default.aspx">JScript</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Scripting/default.aspx">Scripting</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Static+Methods/default.aspx">Static Methods</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Language+Design/default.aspx">Language Design</category></item><item><title>Using undefined variables in JScript</title><link>http://blogs.msdn.com/ericlippert/archive/2006/05/04/590030.aspx</link><pubDate>Thu, 04 May 2006 19:28:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:590030</guid><dc:creator>Eric Lippert</dc:creator><slash:comments>5</slash:comments><comments>http://blogs.msdn.com/ericlippert/comments/590030.aspx</comments><wfw:commentRss>http://blogs.msdn.com/ericlippert/commentrss.aspx?PostID=590030</wfw:commentRss><description>&lt;DIV class=mine&gt;
&lt;P&gt;I got a question the other day pointing out that in JScript, it is legal to assign a value to an undeclared variable, and the variable kind of gets implicitly declared for you, but it is not legal to read the value of an undeclared variable. The writer wanted to know if &lt;SPAN class=code&gt;y = 1;&lt;/SPAN&gt; for some undeclared variable has exactly the same semantics as &lt;SPAN class=code&gt;var y = 1;&lt;/SPAN&gt;.&lt;/P&gt;
&lt;P&gt;Close, but not quite. Assigning to an undefined variable is &lt;I&gt;not&lt;/I&gt; equivalent to replacing the assignment with a declaration because &lt;I&gt;that might declare a local variable bound to a particular activation&lt;/I&gt;. Using a variable without declaring it in Jscript produces a new &lt;I&gt;global&lt;/I&gt; variable, not a new &lt;I&gt;local&lt;/I&gt; variable. You can clearly see that they are not equivalent because these two programs do different things:&lt;/P&gt;&lt;SPAN class=code&gt;
&lt;P&gt;function foo() {y = 1; }&lt;BR&gt;foo();&lt;BR&gt;print(y); // 1&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;function foo() {var y = 1; }&lt;BR&gt;foo();&lt;BR&gt;print(y); // error, y undefined&lt;BR&gt;&lt;/P&gt;&lt;/SPAN&gt;
&lt;P&gt;These behaviours of the Jscript engine are conformant to the ECMAScript specification, Revision 3, Section 8.7.&lt;/P&gt;
&lt;P&gt;In VBScript, on the other hand, using an undefined variable does produce a new local variable, whether you're reading or writing.&lt;/P&gt;
&lt;P&gt;The writer then went on to ask "how can I &lt;I&gt;prevent&lt;/I&gt; JScript from creating a new variable in this case? I want this to be an error." &lt;/P&gt;
&lt;P&gt;To explain, we should take a look at what exactly happens when we see &lt;SPAN class=code&gt;y = 1;&lt;/SPAN&gt; so that we can determine that we need to create a new variable. To do the assignment successfully, three things must happen: we must determine an address for &lt;SPAN class=code&gt;y&lt;/SPAN&gt;, we must determine the value, and we must store the value in that address. The way those things happen goes like this:&lt;/P&gt;
&lt;UL&gt;
&lt;LI&gt;First we search the scope chain – &lt;SPAN class=code&gt;with&lt;/SPAN&gt; blocks, the activation frame, the globals – for any object that has a property &lt;SPAN class=code&gt;y&lt;/SPAN&gt;. We do not find one. 
&lt;LI&gt;Next we search all the global host objects asking them if they have a property &lt;SPAN class=code&gt;y&lt;/SPAN&gt;. We do not find one. 
&lt;LI&gt;Therefore we create a special "fake" address and put it on the script stack. This completes the first part of the binding. 
&lt;LI&gt;Determining the value is trivial in this case. 
&lt;LI&gt;When we do the store we detect that there's a fake address on the stack, allocate a new global variable in the script engine's global name table, and replace the fake address with this new real address. 
&lt;LI&gt;Finally, we invoke the property put logic in the global name table to store the value to the correct address.&lt;/LI&gt;&lt;/UL&gt;
&lt;P&gt;Notice that the only question we ask the host is "do you have this property?", and if the host says no, we create a variable. Therefore, if you want this to be an error, you have to write a script host that lies to the script engine. If you always say "yes, I have that property" even when you don't, then you can raise an exception when the store logic attempts to do the store. However, I've never heard of anyone trying that. There might be other negative consequences to consistently lying to the script engine about whether you have a property or not. You'll have to try it and see.&lt;/P&gt;
&lt;P&gt;As an aside, you might be wondering why we go to the trouble of creating a fake address during the address lookup that gets turned into a real address during the store. Why not just create the real address in the first place? &lt;/P&gt;
&lt;P&gt;Ponder that for a moment. Under what circumstances would we not want to create a real global variable until after the right hand side of the assignment was evaluated? &lt;/P&gt;
&lt;P&gt;Well, you would not expect this program to produce a new global variable: &lt;/P&gt;&lt;SPAN class=code&gt;
&lt;P&gt;function foo() { try { y = eval("throw 1;"); } catch(e) { } }&lt;BR&gt;foo();&lt;BR&gt;print(y); // should be undefined!&lt;BR&gt;&lt;/P&gt;&lt;/SPAN&gt;
&lt;P&gt;The global variable creation must happen at the moment of &lt;I&gt;actual assignment&lt;/I&gt;, not at the moment when the address is determined, because determining the value might prevent the store from ever happening. &lt;/P&gt;&lt;/DIV&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=590030" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/ericlippert/archive/tags/JScript/default.aspx">JScript</category></item><item><title>Checking For Script Syntax Errors, This Time With Code</title><link>http://blogs.msdn.com/ericlippert/archive/2005/10/12/480154.aspx</link><pubDate>Wed, 12 Oct 2005 19:37:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:480154</guid><dc:creator>Eric Lippert</dc:creator><slash:comments>9</slash:comments><comments>http://blogs.msdn.com/ericlippert/comments/480154.aspx</comments><wfw:commentRss>http://blogs.msdn.com/ericlippert/commentrss.aspx?PostID=480154</wfw:commentRss><description>&lt;FONT face="lucida sans unicode" color=purple size=2&gt;
&lt;P&gt;A number of people asked me to clarify yesterday's entry.&amp;nbsp;Rather than try to talk you through it, I think the code is straightforward enough to speak for itself.&amp;nbsp;Here's a little skeleton that I just whipped up.&lt;/P&gt;&lt;/FONT&gt;&lt;FONT face="lucida console" color=navy size=2&gt;
&lt;P&gt;#include &amp;lt;stdio.h&amp;gt;&lt;BR&gt;#include &amp;lt;activscp.h&amp;gt;&lt;BR&gt;#include &amp;lt;new&amp;gt;&lt;/P&gt;
&lt;P&gt;const GUID CLSID_VBScript = {0xb54f3741, 0x5b07, 0x11cf, {0xa4, 0xb0, 0x00, 0xaa, 0x00, 0x4a, 0x55, 0xe8}};&lt;BR&gt;const GUID CLSID_JScript&amp;nbsp; = {0xf414c260, 0x6ac0, 0x11cf, {0xb6, 0xd1, 0x00, 0xaa, 0x00, 0xbb, 0xbb, 0x58}};&lt;/P&gt;
&lt;P&gt;class MySite : public IActiveScriptSite {&lt;BR&gt;private:&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&amp;nbsp;ULONG m_cref;&lt;BR&gt;&amp;nbsp; virtual ~MySite() {}&lt;/P&gt;
&lt;P&gt;public:&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&amp;nbsp;MySite() {&lt;BR&gt;&amp;nbsp;&amp;nbsp; &amp;nbsp;this-&amp;gt;m_cref = 1;&lt;BR&gt;&amp;nbsp;&amp;nbsp;}&lt;/P&gt;
&lt;P&gt;&amp;nbsp; STDMETHOD_(ULONG, AddRef)() {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return ++this-&amp;gt;m_cref;&lt;BR&gt;&amp;nbsp;&amp;nbsp;}&lt;/P&gt;
&lt;P&gt;&amp;nbsp; STDMETHOD_(ULONG,Release)() {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; --this-&amp;gt;m_cref;&lt;BR&gt;&amp;nbsp; &amp;nbsp;&amp;nbsp;if (this-&amp;gt;m_cref == 0) {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;delete this;&lt;BR&gt;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;return 0;&lt;BR&gt;&amp;nbsp; &amp;nbsp;&amp;nbsp;}&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return this-&amp;gt;m_cref;&lt;BR&gt;&amp;nbsp;&amp;nbsp;}&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&amp;nbsp;STDMETHOD(QueryInterface)(REFIID iid, void ** ppv) {&lt;BR&gt;&amp;nbsp;&amp;nbsp; &amp;nbsp;if (ppv == NULL)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;return E_POINTER;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (IsEqualIID(iid, IID_IUnknown))&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;*ppv = (IUnknown*)this;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; else if (IsEqualIID(iid, IID_IActiveScriptSite))&lt;BR&gt;&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp;*ppv = (IActiveScriptSite*)this;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; else {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;*ppv = NULL;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;return E_NOINTERFACE;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; this-&amp;gt;AddRef();&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return S_OK;&lt;BR&gt;&amp;nbsp; }&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&amp;nbsp;STDMETHOD(GetLCID)(LCID * plcid) {&lt;BR&gt;&amp;nbsp;&amp;nbsp; &amp;nbsp;return E_NOTIMPL;&lt;BR&gt;&amp;nbsp; }&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&amp;nbsp;STDMETHOD(GetItemInfo)(&lt;BR&gt;&amp;nbsp; &amp;nbsp;&amp;nbsp;LPCOLESTR pstrName,&lt;BR&gt;&amp;nbsp;&amp;nbsp; &amp;nbsp;DWORD dwReturnMask,&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; IUnknown ** ppunkItem,&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; ITypeInfo ** ppti) {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return E_NOTIMPL;&lt;BR&gt;&amp;nbsp;&amp;nbsp;}&lt;/P&gt;
&lt;P&gt;&amp;nbsp; STDMETHOD(GetDocVersionString)(BSTR * pbstrVersion) {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return E_NOTIMPL;&lt;BR&gt;&amp;nbsp; }&lt;/P&gt;
&lt;P&gt;&amp;nbsp; STDMETHOD(OnScriptTerminate)(&lt;BR&gt;&amp;nbsp;&amp;nbsp; &amp;nbsp;const VARIANT * pvarResult,&lt;BR&gt;&amp;nbsp;&amp;nbsp; &amp;nbsp;const EXCEPINFO * pexcepinfo) {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return S_OK;&lt;BR&gt;&amp;nbsp;&amp;nbsp;}&lt;/P&gt;
&lt;P&gt;&amp;nbsp; STDMETHOD(OnStateChange)(SCRIPTSTATE state) {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return S_OK;&lt;BR&gt;&amp;nbsp;&amp;nbsp;}&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&amp;nbsp;STDMETHOD(OnEnterScript)() {&lt;BR&gt;&amp;nbsp;&amp;nbsp; &amp;nbsp;return S_OK;&lt;BR&gt;&amp;nbsp; }&lt;BR&gt;&amp;nbsp;&lt;BR&gt;&amp;nbsp; STDMETHOD(OnLeaveScript)() {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return S_OK;&lt;BR&gt;&amp;nbsp;&amp;nbsp;}&lt;/P&gt;
&lt;P&gt;&amp;nbsp; STDMETHOD(OnScriptError)(IActiveScriptError * perror) {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; EXCEPINFO excepinfo;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; LONG column = 0;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; ULONG line = 0;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; DWORD context = 0;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; BSTR bstrLine = NULL;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; memset(&amp;amp;excepinfo, 0x00, sizeof excepinfo);&lt;BR&gt;&amp;nbsp;&amp;nbsp; &amp;nbsp;perror-&amp;gt;GetExceptionInfo(&amp;amp;excepinfo);&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (excepinfo.pfnDeferredFillIn != NULL)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;excepinfo.pfnDeferredFillIn(&amp;amp;excepinfo);&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; perror-&amp;gt;GetSourceLineText(&amp;amp;bstrLine);&lt;BR&gt;&amp;nbsp;&amp;nbsp; &amp;nbsp;perror-&amp;gt;GetSourcePosition(&amp;amp;context, &amp;amp;line, &amp;amp;column);&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&amp;nbsp; &amp;nbsp;wprintf(L"Error on line %ld column %ld\n", line, column);&lt;BR&gt;&amp;nbsp;&amp;nbsp; &amp;nbsp;if (bstrLine != NULL)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; wprintf(L"Line: %s\n", bstrLine);&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (excepinfo.bstrDescription != NULL)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;wprintf(L"Description: %s\n", excepinfo.bstrDescription);&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (excepinfo.bstrSource != NULL)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;wprintf(L"Source: %s\n", excepinfo.bstrSource);&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (excepinfo.bstrHelpFile != NULL)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;wprintf(L"Help: %s\n", excepinfo.bstrHelpFile);&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; SysFreeString(bstrLine);&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; SysFreeString(excepinfo.bstrDescription);&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; SysFreeString(excepinfo.bstrSource);&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; SysFreeString(excepinfo.bstrHelpFile);&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return S_OK;&lt;BR&gt;&amp;nbsp; }&lt;BR&gt;};&lt;/P&gt;
&lt;P&gt;void main() {&lt;BR&gt;&amp;nbsp; HRESULT hr = S_OK;&lt;BR&gt;&amp;nbsp; HRESULT hrInit;&lt;BR&gt;&amp;nbsp; IClassFactory * pfactory = NULL;&lt;BR&gt;&amp;nbsp; IActiveScript * pscript = NULL;&lt;BR&gt;&amp;nbsp; IActiveScriptParse * pparse = NULL;&lt;BR&gt;&amp;nbsp; IActiveScriptSite * psite = NULL;&lt;/P&gt;
&lt;P&gt;&amp;nbsp; hr = hrInit = OleInitialize(NULL);&lt;BR&gt;&amp;nbsp; if (FAILED(hr))&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; goto LError;&lt;/P&gt;
&lt;P&gt;&amp;nbsp; hr = CoGetClassObject(CLSID_VBScript, CLSCTX_SERVER, NULL, &lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; IID_IClassFactory, (void**)&amp;amp;pfactory);&lt;BR&gt;&amp;nbsp; if (FAILED(hr))&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; goto LError;&lt;/P&gt;
&lt;P&gt;&amp;nbsp; hr = pfactory-&amp;gt;CreateInstance(NULL, IID_IActiveScript, (void**)&amp;amp;pscript);&lt;BR&gt;&amp;nbsp; if (FAILED(hr))&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; goto LError;&lt;/P&gt;
&lt;P&gt;&amp;nbsp; psite = new(std::nothrow) MySite();&lt;BR&gt;&amp;nbsp; if (psite == NULL) {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; hr = E_OUTOFMEMORY;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; goto LError;&lt;BR&gt;&amp;nbsp; }&lt;/P&gt;
&lt;P&gt;&amp;nbsp; hr = pscript-&amp;gt;SetScriptSite(psite);&lt;BR&gt;&amp;nbsp; if (FAILED(hr))&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; goto LError;&lt;/P&gt;
&lt;P&gt;&amp;nbsp; hr = pscript-&amp;gt;QueryInterface(IID_IActiveScriptParse, (void**)&amp;amp;pparse);&lt;BR&gt;&amp;nbsp; if (FAILED(hr))&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; goto LError;&lt;/P&gt;
&lt;P&gt;&amp;nbsp; hr = pparse-&amp;gt;ParseScriptText(L"Function Foo \n Foo = 123 \n End Funtcion \n",&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; NULL, NULL, NULL, 0, 1, 0, NULL, NULL);&lt;/P&gt;
&lt;P&gt;&amp;nbsp; if (FAILED(hr))&lt;BR&gt;&amp;nbsp;&amp;nbsp; &amp;nbsp;goto LError;&lt;BR&gt;&amp;nbsp;&lt;BR&gt;LError:&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&amp;nbsp;if (FAILED(hr))&lt;BR&gt;&amp;nbsp;&amp;nbsp; &amp;nbsp;printf("%0x\n", hr);&lt;/P&gt;
&lt;P&gt;&amp;nbsp; if (pparse != NULL)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; pparse-&amp;gt;Release();&lt;/P&gt;
&lt;P&gt;&amp;nbsp; if (psite != NULL)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; psite-&amp;gt;Release();&lt;/P&gt;
&lt;P&gt;&amp;nbsp; if (pscript != NULL) {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; pscript-&amp;gt;Close();&lt;BR&gt;&amp;nbsp;&amp;nbsp; &amp;nbsp;pscript-&amp;gt;Release();&lt;BR&gt;&amp;nbsp;&amp;nbsp;}&lt;/P&gt;
&lt;P&gt;&amp;nbsp; if (pfactory != NULL)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; pfactory-&amp;gt;Release();&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&amp;nbsp;if (SUCCEEDED(hrInit))&lt;BR&gt;&amp;nbsp;&amp;nbsp; &amp;nbsp;OleUninitialize();&lt;BR&gt;}&lt;/P&gt;&lt;FONT face="lucida sans unicode" color=purple size=2&gt;
&lt;P&gt;As you would expect, this program prints out the information about the error, and ParseScriptText returns SCRIPT_E_REPORTED to indicate that there was an error but it has already been reported. Had there been no error, the script would not have actually&amp;nbsp;run; the engine is not &lt;STRONG&gt;started&lt;/STRONG&gt;, just &lt;STRONG&gt;initialized&lt;/STRONG&gt;.&lt;/P&gt;&lt;/FONT&gt;
&lt;P&gt;Error on line 3 column 5&lt;BR&gt;Line:&amp;nbsp; End Funtcion&lt;BR&gt;Description: Expected 'Function'&lt;BR&gt;Source: Microsoft VBScript compilation error&lt;BR&gt;80020101&lt;/P&gt;&lt;/FONT&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=480154" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/ericlippert/archive/tags/JScript/default.aspx">JScript</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/VBScript/default.aspx">VBScript</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Scripting/default.aspx">Scripting</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/COM+Programming/default.aspx">COM Programming</category></item><item><title>Checking For Script Syntax Errors</title><link>http://blogs.msdn.com/ericlippert/archive/2005/10/11/479696.aspx</link><pubDate>Tue, 11 Oct 2005 20:35:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:479696</guid><dc:creator>Eric Lippert</dc:creator><slash:comments>8</slash:comments><comments>http://blogs.msdn.com/ericlippert/comments/479696.aspx</comments><wfw:commentRss>http://blogs.msdn.com/ericlippert/commentrss.aspx?PostID=479696</wfw:commentRss><description>&lt;FONT face="lucida sans unicode" color=purple size=2&gt;
&lt;P&gt;A reader asked me recently whether there was a way to check a chunk of JScript or VBScript for syntax errors without actually running the code. I'm sure that there are many third-party tools which you could find that do this. If you have your own script host, you can do it yourself quite easily.&lt;/P&gt;
&lt;P&gt;The trick is to initialize the engine by setting the script site, but do not do anything that would move the engine from initialized into started state. (Note that attempting to evaluate an expression moves the engine to started state.) &lt;/P&gt;
&lt;P&gt;If the engine is initialzed but not started then calling &lt;FONT color=#000080&gt;ParseScriptText&lt;/FONT&gt; will check the text passed in for syntax errors but will not run the script.&amp;nbsp;Rather, if the script compiles successfully, it is simply marked as "needs to run when the engine is started".&amp;nbsp;&lt;/P&gt;
&lt;P&gt;Unfortunately the script engines do not have an error-recovering parser, so they will detect only the first syntax error and then bail out. Still, better than nothing.&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;/FONT&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=479696" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/ericlippert/archive/tags/JScript/default.aspx">JScript</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/VBScript/default.aspx">VBScript</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Scripting/default.aspx">Scripting</category></item><item><title>Local variables considered not very harmful</title><link>http://blogs.msdn.com/ericlippert/archive/2005/10/04/476938.aspx</link><pubDate>Tue, 04 Oct 2005 20:22:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:476938</guid><dc:creator>Eric Lippert</dc:creator><slash:comments>5</slash:comments><comments>http://blogs.msdn.com/ericlippert/comments/476938.aspx</comments><wfw:commentRss>http://blogs.msdn.com/ericlippert/commentrss.aspx?PostID=476938</wfw:commentRss><description>&lt;FONT face="lucida sans unicode"&gt;&lt;FONT color=#800080 size=2&gt;
&lt;P&gt;Like I said, that code from &lt;a href="http://blogs.msdn.com/ericlippert/archive/2005/09/30/475826.aspx"&gt;last time&lt;/A&gt;&amp;nbsp;was just test code, not real production code. Though clearly it works, I'd never write code like that in a million years. I'm not thrilled with the way it uses the &lt;/FONT&gt;&lt;FONT face="Lucida Console" color=#333399 size=2&gt;answer&lt;/FONT&gt;&lt;FONT color=#800080 size=2&gt; variable of the outer scope as an accumulator, and it is profoundly weird that the "do this function n times" function is a member of the&amp;nbsp;&lt;/FONT&gt;&lt;FONT face="Lucida Console" color=#333399 size=2&gt;Number&lt;/FONT&gt;&lt;FONT color=#800080 size=2&gt; prototype and not the&amp;nbsp;&lt;/FONT&gt;&lt;FONT face="Lucida Console" color=#333399 size=2&gt;Function &lt;/FONT&gt;&lt;FONT color=#800080 size=2&gt;prototype.&amp;nbsp; Worse still, we have a function that is essentially used as a composition operator that only makes sense to use on functions that have side effects and no arguments or returns.&amp;nbsp;That's a kind of&amp;nbsp;crazy way to do composition operations.&lt;/P&gt;
&lt;P&gt;I'd probably do something more like this:&lt;/P&gt;
&lt;P&gt;First, define a self-composition &lt;I&gt;factory&lt;/I&gt; on the &lt;/FONT&gt;&lt;FONT face="Lucida Console" color=#333399 size=2&gt;Function&lt;/FONT&gt;&lt;FONT color=#800080 size=2&gt; prototype, so that it is of general use on all functions of one argument, not just functions of no arguments and no returns&amp;nbsp;that have side effects. What we'll do is make a new member function for every function object that returns a new function which is equivalent to calling the input function n times:&lt;/P&gt;&lt;/FONT&gt;&lt;FONT face="Lucida Console" color=#333399 size=2&gt;
&lt;P&gt;Function.prototype.times = function(n) {&lt;BR&gt;&amp;nbsp; var f = this;&lt;BR&gt;&amp;nbsp; return function (x) {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;while (n &amp;gt; 0)&amp;nbsp;{&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;x = f(x);&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; --n;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return x;&lt;BR&gt;&amp;nbsp; };&lt;BR&gt;}&lt;/P&gt;&lt;/FONT&gt;&lt;FONT color=#800080 size=2&gt;
&lt;P&gt;Obviously we don't need to compose functions of more than one argument because we want to feed the &lt;I&gt;single&lt;/I&gt; output back into the input.&amp;nbsp;&amp;nbsp;Now we compose the function "multiply something by x" with itself&amp;nbsp;n times. That gives us the function "multiply something by x, n times".&amp;nbsp; Pass 1 to that function and we have a handy &lt;/FONT&gt;&lt;FONT face="Lucida Console" color=#333399 size=2&gt;raiseTo&lt;/FONT&gt;&lt;FONT color=#800080 size=2&gt; function:&lt;/P&gt;
&lt;P&gt;&lt;/FONT&gt;&lt;FONT face="Lucida Console" color=#333399 size=2&gt;Number.prototype.raiseTo = function(power) { &lt;BR&gt;&amp;nbsp; var x = this;&lt;BR&gt;&amp;nbsp; return function(y) {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/FONT&gt;&lt;FONT face="Lucida Console" color=#333399 size=2&gt;return x * y&lt;BR&gt;&amp;nbsp; }.times(power)(1);&lt;BR&gt;}&lt;/P&gt;&lt;/FONT&gt;&lt;FONT color=#800080 size=2&gt;
&lt;P&gt;No fuss, no muss, no accumulators, no side effects, no non-number-related functions on the number prototype.&amp;nbsp;I like it!&lt;/P&gt;
&lt;P&gt;Heck, if we wanted to get &lt;I&gt;really&lt;/I&gt; crazy then&amp;nbsp;we could eliminate the local variables entirely by introducing another function constructor in-line:&lt;/P&gt;&lt;/FONT&gt;&lt;FONT face="Lucida Console" color=#333399 size=2&gt;
&lt;P&gt;Function.prototype.times = function(n) {&lt;BR&gt;&amp;nbsp; return function(f) {&amp;nbsp;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return function (x) {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;while (n &amp;gt; 0) {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; x = f(x);&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; --n;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return x;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;BR&gt;&amp;nbsp; }(this);&lt;BR&gt;} &lt;/P&gt;
&lt;P&gt;Number.prototype.raiseTo = function(power) { &lt;BR&gt;&amp;nbsp; return function(x) {&lt;BR&gt;&amp;nbsp;&amp;nbsp; &amp;nbsp;return function(y) {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return x * y&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;BR&gt;&amp;nbsp; }(this).times(power)(1);&lt;BR&gt;}&lt;/FONT&gt;&lt;FONT color=#800080 size=2&gt;&lt;/P&gt;
&lt;P&gt;Local variables are actually an unnecessary syntactic sugar in Jscript.&amp;nbsp; We can do everything that local variables do by cleverly nesting function scopes.&amp;nbsp;However, it becomes &lt;I&gt;somewhat&lt;/I&gt; less easy to read, so I would stick to using local variables if I were you!&lt;/P&gt;&lt;/FONT&gt;&lt;/FONT&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=476938" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/ericlippert/archive/tags/JScript/default.aspx">JScript</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Scripting/default.aspx">Scripting</category></item><item><title>Guru meditations on scope chains of closures</title><link>http://blogs.msdn.com/ericlippert/archive/2005/09/30/475826.aspx</link><pubDate>Fri, 30 Sep 2005 22:41:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:475826</guid><dc:creator>Eric Lippert</dc:creator><slash:comments>11</slash:comments><comments>http://blogs.msdn.com/ericlippert/comments/475826.aspx</comments><wfw:commentRss>http://blogs.msdn.com/ericlippert/commentrss.aspx?PostID=475826</wfw:commentRss><description>&lt;FONT face="lucida sans unicode"&gt;&lt;FONT color=#800080 size=2&gt;
&lt;P&gt;I just had a really interesting meeting with some of the scripting community MVPs.&amp;nbsp; I may write up some notes on that meeting here next week, so watch this space.&lt;/P&gt;
&lt;P&gt;In other news, someone asked me&amp;nbsp;last night&amp;nbsp;(and I quote)&lt;/P&gt;
&lt;BLOCKQUOTE dir=ltr style="MARGIN-RIGHT: 0px"&gt;
&lt;P&gt;&lt;/FONT&gt;&lt;EM&gt;&lt;FONT size=2&gt;Oh ECMA guru, can you provide a succinct explanation of why the following code works, but if I replace &lt;/FONT&gt;&lt;FONT face="Lucida Console" color=#333399 size=2&gt;x&lt;/FONT&gt;&lt;FONT size=2&gt; with &lt;/FONT&gt;&lt;FONT face="Lucida Console" color=#333399 size=2&gt;this&lt;/FONT&gt;&lt;FONT size=2&gt; it fails?&lt;/P&gt;&lt;/BLOCKQUOTE&gt;&lt;/FONT&gt;&lt;/EM&gt;&lt;FONT color=#800080 size=2&gt;&lt;/FONT&gt;&lt;FONT face="Lucida Console" color=#333399 size=2&gt;
&lt;P&gt;Number.prototype.times = function(f) {&lt;BR&gt;&amp;nbsp; for(var i = 0; i &amp;lt; this; i++)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; f(); &lt;BR&gt;} &lt;BR&gt;Number.prototype.raiseTo = function(n) { &lt;BR&gt;&amp;nbsp; var answer = 1; &lt;BR&gt;&amp;nbsp; var x = this; &lt;BR&gt;&amp;nbsp; n.times(function(){ answer = &lt;B&gt;x &lt;/B&gt;* answer;}); // succeeds&lt;BR&gt;//n.times(function(){ answer = &lt;B&gt;this &lt;/B&gt;* answer;}); // fails!&lt;BR&gt;&amp;nbsp; return answer; &lt;BR&gt;} &lt;BR&gt;(3).raiseTo(2).raiseTo(5); &lt;/P&gt;&lt;/FONT&gt;&lt;FONT color=#800080 size=2&gt;
&lt;P&gt;Well I'd hardly describe myself as a guru, but I take the questioner's point -- surely if you set &lt;/FONT&gt;&lt;FONT face="Lucida Console" color=#333399 size=2&gt;x&lt;/FONT&gt;&lt;FONT color=#800080 size=2&gt; to &lt;/FONT&gt;&lt;FONT face="Lucida Console" color=#333399 size=2&gt;this&lt;/FONT&gt;&lt;FONT color=#800080 size=2&gt; then &lt;/FONT&gt;&lt;FONT face="Lucida Console" color=#333399 size=2&gt;x&lt;/FONT&gt;&lt;FONT color=#800080 size=2&gt; and &lt;/FONT&gt;&lt;FONT face="Lucida Console" color=#333399 size=2&gt;this&lt;/FONT&gt;&lt;FONT color=#800080 size=2&gt; should be aliases for each other, right?&lt;/P&gt;
&lt;P&gt;Often. But not in this case. &lt;/P&gt;
&lt;P&gt;The inner function's execution context contains a scope chain that includes the variable object of the outer function, so the inner function can see &lt;/FONT&gt;&lt;FONT face="Lucida Console" color=#333399 size=2&gt;x&lt;/FONT&gt;&lt;FONT color=#800080 size=2&gt; by looking up the scope chain. &lt;STRONG&gt;But &lt;/STRONG&gt;&lt;/FONT&gt;&lt;FONT face="Lucida Console" color=#333399 size=2&gt;&lt;STRONG&gt;this &lt;/STRONG&gt;&lt;/FONT&gt;&lt;FONT color=#800080 size=2&gt;&lt;STRONG&gt;is not a variable&lt;/STRONG&gt;, so it is not member of the outer function's variable object. Rather, it is a member of the outer function's execution context.&lt;/P&gt;
&lt;P&gt;Therefore the inner function's execution context gets the &lt;I&gt;global&lt;/I&gt; &lt;/FONT&gt;&lt;FONT face="Lucida Console" color=#333399 size=2&gt;this&lt;/FONT&gt;&lt;FONT color=#800080 size=2&gt;, in accordance with the ECMAScript specification, revision 3, section 10.2.3:&lt;/P&gt;
&lt;BLOCKQUOTE dir=ltr style="MARGIN-RIGHT: 0px"&gt;
&lt;P&gt;&lt;EM&gt;The caller provides the &lt;/EM&gt;&lt;/FONT&gt;&lt;EM&gt;&lt;FONT face="Lucida Console" color=#333399 size=2&gt;this&lt;/FONT&gt;&lt;FONT color=#800080 size=2&gt; value. If the &lt;/FONT&gt;&lt;FONT face="Lucida Console" color=#333399 size=2&gt;this&lt;/FONT&gt;&lt;FONT color=#800080 size=2&gt; value provided by the caller is not an object (including the case where it is &lt;/FONT&gt;&lt;FONT face="Lucida Console" color=#333399 size=2&gt;null&lt;/FONT&gt;&lt;/EM&gt;&lt;FONT color=#800080 size=2&gt;&lt;EM&gt;), then the this value is the global object.&lt;/EM&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;The global object is not something that can be multiplied, so the alternate version of the program fails.&lt;/P&gt;
&lt;P&gt;The code above was of course not real production code, it was just code that came up while testing an engine implementation. Obviously JScript already has a built-in power function that works much better than this crazy thing. But I'm in an expansive mood, so next time I'll talk a bit about some of the shortcomings of this programming style, and some ideas for improving it.&lt;/P&gt;&lt;/FONT&gt;&lt;/FONT&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=475826" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/ericlippert/archive/tags/JScript/default.aspx">JScript</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Scripting/default.aspx">Scripting</category></item><item><title>C# 3.0 is still statically typed, honest!</title><link>http://blogs.msdn.com/ericlippert/archive/2005/09/27/c-3-0-is-still-statically-typed-honest.aspx</link><pubDate>Tue, 27 Sep 2005 20:03:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:474462</guid><dc:creator>Eric Lippert</dc:creator><slash:comments>23</slash:comments><comments>http://blogs.msdn.com/ericlippert/comments/474462.aspx</comments><wfw:commentRss>http://blogs.msdn.com/ericlippert/commentrss.aspx?PostID=474462</wfw:commentRss><description>&lt;FONT face="lucida sans unicode"&gt;&lt;FONT color=#800080 size=2&gt;
&lt;P&gt;Since LINQ was announced I've seen a lot of really positive feedback and a lot of questions and concerns. Keep 'em coming! We need this feedback so that we can both correct misconceptions early and get the design right now.&lt;/P&gt;
&lt;P&gt;One of the misconceptions that I've seen a lot over the last few days in forums, blog posts and private emails is a confusion about what the new "type inferencing" feature implies for the type safety of the language. Apparently we have not been sufficiently clear on this point: &lt;B&gt;C# 3.0 will be statically typed, just like&amp;nbsp;C# 1.0 and 2.0. The var declaration style does not introduce dynamic typing or duck typing to C#.&lt;/P&gt;&lt;/B&gt;
&lt;P&gt;I think the confusion may arise from familiarity with other languages such as JScript. In JScript this is perfectly legal:&lt;/P&gt;&lt;/FONT&gt;&lt;FONT face="Lucida Console" color=#333399 size=2&gt;
&lt;P&gt;var foo = new Blah();&lt;BR&gt;foo = 123;&lt;BR&gt;foo = "hello";&lt;/P&gt;&lt;/FONT&gt;&lt;FONT color=#800080 size=2&gt;
&lt;P&gt;JScript is a dynamically typed language. You can assign any value of any type to a var.&lt;/P&gt;
&lt;P&gt;In C# 3.0, the var statement&amp;nbsp;means&amp;nbsp;"look at the type of the thing assigned to the variable, and act as though the variable was declared with that type." In other words, in C# the code above is just a syntactic sugar for&lt;/P&gt;&lt;/FONT&gt;&lt;FONT face="Lucida Console" color=#333399 size=2&gt;
&lt;P&gt;&lt;STRONG&gt;Blah&lt;/STRONG&gt; foo = new Blah();&lt;BR&gt;foo = 123;&lt;BR&gt;foo = "hello";&lt;/P&gt;&lt;/FONT&gt;&lt;FONT color=#800080 size=2&gt;
&lt;P&gt;which of course would produce a type error on the second and third lines.&lt;/P&gt;
&lt;P&gt;If you take a look at section 26.1 of the C# 3.0 specification you'll see that the var statement has a lot of restrictions on it to ensure that the compiler always has enough information to make the correct type inference. Namely:&lt;/P&gt;
&lt;UL&gt;
&lt;LI&gt;the declarator must include an initializer, so that we can infer the type of the variable from the type of the initializer&lt;/LI&gt;
&lt;LI&gt;the initializer has to be something that we can figure out the type of – not null or a collection initializer&lt;/LI&gt;&lt;/UL&gt;
&lt;P&gt;Compare this to JScript .NET, which has a much stronger type inference mechanism. JScript .NET does not require initializers in var statements; the compiler tracks all assignments to the variable and infers the best type. If, say, only strings are assigned to a variable then it will infer the string type. JScript .NET also infers return types of functions by a similar mechanism. But the goal of the JScript .NET type inference mechanism was to &lt;STRONG&gt;increase the performance of legacy dynamically typed code&lt;/STRONG&gt;. If we can infer a type and thereby generate faster, smaller code, we do so.&amp;nbsp; If not, we don't.&lt;/P&gt;
&lt;P&gt;Then why introduce this syntactic sugar in C# 3.0? C# doesn't have a body of legacy dynamic code like JScript and already generates efficient code.&lt;/P&gt;
&lt;P&gt;There are two reasons, one which exists today, one which will crop up in 3.0. &lt;/P&gt;
&lt;P&gt;The first reason is that this code is incredibly ugly because of all the redundancy:&lt;/P&gt;&lt;/FONT&gt;&lt;FONT face="Lucida Console" color=#333399 size=2&gt;
&lt;P&gt;Dictionary&amp;lt;string, List&amp;lt;int&amp;gt;&amp;gt; mylists = new Dictionary&amp;lt;string, List&amp;lt;int&amp;gt;&amp;gt;();&lt;/P&gt;&lt;/FONT&gt;&lt;FONT color=#800080 size=2&gt;
&lt;P&gt;And that's a simple example – I've written worse. Any time you're forced to type exactly the same thing twice, that's a redundancy that we can remove. Much nicer to write&lt;/P&gt;&lt;/FONT&gt;&lt;FONT face="Lucida Console" color=#333399 size=2&gt;
&lt;P&gt;var mylists = new Dictionary&amp;lt;string, List&amp;lt;int&amp;gt;&amp;gt;();&lt;/P&gt;&lt;/FONT&gt;&lt;FONT color=#800080 size=2&gt;
&lt;P&gt;and let the compiler figure out what the type is based on the assignment.&lt;/P&gt;
&lt;P&gt;Second, C# 3.0 introduces anonymous types. Since anonymous types by definition have no names, you need to be able to infer the type of the variable from the initializing expression if its type is anonymous.&lt;/P&gt;
&lt;P&gt;We'll discuss the reasoning behind anonymous types in another post.&lt;/P&gt;&lt;/FONT&gt;&lt;/FONT&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=474462" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/ericlippert/archive/tags/JScript+.NET/default.aspx">JScript .NET</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/JScript/default.aspx">JScript</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Type+Inference/default.aspx">Type Inference</category></item><item><title>Implementing Event Handling, Part Two</title><link>http://blogs.msdn.com/ericlippert/archive/2005/09/21/472465.aspx</link><pubDate>Wed, 21 Sep 2005 21:51:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:472465</guid><dc:creator>Eric Lippert</dc:creator><slash:comments>3</slash:comments><comments>http://blogs.msdn.com/ericlippert/comments/472465.aspx</comments><wfw:commentRss>http://blogs.msdn.com/ericlippert/commentrss.aspx?PostID=472465</wfw:commentRss><description>&lt;FONT face="lucida sans unicode" color=purple size=2&gt;
&lt;P&gt;It's been an insanely busy month for me, between having multiple out-of-town guests, throwing a party for the people who couldn't make it to the wedding, and oh yeah, getting up to speed on the C# compiler and trying to understand the implications that LINQ features are going to have on the current implementation.&amp;nbsp; Not much time for blogging.&amp;nbsp;Hopefully October will be a little bit more under control.&lt;/P&gt;
&lt;P&gt;Anyway, &lt;a href="http://blogs.msdn.com/ericlippert/archive/2005/09/09/463215.aspx"&gt;I was talking about early-bound event binding&lt;/A&gt;. Basically the idea is that the source and the sink agree upon an interface that the source can call on the sink whenever the source wishes to fire an event. Before we get into that more, I want to talk briefly about early- and late-bound code.&lt;/P&gt;
&lt;P&gt;At an implementation level, what is the difference between early- and late- bound code? In the early-bound world, a particular function on an interface&amp;nbsp;gets called&amp;nbsp;when the caller&amp;nbsp;dereferences the callee's virtual function table and transfers control directly to the function by changing the instruction pointer on the chip.&amp;nbsp;In the late-bound world, the caller calls &lt;FONT color=#000080&gt;IDispatch::Invoke&lt;/FONT&gt; and passes in a magic number that tells the callee what function it should be calling, and the callee is then responsible for dispatching the function appropriately. (Hence the name "&lt;FONT color=#000080&gt;IDispatch&lt;/FONT&gt;".)&lt;/P&gt;
&lt;P&gt;The script engines use &lt;FONT color=#000080&gt;IDispatch&lt;/FONT&gt; all the time to call out to functions on objects. When calling an object late-bound, you don't know until you actually try the call whether or not it is going to succeed, because you do not know the interface the object implements.&amp;nbsp; So you call &lt;FONT color=#000080&gt;GetIdsOfNames&lt;/FONT&gt; to get the magic number associated with a particular function, Invoke on that magic number,&amp;nbsp;and let the callee sort it out. In this situation, the caller (the script engine)&amp;nbsp;knows the name of the function it wants to call, and the callee (the object)&amp;nbsp;can map the name to the appropriate identifier.&lt;/P&gt;
&lt;P&gt;Now consider how this works if &lt;FONT color=#000080&gt;IDispatch&lt;/FONT&gt; is the interface over which the source (the object) is calling back the sink (the script host). This &lt;EM&gt;appears&lt;/EM&gt; to be the same situation, but in fact it is completely different.&amp;nbsp; It appears the same because from the perspective of how COM actually manages all the calls, its exactly the same.&amp;nbsp; &lt;FONT color=#000080&gt;IDispatch&lt;/FONT&gt; is an interface like any other, and the source can call the sink's &lt;FONT color=#000080&gt;IDispatch&lt;/FONT&gt; to its heart's content if that's the interface that they agree to talk over.&lt;/P&gt;
&lt;P&gt;But look at it from the point of view of the sink: the &lt;EM&gt;caller&lt;/EM&gt; knows what the magic number means and the callee does not, but it's the callee who is being asked to do the dispatching!&amp;nbsp;You're sitting there sinking events of who knows what object, and every now and then you get a call on &lt;FONT color=#000080&gt;IDispatch::Invoke&lt;/FONT&gt; with some unknown dispid.&amp;nbsp; What the heck are you supposed to do with that?&amp;nbsp; In the late-bound world, instead of getting a nice direct call on "&lt;FONT color=#000080&gt;Tick()... Tick()...&amp;nbsp; Tick()...&lt;/FONT&gt;"&amp;nbsp; you're getting "12...&amp;nbsp; 12...&amp;nbsp; 12..." and &lt;EM&gt;you have no idea what "12" means.&lt;BR&gt;&lt;/EM&gt;&amp;nbsp;&lt;BR&gt;Let's tie this in to scripting.&amp;nbsp; Suppose you're in Windows Script Host and you do something like:&lt;BR&gt;&amp;nbsp;&lt;BR&gt;&lt;FONT color=#000080&gt;Sub Timer_Tick()&lt;BR&gt;&amp;nbsp; 'whatever&lt;BR&gt;End Sub&lt;BR&gt;Set Timer = CreateObject("mytimer")&lt;BR&gt;WScript.ConnectObject Timer, "Timer_"&lt;BR&gt;Timer.Start 10&lt;BR&gt;WScript.Sleep 1000&lt;/FONT&gt;&lt;BR&gt;&amp;nbsp;&lt;BR&gt;&lt;FONT color=#000080&gt;&lt;FONT color=#800080&gt;There are many&amp;nbsp;&lt;FONT color=#000080&gt;IDispatch&lt;/FONT&gt; objects here and we'll look at three of them.&amp;nbsp;First, there's the source, that is, the timer object.&amp;nbsp;Then there's the sink, owned by the host and created when the source is connected to it.&amp;nbsp;Finally there is the script engine itself, upon which the host can dispatch calls to global functions such as the event handler.&lt;/FONT&gt;&lt;/FONT&gt;&lt;/P&gt;
&lt;P&gt;&lt;FONT color=#000080&gt;ConnectObject&lt;/FONT&gt;&amp;nbsp;is given a source&amp;nbsp;object.&amp;nbsp; It has no idea what early-bound &lt;EM&gt;outgoing&lt;/EM&gt; interface is on that object, and it certainly doesn't have an implementation of such an interface even if there is one, so it is going to have to do a late bound sink.&amp;nbsp; It creates an object to act as the sink, gets an &lt;FONT color=#000080&gt;IDispatch&lt;/FONT&gt;-enabled connection point from the source, and advises it.&lt;BR&gt;&amp;nbsp;&lt;BR&gt;Now the script engine calls &lt;FONT color=#000080&gt;Start&lt;/FONT&gt; (via &lt;FONT color=#000080&gt;IDispatch &lt;/FONT&gt;on the source)&amp;nbsp;and goes to sleep.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;Pretty soon the timer invokes the sink, passing in the dispatch identifier for &lt;FONT color=#000080&gt;Tick&lt;/FONT&gt;.&amp;nbsp;&amp;nbsp;&lt;BR&gt;&lt;BR&gt;The sink&amp;nbsp;needs to know which sub to call in the script engine.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;Fortunately, it has an &lt;FONT color=#000080&gt;IDispatch&lt;/FONT&gt; pointer to the source, and a dispatch identifier.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;Unfortunately, though &lt;FONT color=#000080&gt;IDispatch&lt;/FONT&gt; provides a function which maps from name to id, it provides no function&amp;nbsp;that&amp;nbsp;maps the other way. &lt;/P&gt;
&lt;P&gt;Fortunately, &lt;FONT color=#000080&gt;IDispatch&lt;/FONT&gt; &lt;EM&gt;does&lt;/EM&gt; provide a function that enables the host to obtain a type information structure which contains a list of all the methods and what their dispatch identifiers are. Therefore&amp;nbsp;we can search all the methods in the type info and check to see which has the desired dispatch identifier.&amp;nbsp; That then gives us the method name, so we know which event handler function to dispatch on the script engine. &lt;/P&gt;
&lt;P&gt;Unfortunately there is a major design flaw in &lt;FONT color=#000080&gt;IDispatch&lt;/FONT&gt; -- it gives you the&amp;nbsp;type info for the incoming interface -- the &lt;FONT color=#000080&gt;ITimer&lt;/FONT&gt;.&amp;nbsp; But there is no way to take the &lt;FONT color=#000080&gt;ITypeInfo&lt;/FONT&gt; for &lt;FONT color=#000080&gt;ITimer&lt;/FONT&gt; and say "give me the type info &lt;EM&gt;for the class as a whole&lt;/EM&gt; so that I can obtain the type info for the &lt;EM&gt;outgoing&lt;/EM&gt; interface".&lt;BR&gt;&amp;nbsp;&lt;BR&gt;Fortunately,&amp;nbsp;&lt;FONT color=#000080&gt;IProvideClassInfo&lt;/FONT&gt; was invented.&amp;nbsp; IPCI gives you back the "root" type info for an object, from which you can obtain a type info for the default outgoing interface, from which you can map the dispatch identifier to the name.&lt;/P&gt;
&lt;P&gt;Unfortunately, many objects do not implement &lt;FONT color=#000080&gt;IProvideClassInfo&lt;/FONT&gt;, and therefore cannot&amp;nbsp;have their events hooked up by&amp;nbsp;&lt;FONT color=#000080&gt;ConnectObject&lt;/FONT&gt;.&lt;/P&gt;
&lt;P&gt;(I feel a little bit like the ending of Dr. Strangelove here.&amp;nbsp; Fortunately, they stop General Ripper in time.&amp;nbsp; Unfortunately, the secret code died with him. Fortunately they figure out the code. Unfortunately, the radio is broken.&amp;nbsp; Fortunately, the bomb bay doors are stuck. Unfortunately, they fix them, and the Doomsday Device destroys the world. Bummer.)&lt;/P&gt;
&lt;P&gt;The moral of this story is simple: &lt;STRONG&gt;for late bound events to work, at some point the class of the source must be known&lt;/STRONG&gt;. And therefore:&lt;/P&gt;
&lt;UL&gt;
&lt;LI&gt;"automagic event binding" in IE only works on "named items" present in the script engine.&amp;nbsp; (The script engines require that the host provide a coclass type info for named items, and build the sinks very early on, before other code runs.) 
&lt;LI&gt;&lt;FONT color=#000080&gt;WScript.CreateObject&lt;/FONT&gt; can &lt;EM&gt;always&lt;/EM&gt; hook up events. The class type info is known because &lt;FONT color=#000080&gt;CreateObject&lt;/FONT&gt; had to create an instance of the class. 
&lt;LI&gt;&lt;FONT color=#000080&gt;WScript.ConnectObject&lt;/FONT&gt; can hook up events&amp;nbsp;only if&amp;nbsp;the object implements &lt;FONT color=#000080&gt;IProvideClassInfo&lt;/FONT&gt;&lt;/LI&gt;&lt;/UL&gt;
&lt;P&gt;I hope that clears up any confusion about what &lt;FONT color=#000080&gt;IProvideClassInfo&lt;/FONT&gt; is for!&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;/FONT&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=472465" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/ericlippert/archive/tags/JScript/default.aspx">JScript</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/VBScript/default.aspx">VBScript</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Scripting/default.aspx">Scripting</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/COM+Programming/default.aspx">COM Programming</category></item><item><title>Recursion, Part Six: Making CPS Work</title><link>http://blogs.msdn.com/ericlippert/archive/2005/08/15/recursion-part-six-making-cps-work.aspx</link><pubDate>Mon, 15 Aug 2005 13:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:442714</guid><dc:creator>Eric Lippert</dc:creator><slash:comments>2</slash:comments><comments>http://blogs.msdn.com/ericlippert/comments/442714.aspx</comments><wfw:commentRss>http://blogs.msdn.com/ericlippert/commentrss.aspx?PostID=442714</wfw:commentRss><description>&lt;FONT face="lucida sans unicode" color=purple size=2&gt;
&lt;P&gt;JScript doesn't support CPS natively but we can write another dispatch engine that makes it work. There's only ever one active continuation, so lets have a new rule:&amp;nbsp; JScript CPS&amp;nbsp;functions are allowed to return, but the last thing that they do must be to tell our dispatch engine what the continuation was.&lt;/P&gt;
&lt;P&gt;To keep things simple, we'll also say &lt;STRONG&gt;that every CPS-style function takes exactly one argument&lt;/STRONG&gt;. Of course, that can be an object that contains multiple fields should the function require multiple arguments.&lt;/P&gt;
&lt;P&gt;Let's go through our CPS treeDepth program and replace all the continuation calls with calls that tell the runtime engine what continuation to use next.&amp;nbsp; We'll then return normally and let the runtime engine call the continuation for us.&lt;/P&gt;&lt;FONT face="lucida console" color=navy&gt;
&lt;P&gt;function treeDepth(args)&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; if (args.curtree == null)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; cont(args.afterDepth, 0);&lt;BR&gt;&amp;nbsp; else&lt;BR&gt;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; function afterLeft(leftDepth)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; function afterRight(rightDepth)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; cont(args.afterDepth, 1+Math.max(leftDepth, rightDepth));&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; cont(treeDepth, {curtree: args.curtree.right, afterDepth: afterRight});&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; cont(treeDepth, {curtree: args.curtree.left, afterDepth: afterLeft});&lt;BR&gt;&amp;nbsp; }&lt;BR&gt;}&lt;/P&gt;&lt;/FONT&gt;
&lt;P&gt;The dispatch engine is very simple:&lt;/P&gt;&lt;FONT face="lucida console" color=navy&gt;
&lt;P&gt;var continuation = null;&lt;BR&gt;function cont(newfunc, newargs)&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; continuation = { func: newfunc, args : newargs };&lt;BR&gt;}&lt;/P&gt;
&lt;P&gt;function run()&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; while(continuation != null)&lt;BR&gt;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; var curfunc = continuation.func;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; var curargs = continuation.args;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; continuation = null;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; curfunc(curargs);&lt;BR&gt;&amp;nbsp; }&lt;BR&gt;}&lt;/P&gt;&lt;/FONT&gt;
&lt;P&gt;No stack at all this time. Just a single global variable saying what to call next. If there is nothing to call next, we're done. To determine the depth of a tree we simply tell the continuation engine what the next thing to do is, and start it running:&lt;/P&gt;&lt;FONT face="lucida console" color=navy&gt;
&lt;P&gt;cont(treeDepth, {curtree: mytree, afterDepth: print});&lt;BR&gt;run();&lt;/P&gt;&lt;/FONT&gt;
&lt;P&gt;and hey presto, we've just implemented a recursive function with no stack that prints the depth of an arbitrary binary tree.&lt;/P&gt;
&lt;P&gt;Nice trick! Of course, &lt;STRONG&gt;really what we've done is we've just hidden the call stack in another harder-to-see data structure. Where is it?&lt;/STRONG&gt; (Hint: draw some diagrams that show what all the closure name table bindings are during the recursion.)&lt;/P&gt;
&lt;P&gt;That's all I managed to get done here before my vacation. When I get back, maybe I'll &lt;EM&gt;pop the stack&lt;/EM&gt; and pick up where we left off, or maybe I'll &lt;EM&gt;continue&lt;/EM&gt; with something completely different and forget all about my current state.&amp;nbsp; (Or maybe I'm actually interrupt driven, which seems most likely.) Who knows? Whatever happens though, it'll probably be another &lt;STRONG&gt;fabulous adventure in coding&lt;/STRONG&gt;.&lt;/P&gt;
&lt;P&gt;***********************************&lt;/P&gt;
&lt;P&gt;Further reading:&lt;/P&gt;
&lt;P&gt;Don Box on closures and CPS in C# 2.0: &lt;A href="http://pluralsight.com/blogs/dbox/archive/2005/04/27/7780.aspx"&gt;http://pluralsight.com/blogs/dbox/archive/2005/04/27/7780.aspx&lt;/A&gt;&lt;/P&gt;
&lt;P&gt;(Eric is on vacation; this message was pre-recorded.)&amp;nbsp;&lt;/P&gt;&lt;/FONT&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=442714" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/ericlippert/archive/tags/JScript/default.aspx">JScript</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Scripting/default.aspx">Scripting</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Rarefied+Heights/default.aspx">Rarefied Heights</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Recursion/default.aspx">Recursion</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Continuation+Passing+Style/default.aspx">Continuation Passing Style</category></item><item><title>Recursion, Part Five: More on CPS</title><link>http://blogs.msdn.com/ericlippert/archive/2005/08/11/recursion-part-five-more-on-cps.aspx</link><pubDate>Thu, 11 Aug 2005 13:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:442711</guid><dc:creator>Eric Lippert</dc:creator><slash:comments>0</slash:comments><comments>http://blogs.msdn.com/ericlippert/comments/442711.aspx</comments><wfw:commentRss>http://blogs.msdn.com/ericlippert/commentrss.aspx?PostID=442711</wfw:commentRss><description>&lt;FONT face="lucida sans unicode" color=purple size=2&gt;
&lt;P&gt;Suppose we wanted to write this by-now-familiar little function in continuation passing style:&lt;/P&gt;&lt;FONT face="lucida console" color=navy&gt;
&lt;P&gt;function treeDepth(curtree)&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; if (curtree == null)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return 0;&lt;BR&gt;&amp;nbsp; else&lt;BR&gt;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; var leftDepth = treeDepth(curtree.left);&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; var rightDepth = treeDepth(curtree.right);&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return 1 + Math.max(leftDepth, rightDepth);&lt;BR&gt;&amp;nbsp; }&lt;BR&gt;}&lt;/P&gt;&lt;/FONT&gt;
&lt;P&gt;Let's start by getting rid of the returns, since there are no returns in CPS. Rather, we "return" by passing the return value to the continuation. Remember, the continuation is "what are we supposed to do after this function is done?"&lt;/P&gt;&lt;FONT face="lucida console" color=navy&gt;
&lt;P&gt;function treeDepth(curtree, afterDepth)&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; if (curtree == null)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; afterDepth(0);&lt;BR&gt;&amp;nbsp; else&lt;BR&gt;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; //UNDONE: var leftDepth = treeDepth(curtree.left);&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; //UNDONE: var rightDepth = treeDepth(curtree.right);&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; afterDepth(1 + Math.max(leftDepth, rightDepth));&lt;BR&gt;&amp;nbsp; }&lt;BR&gt;}&lt;/P&gt;&lt;/FONT&gt;
&lt;P&gt;We'll presume that the addition and maximum&amp;nbsp;guys are not written in CPS, just to keep this simple.&lt;/P&gt;
&lt;P&gt;OK, this is a start, but now we need to fix up those recursive calls.&amp;nbsp; Consider the second recursive call.&amp;nbsp; What is its continuation?&amp;nbsp; That is, what needs to happen after the right tree depth is determined?&amp;nbsp; Two things. First, the maximum of left and right must be calculated and incremented.&amp;nbsp; Second, we've promised our caller that when we're done, we'll call its continuation.&amp;nbsp; So let's write a closure that does those two things.&lt;/P&gt;&lt;FONT face="lucida console" color=navy&gt;
&lt;P&gt;function treeDepth(curtree, afterDepth)&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; if (curtree == null)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; afterDepth(0);&lt;BR&gt;&amp;nbsp; else&lt;BR&gt;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; function afterRight(rightDepth)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; afterDepth(1 + Math.max(leftDepth, rightDepth));&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; // UNDONE: var leftDepth = treeDepth(curtree.left);&amp;nbsp;&amp;nbsp; &lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; treeDepth(curtree.right, afterRight);&lt;BR&gt;&amp;nbsp; }&lt;BR&gt;}&lt;/P&gt;&lt;/FONT&gt;
&lt;P&gt;We're making progress. What do we need to do after we determine the depth of the left tree?&amp;nbsp; Pass the left depth to a continuation that recurses on the right tree to determine the right depth,&amp;nbsp;does the max, and calls the &lt;FONT color=#000080&gt;afterDepth&lt;/FONT&gt; continuation.&lt;/P&gt;&lt;FONT face="lucida console" color=navy&gt;
&lt;P&gt;function treeDepth(curtree, afterDepth)&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; if (curtree == null)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; afterDepth(0);&lt;BR&gt;&amp;nbsp; else&lt;BR&gt;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; function afterLeft(leftDepth)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; function afterRight(rightDepth)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; afterDepth(1 + Math.max(leftDepth, rightDepth));&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; treeDepth(curtree.right, afterRight);&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; treeDepth(curtree.left, afterLeft);&lt;BR&gt;&amp;nbsp; }&lt;BR&gt;}&lt;/P&gt;&lt;/FONT&gt;
&lt;P&gt;And we're done.&amp;nbsp; We've got a CPS version of &lt;FONT color=#000080&gt;treeDepth&lt;/FONT&gt; which never returns and therefore we never need to keep track of what is on the stack, because we're never coming back.&lt;/P&gt;
&lt;P&gt;Of course, like I said last time, in reality JScript does &lt;STRONG&gt;not&lt;/STRONG&gt; detect that we're in this situation and optimize away the stack frames.&amp;nbsp; This program still pushes interpreters on the system stack and still runs out of stack space if you have a 1500-deep branch in your tree.&lt;/P&gt;
&lt;P&gt;But we can fake it out.&amp;nbsp; Next time, we'll finish up with a CPS program that really doesn't run out of stack space, even in JScript.&lt;/P&gt;
&lt;P&gt;(Eric is on vacation; this message was pre-recorded.)&lt;/P&gt;&lt;/FONT&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=442711" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/ericlippert/archive/tags/JScript/default.aspx">JScript</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Scripting/default.aspx">Scripting</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Rarefied+Heights/default.aspx">Rarefied Heights</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Recursion/default.aspx">Recursion</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Continuation+Passing+Style/default.aspx">Continuation Passing Style</category></item><item><title>Recursion, Part Four: Continuation Passing Style</title><link>http://blogs.msdn.com/ericlippert/archive/2005/08/08/recursion-part-four-continuation-passing-style.aspx</link><pubDate>Mon, 08 Aug 2005 13:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:442706</guid><dc:creator>Eric Lippert</dc:creator><slash:comments>4</slash:comments><comments>http://blogs.msdn.com/ericlippert/comments/442706.aspx</comments><wfw:commentRss>http://blogs.msdn.com/ericlippert/commentrss.aspx?PostID=442706</wfw:commentRss><description>&lt;FONT face="lucida sans unicode" color=purple size=2&gt;
&lt;P&gt;We're getting hung up on the stack management aspects of recursive programming. &lt;STRONG&gt;Why do we need a stack at all? What purpose does it serve?&lt;/STRONG&gt;&lt;/P&gt;
&lt;P&gt;If you're like most developers, you probably learned about subroutines and functions at an early age. The idea is pretty straightforward.&amp;nbsp; You stop what you're doing right now, go perform some other task, and then pick up where you left off, possibly using data computed by the other task.&amp;nbsp; But this idea of "pick up where you left off" means that you have to have some mechanism for storing information about what you were doing and where to pick it up. A stack is a natural data structure for that, so we've been thinking a lot about stacks lately when we consider how to operate on recursive data structures.&lt;/P&gt;
&lt;P&gt;But what if we simply denied the whole premise of functions? What if we said that &lt;STRONG&gt;no function was ever allowed to return&lt;/STRONG&gt;?&amp;nbsp; It either terminates the program, or itself calls another function.&lt;/P&gt;
&lt;P&gt;You might be thinking that clearly the cure is worse than the disease.&amp;nbsp; I mean, sure, now you don't have to keep track of what you were doing, but that's because you're never going to get back there!&amp;nbsp; How is it possible to get any work done at all if every time you try to call a procedure for a little help, it takes over control and never comes back to you?&lt;/P&gt;
&lt;P&gt;This sounds like crazy talk, but let's think about the consequences of removing all returns from the language. Three things are clear. &lt;/P&gt;
&lt;P&gt;First, if you yourself write a function then &lt;STRONG&gt;calling another function has to be the last thing you do&lt;/STRONG&gt;. Control is never coming back, so there's no point in having any code after a function call. &lt;/P&gt;
&lt;P&gt;Second, suppose you have more work to do after you call a function foo. Foo is in the same position as you -- the last thing it does will either be a function call or terminating the program. Therefore, you need to put the work that needs to be done after foo into function bar, and make for darn sure that foo calls bar rather than terminating!&lt;/P&gt;
&lt;P&gt;But if you didn't write foo, how do you know that foo is going to call bar when its done?&amp;nbsp; You need to somehow tell foo to call bar, and hope that foo cooperates.&lt;/P&gt;
&lt;P&gt;Third, if someone calls your function then&amp;nbsp;they're in the same boat -- it's the last thing they're going to do, ever, because you're not coming back. You need to find some way to allow your caller to tell you what to do when you're done your work. &lt;/P&gt;
&lt;P&gt;This idea of functions never returning, and callers passing their functions information about what needs to be done next, is a bizarre but powerful style of programming called &lt;STRONG&gt;Continuation Passing Style&lt;/STRONG&gt;. The "information about what to do next" is called a "continuation", which is passed from function to function, hence the name.&lt;/P&gt;
&lt;P&gt;Many languages support CPS natively -- Scheme, Ruby and Rhino, for example, all support CPS.&amp;nbsp; To get it working in JScript will take some doing, but when we're done there will be no explicit stack at all in our formerly recursive program.&lt;/P&gt;
&lt;P&gt;In the next episode I'm going to write our tree depth program in a mix of CPS and regular procedural programming. (To be purely CPS we'd write CPS versions of the addition operators, the &lt;FONT style="BACKGROUND-COLOR: #ffffff" color=#000080&gt;Math.max&lt;/FONT&gt; function, and so on, but I'm not going to go there&amp;nbsp; -- that's overkill.)&amp;nbsp; But before we get into the tree depth program let's get a little more familiar with CPS.&lt;/P&gt;
&lt;P&gt;Suppose we had this fragment of a JScript program:&lt;/P&gt;&lt;FONT face="lucida console" color=navy&gt;
&lt;P&gt;function foo(x)&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; var y = bar();&lt;BR&gt;&amp;nbsp; blah(x,y); &lt;BR&gt;}&lt;BR&gt;function bar()&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; return 123;&lt;BR&gt;}&lt;BR&gt;function blah(a, b)&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; print(a+b);&lt;BR&gt;}&lt;BR&gt;foo(1);&lt;/P&gt;&lt;/FONT&gt;
&lt;P&gt;I hope you agree that this is a very straightforward program. How would we do this in CPS?&amp;nbsp; Well, first of all, every function would have to take an extra argument for the continuation. Our program calls foo and then terminates, so the continuation of the call to foo is "terminate the program".&amp;nbsp; Let's presume that we have a magic function that does that.&lt;/P&gt;&lt;FONT face="lucida console" color=navy&gt;
&lt;P&gt;function foo(x, cfoo)&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; // UNDONE: rewrite foo in CPS&lt;BR&gt;}&lt;BR&gt;foo(1, terminate);&lt;/P&gt;&lt;/FONT&gt;
&lt;P&gt;Let's reason about &lt;FONT color=#000080&gt;foo&lt;/FONT&gt; from end to start. &lt;FONT color=#000080&gt;foo&lt;/FONT&gt; wants to ensure that three things happen in this order: &lt;/P&gt;
&lt;UL&gt;
&lt;LI&gt;&lt;FONT color=#000080&gt;bar&lt;/FONT&gt; runs 
&lt;LI&gt;&lt;FONT color=#000080&gt;blah&lt;/FONT&gt; runs 
&lt;LI&gt;&lt;FONT color=#000080&gt;foo&lt;/FONT&gt;'s continuation from its caller runs&lt;/LI&gt;&lt;/UL&gt;
&lt;P&gt;But &lt;FONT color=#000080&gt;blah&lt;/FONT&gt; is never going to return.&amp;nbsp;&lt;STRONG&gt; Therefore we'll make it &lt;FONT color=#000080&gt;blah&lt;/FONT&gt;'s responsibility to call &lt;FONT color=#000080&gt;foo&lt;/FONT&gt;'s continuation when it is done.&lt;/STRONG&gt; We'll rewrite &lt;FONT color=#000080&gt;blah&lt;/FONT&gt; so that it does CPS, so that we can say:&lt;/P&gt;&lt;FONT face="lucida console" color=navy&gt;
&lt;P&gt;function foo(x, cfoo)&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; var y = bar();&lt;BR&gt;&amp;nbsp; blah(x,y,cfoo); &lt;BR&gt;}&lt;/P&gt;&lt;/FONT&gt;
&lt;P&gt;OK, super, we've taken care of our responsibility to our caller by foisting it off onto &lt;FONT color=#000080&gt;blah&lt;/FONT&gt;.&amp;nbsp; But now we have an additional problem. &lt;FONT color=#000080&gt;bar&lt;/FONT&gt; is never going to return, so we're never going to call &lt;FONT color=#000080&gt;blah&lt;/FONT&gt;!&amp;nbsp; We've both failed in our responsibility to our caller and haven't done the work we need to do.&lt;/P&gt;
&lt;P&gt;We have an additional problem. &lt;FONT color=#000080&gt;bar&lt;/FONT&gt; was going to return a value that we were going to use. But we've just removed returns from the language! Let's solve both of these problems.&amp;nbsp; We'll&amp;nbsp;say that &lt;FONT color=#000080&gt;bar&lt;/FONT&gt; takes a continuation and &lt;STRONG&gt;passes the value that it was going to return as an argument to its continuation&lt;/STRONG&gt;. That's functionally the same thing, right? Before, you return the value to "whatever you were going to do next", now you pass the value to "whatever you were going to do next", same thing.&lt;/P&gt;
&lt;P&gt;But what continuation should &lt;FONT color=#000080&gt;foo&lt;/FONT&gt; pass to &lt;FONT color=#000080&gt;bar&lt;/FONT&gt;?&amp;nbsp; Well, what does &lt;FONT color=#000080&gt;foo&lt;/FONT&gt; want done when &lt;FONT color=#000080&gt;bar&lt;/FONT&gt; calls its continuation with its "return" value?&amp;nbsp; That's easy. It wants to call &lt;FONT color=#000080&gt;blah&lt;/FONT&gt; with that value and &lt;FONT color=#000080&gt;foo&lt;/FONT&gt;'s original arguments.&amp;nbsp;We can&amp;nbsp;write a helper function that does that.&lt;/P&gt;&lt;FONT face="lucida console" color=navy&gt;
&lt;P&gt;function foo(x, afterfoo)&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; function foocontinuation(y)&lt;BR&gt;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; blah(x,y,afterfoo); &lt;BR&gt;&amp;nbsp; }&lt;BR&gt;&amp;nbsp; bar(foocontinuation);&lt;BR&gt;}&lt;BR&gt;function bar(afterbar)&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; afterbar(123);&lt;BR&gt;}&lt;BR&gt;function blah(a, b, afterblah)&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; print(a+b, afterblah); // print also rewritten in CPS&lt;BR&gt;}&lt;/P&gt;
&lt;P&gt;foo(1, terminate);&lt;/P&gt;&lt;/FONT&gt;
&lt;P&gt;&lt;FONT color=#000080&gt;foocontinuation&lt;/FONT&gt; is a &lt;a href="http://blogs.msdn.com/ericlippert/archive/2003/09/17/53028.aspx"&gt;closure&lt;/A&gt;, so it keeps track of what the values of &lt;FONT color=#000080&gt;x&lt;/FONT&gt; and &lt;FONT color=#000080&gt;afterfoo&lt;/FONT&gt; were when it was passed to &lt;FONT color=#000080&gt;bar&lt;/FONT&gt;.&amp;nbsp; So we're all set here.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;The global code passes 1, &lt;FONT color=#000080&gt;terminate&lt;/FONT&gt; to &lt;FONT color=#000080&gt;foo&lt;/FONT&gt;&amp;nbsp; &lt;BR&gt;&lt;FONT color=#000080&gt;foo&lt;/FONT&gt; passes &lt;FONT color=#000080&gt;foocontinuation&lt;/FONT&gt; to &lt;FONT color=#000080&gt;bar&lt;/FONT&gt;&lt;BR&gt;&lt;FONT color=#000080&gt;bar&lt;/FONT&gt; passes 123 to &lt;FONT color=#000080&gt;foocontinuation&lt;/FONT&gt;&amp;nbsp; &lt;BR&gt;&lt;FONT color=#000080&gt;foocontinuation&lt;/FONT&gt; passes 1, 123, &lt;FONT color=#000080&gt;terminate&lt;/FONT&gt; to &lt;FONT color=#000080&gt;blah&lt;/FONT&gt;&lt;BR&gt;&lt;FONT color=#000080&gt;blah&lt;/FONT&gt; adds together its arguments and passes 124, &lt;FONT color=#000080&gt;terminate&lt;/FONT&gt; to &lt;FONT color=#000080&gt;print&lt;/FONT&gt;&lt;BR&gt;&lt;FONT color=#000080&gt;print&lt;/FONT&gt; presumably prints out 124 and calls &lt;FONT color=#000080&gt;terminate&lt;/FONT&gt;, and we're done&lt;/P&gt;
&lt;P&gt;Not once did any function return in there, and we did everything in the right order.&lt;/P&gt;
&lt;P&gt;Now of course in reality, JScript does not know that none of these functions are going to return. Nor is JScript smart enough to realize that even if they did return, none of these functions now does anything after the subroutine call, and therefore keeping track of the old frames on the stack is unnecessary, since they're never going to be read from again. If it did, we could totally write programs in this style and never worry about running out of stack space, but unfortunately, it doesn't.&lt;/P&gt;
&lt;P&gt;But just as we helped JScript along by writing our own explicit frame stack, we can help it along by writing our own CPS system. Stay tuned!&lt;/P&gt;
&lt;P&gt;(Eric is on vacation; this message was prerecorded.)&lt;/P&gt;&lt;/FONT&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=442706" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/ericlippert/archive/tags/JScript/default.aspx">JScript</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Scripting/default.aspx">Scripting</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Rarefied+Heights/default.aspx">Rarefied Heights</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Recursion/default.aspx">Recursion</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Continuation+Passing+Style/default.aspx">Continuation Passing Style</category></item><item><title>Recursion, Part Three: Building a Dispatch Engine</title><link>http://blogs.msdn.com/ericlippert/archive/2005/08/04/recursion-part-three-building-a-dispatch-engine.aspx</link><pubDate>Thu, 04 Aug 2005 13:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:442691</guid><dc:creator>Eric Lippert</dc:creator><slash:comments>0</slash:comments><comments>http://blogs.msdn.com/ericlippert/comments/442691.aspx</comments><wfw:commentRss>http://blogs.msdn.com/ericlippert/commentrss.aspx?PostID=442691</wfw:commentRss><description>&lt;FONT face="lucida sans unicode" color=purple size=2&gt;
&lt;P&gt;There's a particular technique that I like to use to solve problems -- it doesn't always work, but when it does, it can produce programs of surprising elegance and power. The technique is this: if you have a specific problem to solve, solve a more general problem, and then your problem is just a special case. It's like that joke someone mentioned during my series on high-dimensional arithmetic -- it's easy to imagine a 9-dimensional space, just imagine an n-dimensional space and set n=9.&lt;/P&gt;
&lt;P&gt;That sounds like more work, doesn't it?&amp;nbsp; Often it is, but paradoxically, sometimes it's less work.&lt;/P&gt;
&lt;P&gt;Our solution last time for de-recursivizing a three-line recursive algorithm was an unreadable mess in part because the explicit stack logic was all mixed up with the bits of the function actually doing work. Rather than messing around trying to implement JScript's call logic in JScript itself, complete with frames and return values and activation objects, let's solve a more general problem. Let's build a little dispatch engine, and build some functions that use that dispatch engine to solve problems. Solving tree depth will then just be a special case.&lt;/P&gt;
&lt;P&gt;Our dispatch engine will have two stacks: the functions-I-still-need-to-call stack, and the values-to-pass-to-them stack.&amp;nbsp; But to keep it simple, the functions themselves will be responsible for taking the values on and off the value stack. With those design characteristics, our "dispatch engine" becomes very, very simple.&amp;nbsp; It just pops a function off the function stack and calls it. When there are no more functions on the stack, we're done.&lt;/P&gt;&lt;FONT face="lucida console" color=navy&gt;
&lt;P&gt;while(functionstack.length != 0)&lt;BR&gt;&amp;nbsp; functionstack.pop()();&lt;/FONT&gt;&lt;/P&gt;
&lt;P&gt;We'll need to do a little stack magic to make it all work, but we can do it. We'll call the functions D, R and M:&lt;/P&gt;
&lt;P&gt;D:&lt;BR&gt;&lt;STRONG&gt;action&lt;/STRONG&gt;: either computes the depth of a null&amp;nbsp;node or pushes a program that "recursively" computes the depth of a node.&lt;BR&gt;&lt;STRONG&gt;value stack precondition&lt;/STRONG&gt;: value stack top contains tree node&lt;BR&gt;&lt;STRONG&gt;value stack postcondition&lt;/STRONG&gt;: if tree node on stack is null, replace it with zero. Otherwise push right and left trees&lt;BR&gt;&lt;STRONG&gt;function stack postcondition&lt;/STRONG&gt;: if tree node is not null, push MDRD onto function stack&lt;/P&gt;
&lt;P&gt;R: &lt;BR&gt;&lt;STRONG&gt;action&lt;/STRONG&gt;: reorganizes the value stack so that the depth of the right tree can be determined&lt;BR&gt;&lt;STRONG&gt;value stack precondition&lt;/STRONG&gt;: top of stack is left tree depth, followed by tree node&lt;BR&gt;&lt;STRONG&gt;value stack postcondition&lt;/STRONG&gt;: top of stack is tree node, followed by left tree depth&lt;BR&gt;&lt;BR&gt;M:&lt;BR&gt;&lt;STRONG&gt;action&lt;/STRONG&gt;: takes the max + 1 of two numbers&lt;BR&gt;&lt;STRONG&gt;value stack precondition&lt;/STRONG&gt;: two numbers on top of stack&lt;BR&gt;&lt;STRONG&gt;value stack postcondition&lt;/STRONG&gt;: one number on top of stack&lt;/P&gt;
&lt;P&gt;Does that make sense?&amp;nbsp; Let's think about how that would play out for a tree with root B, left child A, right child C.&amp;nbsp; I'll use X to represent an empty (null) tree. We put D on the function stack and B on the value stack and start the engine:&lt;/P&gt;&lt;FONT face="lucida console" color=navy&gt;
&lt;P&gt;functions values&amp;nbsp;notes&lt;BR&gt;D&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; B&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;B is not null, so we push its children on the value stack and MDRD on the function stack&lt;BR&gt;MDRD&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; CA&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Again, D is the top of the function stack, so we do it again, this time on A&lt;BR&gt;MDRMDRD&amp;nbsp;&amp;nbsp; CXX&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Now D is at the top of the function stack and we have a null. Replace it with zero.&lt;BR&gt;MDRMDR &amp;nbsp;&amp;nbsp; CX0&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Swap the top two &lt;BR&gt;MDRMD&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; C0X&amp;nbsp;&amp;nbsp;&amp;nbsp; Replace null with zero&lt;BR&gt;MDRM&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; C00&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;M pops both numbers, finds the larger, adds one, pushes it&lt;BR&gt;MDR&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; C1&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Swap the top two, replace the tree with its right child&lt;BR&gt;MD&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 1C&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;and so on...&lt;BR&gt;MMDRD&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 1XX&lt;BR&gt;MMDR&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 1X0&lt;BR&gt;MMD&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 10X&lt;BR&gt;MM&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 100&lt;BR&gt;M&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 11&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 2&lt;/P&gt;&lt;/FONT&gt;
&lt;P&gt;And if we've done it right, when we're done the value stack contains the depth of the tree that we started with, and the function stack is empty.&lt;/P&gt;
&lt;P&gt;Looks promising. Let's write the code.&lt;/P&gt;&lt;FONT face="lucida console" color=navy&gt;
&lt;P&gt;var functionstack = new Array();&lt;BR&gt;var valuestack = new Array();&lt;/P&gt;
&lt;P&gt;function treeDepth()&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; var curtree = valuestack.pop();&lt;BR&gt;&amp;nbsp; if (curtree == null)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; valuestack.push(0);&lt;BR&gt;&amp;nbsp; else&lt;BR&gt;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; functionstack.push(max);&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; functionstack.push(treeDepth);&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; functionstack.push(reorder);&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; functionstack.push(treeDepth);&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; valuestack.push(curtree.right);&amp;nbsp;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; valuestack.push(curtree.left);&lt;BR&gt;&amp;nbsp; }&lt;BR&gt;}&lt;/P&gt;
&lt;P&gt;function reorder()&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; var leftdepth = valuestack.pop();&lt;BR&gt;&amp;nbsp; var righttree = valuestack.pop();&lt;BR&gt;&amp;nbsp; valuestack.push(leftdepth);&lt;BR&gt;&amp;nbsp; valuestack.push(righttree);&lt;BR&gt;}&lt;/P&gt;
&lt;P&gt;function max()&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; valuestack.push(1 + Math.max(valuestack.pop(), valuestack.pop()));&lt;BR&gt;}&lt;/P&gt;
&lt;P&gt;functionstack.push(treeDepth);&lt;BR&gt;valuestack.push(mytree);&lt;BR&gt;while(functionstack.length != 0)&lt;BR&gt;&amp;nbsp; functionstack.pop()();&lt;BR&gt;print(valuestack.pop());&lt;/P&gt;&lt;/FONT&gt;
&lt;P&gt;Each function is a lot cleaner now that the execution management has been pushed to an external engine. But we've paid a pretty high price in that it's now non-obvious that this program &lt;EM&gt;actually works&lt;/EM&gt; on all trees. I mean, it sure looks like it works, but we haven't proven it. But at least its not directly recursive, so we're pretty sure that we don't have to worry about running out of system stack.&lt;/P&gt;
&lt;P&gt;This time we attacked the problem of eliminating recursion by getting rid of the notion of explicit frames on the stack. Next time we'll take a very different tack and try to eliminate stacks altogether.&lt;BR&gt;&lt;/P&gt;
&lt;P&gt;(Eric is on vacation; this message was pre-recorded.)&lt;/P&gt;&lt;/FONT&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=442691" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/ericlippert/archive/tags/JScript/default.aspx">JScript</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Scripting/default.aspx">Scripting</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Rarefied+Heights/default.aspx">Rarefied Heights</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Recursion/default.aspx">Recursion</category></item><item><title>Recursion, Part Two: Unrolling a Recursive Function With an Explicit Stack</title><link>http://blogs.msdn.com/ericlippert/archive/2005/08/01/recursion-part-two-unrolling-a-recursive-function-with-an-explicit-stack.aspx</link><pubDate>Mon, 01 Aug 2005 13:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:442606</guid><dc:creator>Eric Lippert</dc:creator><slash:comments>3</slash:comments><comments>http://blogs.msdn.com/ericlippert/comments/442606.aspx</comments><wfw:commentRss>http://blogs.msdn.com/ericlippert/commentrss.aspx?PostID=442606</wfw:commentRss><description>&lt;FONT face="lucida sans unicode" color=purple size=2&gt;
&lt;P&gt;That recursive solution is pretty cool, to be sure.&amp;nbsp;But there&amp;nbsp;is one big problem&amp;nbsp;with it.&amp;nbsp; Consider this Jscript program that puts a few more nodes into our tree from last time:&lt;/P&gt;&lt;FONT face="lucida console" color=navy&gt;
&lt;P&gt;function tree(value, left, right)&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; this.value = value;&lt;BR&gt;&amp;nbsp;&amp;nbsp;this.left = left;&lt;BR&gt;&amp;nbsp;&amp;nbsp;this.right = right;&lt;BR&gt;}&lt;BR&gt;for (var i = 1 ; i &amp;lt; 1500 ; ++i)&lt;BR&gt;&amp;nbsp;&amp;nbsp;mytree = new tree(i, mytree, null)&lt;BR&gt;print(treeDepth(mytree));&lt;/P&gt;&lt;/FONT&gt;
&lt;P&gt;This is not a very well-behaved binary tree – it’s actually mostly a linked list, hardly a tree at all.&amp;nbsp; Recursing down 1500 branches to get to the bottom blows the stack.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;Each time you enter a JScript function, that pushes a new JScript "activation" frame on the JScript stack. But the JScript stack is actually allocated off of the system heap, so this isn't&amp;nbsp;the problem. Unfortunately,&amp;nbsp;doing so&amp;nbsp;also pushes a new copy of the interpreter on the &lt;STRONG&gt;system&lt;/STRONG&gt; stack, which consumes a few hundred bytes of stack space.&amp;nbsp; Since by default the system stack only has a million bytes available, this quickly consumes the entire system stack. &lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;Recursive functions are sometimes the most elegant solution, but not always the most practical.&lt;/STRONG&gt;&lt;/P&gt;
&lt;P&gt;How are we going to solve this problem?&lt;/P&gt;
&lt;P&gt;One way to do it is to not get into the situation in the first place. There are various algorithms for guarateeing that when you construct a binary tree that it is a "balanced" binary tree. That is, there are no long, deep paths. A &lt;EM&gt;perfectly&lt;/EM&gt; balanced binary tree with 1500 nodes in it is guaranteed to require no more than 11 recursive steps, and doubling the number of nodes only adds on one more step.&amp;nbsp; A perfect&amp;nbsp;tree with a million nodes requires no more than 20 recursive steps, so odds are pretty good that you'll never blow the stack if you know you have a balanced tree.&amp;nbsp; There are algorithms such as the famous red-black algorithm that guarantee that a binary tree is always within a factor of two of being perfectly balanced, so maybe a million-node tree is 40 deep, which seems doable.&lt;/P&gt;
&lt;P&gt;Another approach is to keep track of how deep you are on the stack and bail out:&lt;/P&gt;&lt;FONT face="lucida console" color=navy&gt;
&lt;P&gt;function treeDepth(curtree, stackdepth)&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; if (curtree == null)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return 0;&lt;BR&gt;&amp;nbsp; if (stackdepth &amp;gt; 1000)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; throw&amp;nbsp;"tree is&amp;nbsp;too deep, bailing out!";&lt;BR&gt;&amp;nbsp; return 1 + Math.max(&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; treeDepth(curtree.left, stackdepth + 1), &lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; treeDepth(curtree.right, stackdepth + 1));&lt;BR&gt;}&lt;/FONT&gt;&lt;/P&gt;
&lt;P&gt;But that's pretty hacked up. What if you're wrong about how much stack you have left?&amp;nbsp;Maybe 1000 is too deep. What if you can't guarantee that the tree is balanced?&amp;nbsp; What if you want to have an algorithm that works for &lt;EM&gt;any&lt;/EM&gt; binary tree without danger of blowing the stack or getting a goofy exception?&lt;/P&gt;
&lt;P&gt;Some languages, such as Scheme, have what’s called “tail recursion”, where they detect when they can optimize away pushing another frame on the stack, and therefore do not have this problem. But JScript does not have this optimization, and even if it did, this tree algorithm is a poor candidate for tail recursion. Tail recursion works really well when the recursive step is last, but this algorithm has &lt;EM&gt;two&lt;/EM&gt; recursive steps, so one of them is going to be not last, obviously. (Though as we'll see in a few episodes, there are things we can do about that.)&lt;/P&gt;
&lt;P&gt;Hmm. &lt;/P&gt;
&lt;P&gt;I just said that the JScript stack is actually allocated off of the system heap -- the interpreter simulates a stack for the script engines rather than re-using the system stack. We can do the same thing with our recursive program: &lt;STRONG&gt;make the stack explicit rather than implicit.&lt;/STRONG&gt;&lt;/P&gt;
&lt;P&gt;That's going to be complicated. Think about what has to happen every time you call a function in JScript. Somehow the interpreter has to remember a whole bunch of things, like:&lt;/P&gt;
&lt;UL&gt;
&lt;LI&gt;values of local variables in the current activation frame -- variables and arguments in the callee's frame&amp;nbsp;must not change the variables in the caller's frame. 
&lt;LI&gt;where to pick up execution when the callee returns 
&lt;LI&gt;what to do with the return value of the callee 
&lt;LI&gt;values of "anonymous locals" -- for example, when you have &lt;FONT color=#000080&gt;x = 1 + 1 + foo(); &lt;/FONT&gt;somehow the engine has to remember that there's a 2 sitting there in temporary storage waiting to be added when foo returns.&lt;/LI&gt;&lt;/UL&gt;
&lt;P&gt;Let's take our recursive depth algorithm and refactor it a little bit so that the temporary variables are spelled out and each recursion happens on its own line:&lt;/P&gt;&lt;FONT face="lucida console" color=navy&gt;
&lt;P&gt;function treeDepth(curtree)&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; if (curtree == null)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return 0;&lt;BR&gt;&amp;nbsp; var leftdepth = treeDepth(curtree.left);&lt;BR&gt;&amp;nbsp; var rightdepth = treeDepth(curtree.right);&lt;BR&gt;&amp;nbsp; return 1 + Math.max(leftdepth, rightdepth);&lt;BR&gt;}&lt;/P&gt;&lt;/FONT&gt;
&lt;P&gt;For each recursive step we'll need a frame that keeps track of what the three local variables are.&amp;nbsp; Before each recursion we need to remember where we were, so that when we start executing, we know whether to pick up on the "&lt;FONT color=#000080&gt;var leftdepth&lt;/FONT&gt;..." line or "&lt;FONT color=#000080&gt;var rightdepth&lt;/FONT&gt;..." line or the "&lt;FONT color=#000080&gt;return 1 +&lt;/FONT&gt; ..." line.&amp;nbsp; We'll remember that by keeping track of whether &lt;FONT color=#000080&gt;leftdepth&lt;/FONT&gt; and/or &lt;FONT color=#000080&gt;rightdepth&lt;/FONT&gt; are initialized on the frame.&amp;nbsp; When we complete a calculation we'll pop off the current frame and fill in the "calling" frame's variables with the appropriate "return value" so that our execution loop knows where to go next.&lt;/P&gt;&lt;FONT face="lucida console" color=navy&gt;
&lt;P&gt;function treeDepth(curtree)&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; if (curtree == null)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return 0;&lt;BR&gt;&amp;nbsp; var frame = { &lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; curtree:&amp;nbsp;&amp;nbsp;&amp;nbsp; curtree, &lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; leftdepth:&amp;nbsp; null, &lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; rightdepth: null};&lt;BR&gt;&amp;nbsp; var stack = new Array();&lt;BR&gt;&amp;nbsp; stack.push(frame);&lt;BR&gt;&amp;nbsp; while(true)&lt;BR&gt;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; var curframe = stack[stack.length-1];&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (curframe.curtree == null)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; stack.pop();&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; curframe = stack[stack.length-1];&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (curframe.leftdepth == null)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; curframe.leftdepth = 0;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; else&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; curframe.rightdepth = 0;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&amp;nbsp; &lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (curframe.leftdepth == null)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; curframe = {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; curtree:&amp;nbsp;&amp;nbsp; &amp;nbsp;curframe.curtree.left, &lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; leftdepth: &amp;nbsp;null, &lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;rightdepth: null};&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; stack.push(curframe);&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; else if (curframe.rightdepth == null)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; curframe = {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; curtree:&amp;nbsp;&amp;nbsp;&amp;nbsp; curframe.curtree.right, &lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; leftdepth:&amp;nbsp; null, &lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; rightdepth: null};&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; stack.push(curframe);&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; else&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; var depth = 1 + Math.max(curframe.leftdepth, curframe.rightdepth);&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; stack.pop();&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (stack.length == 0)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return depth;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; curframe = stack[stack.length-1];&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (curframe.leftdepth == null)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; curframe.leftdepth = depth;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; else&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; curframe.rightdepth = depth;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;BR&gt;&amp;nbsp; }&lt;BR&gt;}&lt;/P&gt;&lt;/FONT&gt;
&lt;P&gt;Since there is no recursion here at all now, there's no danger of running out of stack. But good heavens, that's &lt;STRONG&gt;a freakin' mess compared to the three-line recursive solution. &lt;/STRONG&gt;&lt;/P&gt;
&lt;P&gt;This is probably more trouble than it's worth. Next time we'll look at another explicit-stack based approach that is a whole lot cleaner than this dog's breakfast.&lt;/P&gt;
&lt;P&gt;(Eric is on vacation; this message was prerecorded.)&lt;/P&gt;&lt;/FONT&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=442606" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/ericlippert/archive/tags/JScript/default.aspx">JScript</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Scripting/default.aspx">Scripting</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Rarefied+Heights/default.aspx">Rarefied Heights</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Recursion/default.aspx">Recursion</category></item><item><title>Recursion, Part One: Recursive Data Structures and Functions</title><link>http://blogs.msdn.com/ericlippert/archive/2005/07/27/recursion-part-one-recursive-data-structures-and-functions.aspx</link><pubDate>Wed, 27 Jul 2005 13:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:442590</guid><dc:creator>Eric Lippert</dc:creator><slash:comments>8</slash:comments><comments>http://blogs.msdn.com/ericlippert/comments/442590.aspx</comments><wfw:commentRss>http://blogs.msdn.com/ericlippert/commentrss.aspx?PostID=442590</wfw:commentRss><description>&lt;FONT face="lucida sans unicode" color=purple size=2&gt;
&lt;P&gt;The first thing to wrap your head around is recursively defined data structures. Let's start with something simple.&amp;nbsp; Think about the abstract idea of “list”.&amp;nbsp; Most people think of a “list” as an ordered collection of “items”, one after the other, with a beginning and an end.&amp;nbsp; That’s a very non-recursive way to think about a list, but it’s the usual way of doing so.&lt;/P&gt;
&lt;P&gt;The recursive way to think about a list emphasizes the similarity of a fragment of the list to the whole list.&amp;nbsp; We might recursively define a list as either&lt;/P&gt;
&lt;UL&gt;
&lt;LI&gt;the empty list with zero items on it, or 
&lt;LI&gt;an item followed by a list.&lt;/LI&gt;&lt;/UL&gt;
&lt;P&gt;This certainly appears to be a circular definition, but it’s really not.&amp;nbsp;It’s more sort of a “spiral” definition. You start off with something extremely simple; it’s harder to get more simple than a list with no elements. Then you provide a rule for turning something simple into something &lt;EM&gt;very slightly&lt;/EM&gt; more complicated.&amp;nbsp;The recursive part of the definition means that you can take a list of any size, starting with zero, and construct a list one bigger than it, by sticking an item on to the beginning. It’s not a truly circular definition because there is always a “base case”.&amp;nbsp;There is always some point from which you begin, and upon which you can build. &lt;/P&gt;
&lt;P&gt;But the true power of the recursive definition comes from going the other way: if you have something that meets the definition, then there is usually a way to move back towards the base case, getting simpler and simpler as you go.&lt;/P&gt;
&lt;P&gt;That’s what recursive programming is all about.&amp;nbsp;All recursive functions follow the same basic pattern:&lt;/P&gt;
&lt;UL&gt;
&lt;LI&gt;Am I in the base case? If so, return the easy solution. 
&lt;LI&gt;Otherwise, figure out some way to make the problem closer to the base case and solve that problem. &lt;/LI&gt;&lt;/UL&gt;
&lt;P&gt;That’s why you can get away with calling a function from itself – because you know that the recursion will eventually bottom out when you’ve found the base case. &lt;/P&gt;
&lt;P&gt;Now, for list processing, a recursive solution is usually overkill. The iterative solution of “run down the list in a loop” is usually good enough. But many other problems are naturally solved by other recursively defined data structures.&amp;nbsp;For example, consider the highly useful binary tree.&amp;nbsp;A binary tree is either:&lt;/P&gt;
&lt;UL&gt;
&lt;LI&gt;an empty tree, or 
&lt;LI&gt;a value associated with two binary search trees, called the left and right child trees &lt;/LI&gt;&lt;/UL&gt;
&lt;P&gt;For example, this is a binary tree:&lt;/P&gt;&lt;FONT face="lucida console"&gt;
&lt;P&gt;&lt;FONT color=#000080&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; E&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; / \&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; /&amp;nbsp;&amp;nbsp; \&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; B&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; G&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; / \&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; \&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; A&amp;nbsp;&amp;nbsp; C&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; H&lt;/FONT&gt;&amp;nbsp; &lt;/P&gt;&lt;/FONT&gt;
&lt;P&gt;The children of A, C and H, and the left child of G, are empty trees. (Sharp eyed readers will have noted that this particular example is a binary &lt;EM&gt;search&lt;/EM&gt; tree, because every parent is between its children. We might discuss properties of search trees later.)&lt;/P&gt;
&lt;P&gt;Pretty picture, but how are we going to represent this thing in code?&amp;nbsp; Suppose you’ve got a binary tree: in J&lt;I&gt;&lt;/I&gt;Script 
&lt;P&gt;&lt;/P&gt;&lt;FONT face="lucida console" color=navy&gt;
&lt;P&gt;var mytree =&lt;BR&gt;{ &lt;BR&gt;&amp;nbsp; left:&lt;BR&gt;&amp;nbsp; { &lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; left: &lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; left: null,&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; value : "A", &lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; right: null&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; },&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; value: "B",&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; right: &lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; left: null,&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; value: "C",&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; right: null&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;BR&gt;&amp;nbsp; },&lt;BR&gt;&amp;nbsp; value:"E",&lt;BR&gt;&amp;nbsp; right :&lt;BR&gt;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; left: null,&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; value: "G",&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; right:&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; left: null, &lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; value: "H",&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; right: null&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;BR&gt;&amp;nbsp; }&lt;BR&gt;};&lt;/P&gt;&lt;/FONT&gt;
&lt;P&gt;Now we can use this recursive definition to write recursive functions that answer questions about this tree.&amp;nbsp; For the rest of this series I'll use as my motivating example one of the simplest questions you can ask about a binary tree: &lt;STRONG&gt;what is the deepest you can go in a given tree?&lt;/STRONG&gt;&amp;nbsp; &lt;/P&gt;
&lt;P&gt;We have a recursive definition, so come up with a recursive solution.&lt;/P&gt;
&lt;P&gt;What’s the base case?&amp;nbsp; An empty tree.&amp;nbsp; Clearly the deepest you can go in an empty tree is zero steps.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;What’s the recursive case? If you haven’t got an empty tree then you’ve got a value with two children.&amp;nbsp; Each child is itself a tree. The deepest you can go from this point is one (counting yourself), plus the depth of the deepest child. And we've got a function that gives you the depth of a tree, so let's call it on each child:&lt;/P&gt;&lt;FONT face="lucida console" color=navy&gt;
&lt;P&gt;function treeDepth(curtree) {&lt;BR&gt;&amp;nbsp; if (curtree == null)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return 0;&lt;BR&gt;&amp;nbsp;&amp;nbsp;return 1 + Math.max(treeDepth(curtree.left), treeDepth(curtree.right));&lt;BR&gt;}&lt;/P&gt;&lt;/FONT&gt;
&lt;P&gt;It's magically delicious.&amp;nbsp; It's like having n dominoes lined up.&amp;nbsp; If you knock over the last one, and you know that every domino knocked over also knocks over the previous, then you know that they'll all go down eventually.&lt;/P&gt;
&lt;P&gt;Formally, we could use complete induction to show that this works for all trees.&amp;nbsp; We know that it works for trees of height zero. As an inductive hypothesis, assume that it works for trees of height &amp;lt;= k.&amp;nbsp; Since a tree of height k+1 has one subtree of height k and another of height &amp;lt;=k, by hypothesis the recursion correctly calculates their heights and computes the max as k+1, and we're done. (Of course, how do we know that complete induction works? That question takes us into Peano's Axioms and other topics in the foundations of mathematical logic.&amp;nbsp;Perhaps another time...)&lt;/P&gt;
&lt;P&gt;Next time: Trouble in paradise: the out-of-stack error rears its ugly head.&lt;/P&gt;&lt;/FONT&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=442590" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/ericlippert/archive/tags/JScript/default.aspx">JScript</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Scripting/default.aspx">Scripting</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Rarefied+Heights/default.aspx">Rarefied Heights</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Recursion/default.aspx">Recursion</category></item><item><title>Recursion, Part Zero</title><link>http://blogs.msdn.com/ericlippert/archive/2005/07/25/recursion-part-zero.aspx</link><pubDate>Mon, 25 Jul 2005 13:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:442568</guid><dc:creator>Eric Lippert</dc:creator><slash:comments>6</slash:comments><comments>http://blogs.msdn.com/ericlippert/comments/442568.aspx</comments><wfw:commentRss>http://blogs.msdn.com/ericlippert/commentrss.aspx?PostID=442568</wfw:commentRss><description>&lt;FONT face="lucida sans unicode" color=purple size=2&gt;
&lt;P&gt;I’ve mentioned recursive programming techniques several times over the years in this blog (&lt;a href="http://blogs.msdn.com/ericlippert/archive/2004/03/16/90851.aspx"&gt;Topological Sort&lt;/A&gt;, &lt;a href="http://blogs.msdn.com/ericlippert/archive/2004/05/19/135392.aspx"&gt;How Not To Teach Recursion&lt;/A&gt;, &lt;a href="http://blogs.msdn.com/ericlippert/archive/2004/05/20/136327.aspx"&gt;Fibonacci Challenge&lt;/A&gt;, &lt;a href="http://blogs.msdn.com/ericlippert/archive/2004/07/21/189974.aspx"&gt;Recursion and Dynamic Programming&lt;/A&gt;, &lt;a href="http://blogs.msdn.com/ericlippert/archive/2004/09/27/234826.aspx"&gt;Sometimes Breadth Is Better Than Depth&lt;/A&gt;, and probably a few others).&amp;nbsp; A lot of developers, particularly those without a formal education in computer science, are still pretty vague on this weird idea of functions that call themselves.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;If you’re interviewing at Microsoft for a development position you can expect that at least one person will ask you a whiteboarding question that involves some kind of recursive problem. This isn’t because we’re a bunch of architecture astronauts or theory wonks, it’s because &lt;STRONG&gt;if you want to be a dev here, recursion is simply one of the tools that you have to have in your toolbox.&lt;/STRONG&gt; We use recursive data structures and algorithms quite a bit, and people are expected to know how they work.&lt;/P&gt;
&lt;P&gt;I’d therefore like to take this opportunity to do a series on some of the theory and practice of writing recursive and recursive-like functions. I want to show that (a) they're not as mysterious as they seem, &lt;STRONG&gt;but&lt;/STRONG&gt; (b) that they are potentially dangerous, and (c) there are &lt;STRONG&gt;some absolutely crazy-but-fun&lt;/STRONG&gt; techniques for turning a recursive program into a nonrecursive program.&amp;nbsp;Hopefully by the time we're done here your head will hurt, but hey, &lt;STRONG&gt;it builds character&lt;/STRONG&gt;.&lt;/P&gt;
&lt;P&gt;I'm going to get as much of this done as possible and queued up, because I'm going to go dark shortly. I'm getting married in less than two weeks!&amp;nbsp;Between getting ready for that and finishing up stuff at work, I'm going to be swamped.&amp;nbsp;(And you'd better believe I'm not blogging about recursive programming techniques from my honeymoon.)&amp;nbsp; I'll be back in late August and things should pick up then.&lt;/P&gt;&lt;/FONT&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=442568" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/ericlippert/archive/tags/JScript/default.aspx">JScript</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Scripting/default.aspx">Scripting</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Rarefied+Heights/default.aspx">Rarefied Heights</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Recursion/default.aspx">Recursion</category></item></channel></rss>