Programming

Continuation-passing style (CPS)

steloflute 2012. 9. 17. 23:30

http://en.wikipedia.org/wiki/Continuation-passing_style

 

In functional programming, continuation-passing style (CPS) is a style of programming in which control is passed explicitly in the form of a continuation. Gerald Jay Sussman and Guy L. Steele, Jr. coined the phrase in AI Memo 349 (1975), which sets out the first version of the Scheme programming language.[1][2]

A function written in continuation-passing style takes as an extra argument: an explicit "continuation" i.e. a function of one argument. When the CPS function has computed its result value, it "returns" it by calling the continuation function with this value as the argument. That means that when invoking a CPS function, the calling function is required to supply a procedure to be invoked with the subroutine's "return" value. Expressing code in this form makes a number of things explicit which are implicit in direct style. These include: procedure returns, which become apparent as calls to a continuation; intermediate values, which are all given names; order of argument evaluation, which is made explicit; and tail calls, which is simply calling a procedure with the same continuation, unmodified, that was passed to the caller.

Programs can be automatically transformed from direct style to CPS. Functional and logic compilers often use CPS as an intermediate representation where a compiler for an imperative or procedural programming language would use static single assignment form (SSA); however, SSA and CPS are equivalent. [3] SSA is formally equivalent to a well-behaved subset of CPS (excluding non-local control flow, which does not occur when CPS is used as intermediate representation). Functional compilers can also use Administrative Normal Form (ANF) instead of or in conjunction with CPS. CPS is used more frequently by compilers than by programmers as a local or global style.

 

 


 

오빤 continuation-passing style

 

예제:

 

<script>
function readURL(url,continuation) { // CPS(continuation-passing style) !!
  var r=new XMLHttpRequest();
  var result;
  r.open("GET", url, true);
  r.onreadystatechange=function() {
    if (r.readyState==4) {
      continuation(r.responseText);
    }
  }
  r.send();
}

function stringSum(s) {
  var sum=0;
  var base="A".charCodeAt(0);
  for(var i=0;i<s.length;i++) sum+=s.charCodeAt(i)-base+1;
  return sum;
}

function k(text) {
  var sorted=text.replace(/"/g,"").split(","); 
  sorted.sort();
 
  var sum=0;
  for(var i=0;i<sorted.length;i++) {
    sum+=(i+1)*stringSum(sorted[i]);
  }
  alert(sum); 
}

var url="http://projecteuler.net/project/names.txt";
readURL(url,k);
</script>

 

'Programming' 카테고리의 다른 글

More: Systems Programming with Racket  (0) 2012.09.20
OCaml Language Sucks  (0) 2012.09.18
Semicolons in JavaScript are optional  (0) 2012.09.15
(Clojure) Fibonacci Numbers  (0) 2012.09.14
Using the XML HTTP Request object  (0) 2012.09.14