waltermilner

Untitled

Sep 19th, 2014
298
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.             // convert function of a single Pair argument to a function of two arguments
  2.             // parameter f is a function of a Pair
  3.             // returns a function of two arguments
  4.             function toBiFunction(f)
  5.             {
  6.                 function temp(a, b)
  7.                 {
  8.                     p = new Pair(a, b); // turn 2 values into a Pair
  9.                     return f(p); // return teh function of that Pair
  10.                 }
  11.                 return temp;
  12.             }
  13.  
  14.             function f1(pair) // example function of a Pair
  15.             {
  16.                 // check type of argument
  17.                 if (pair.kind!=="Pair") throw "Not a pair";
  18.                 // exampel function body
  19.                 return pair.getFirst() + pair.getSecond();
  20.             }
  21.            
  22.            
  23.             function Pair(a, b) { // in effect, define a Pair class (actually function constructor)
  24.                 this.kind="Pair";
  25.                 this.firstField = a;
  26.                 this.secondField = b;
  27.                 this.getFirst = getFirst1;
  28.                 this.getSecond = getSecond1;
  29.  
  30.                 function getFirst1()
  31.                 {
  32.                     return this.firstField;
  33.                 }
  34.                 function getSecond1()
  35.                 {
  36.                     return this.secondField;
  37.                 }
  38.  
  39.  
  40.             }
  41.  
  42.  
  43.             p1 = new Pair(1, 2); // make a Pair
  44.             console.log(p1.getFirst()); // 1
  45.             funcPair=f1; // make an example function object of a Pair
  46.             // console.log(funcPair(7)); this throws an exception - cannot apply funcPair to singleton
  47.             console.log(funcPair(p1)); // 3 - check funcPair working
  48.             funcBi = toBiFunction(funcPair); // create a biFunction
  49.             console.log(funcBi(7,8)); // 15
Advertisement
Add Comment
Please, Sign In to add comment