Recursive--cps (iii)

Source: Internet
Author: User

JScript is not a natural support CPS, but a distribution engine can be written to work in CPS style. Generally there is only one active continuation, so you can define the rule: JScript CPS functions allow return, but the last thing they do must be the distribution engine that will continuation tell us.

To make things simple, we have one parameter for each CPS-style function, and of course, it can be an object that contains multiple fields.

Let's review the previous CPS treedepth program and replace all the continuation calls with one such call: This call tells the runtime engine what to do next continuation. The function can then return normally and have the runtime engine call continuation.

function   Treedepth (args) { if  (args.curtree =  ) cont (args.afterdepth,  0 else   { function   Afterleft (leftdepth) { function   Afterright (rightdepth) {cont (args.afterdepth, 
       1+math.max (Leftdepth, rightdepth)); } cont (treedepth, {curtree:args.curtree.right, afterdepth:afterright}); } cont (treedepth, {curtree:args.curtree.left, afterdepth:afterleft}); }}

distribution engine is

 var  continuation = null  ;  function   Cont (NEWFUNC, Newargs) {continuation  = {func: Newfunc, Args:newargs};}  function   run () { while  (continuation! = null   var  curfunc = Continuation.func;         var  curargs = Continuation.args;        Continuation  = null  ;    Curfunc (Curargs); }}

If the next step does not need to be called, it means that the program is complete. To determine the depth of a tree, we simply tell continuation what the engine needs to do next.

Cont (treedepth, {curtree:mytree, afterdepth:print}); run ();

Original: https://blogs.msdn.microsoft.com/ericlippert/2005/08/15/recursion-part-six-making-cps-work/

Recursive--cps (iii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.