Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Thursday, April 20, 2017

ES6 Structuring and Destructuring

JavaScript ES6 contains a great new feature called  "Destructuring Assignment". It is great because among other things it allows you to do things like:

  [a, b] = [b, a];

In other words it allows you to swap the values of two variables without the help of any extra temporary variable!

More typically and usefully Destructuring Assignment can be used to de-struct an object saving values of its chosen properties into individual variables:

  var {a, b} = {a: 1, b: 2}
  // a -> 1, b -> 2


Another great ES6 feature is called "Shorthand property name". That allows you to create objects out of variables so that the  name of the variable  becomes the property-key and  value of the variable becomes the value (of the property). Like this:

  var ding = 55;
  var myOb = {ding};
  ok (myOb.ding === 55);


What may not be immediately obvious is that Destructuring Assignment and Shorthand Property Name are two sides of the same coin.  In fact I think Shorthand Property Name could and should be called simply "Structuring".

Here's an example of how structuring followed by destructuring gives us back the original (like flipping a coin):

  var ding           = {};
  var originalDing   = ding;
  var myOb           = {ding};   // STRUCTURING
  ding = "forget about it";
  ok  (ding !== originalDing);
  var {ding}         = myOb ;    // DE-STRUCTURING
  ok  (ding === originalDing);


(Note, "ok()" is my simple assertion utility-function)

LINKS:


Copyright © 2017 Panu Viljamaa. All rights reserved 

Monday, January 30, 2017

Function.prototype.map IV

The previous episodes  Function.prototype.mapFunction.prototype.map II,  Function.prototype.map III describe how to use Function.prototype.map with three argument-types: Array, Object and Function.  These extensions to Function.prototype provide support for and take advantage of Functional Programming (a.k.a "FP") in JavaScript.

It is kind of fitting that additional support for Functional Programming in JavaScript should be provided as additional methods of the JavaScript class Function. Don't you think?

This blog-post describes some additional features not previously covered and the fpmap() -library as a whole. The described features are now implemented in the "fpmp" download available from npm and GitHub, see links below.


1.  WHERE DID IT ALL COME FROM?

JavaScript standard Array.prototype.map() can be used to execute a given function once once for each of the array-elements and get back an array containing the results of each such call:

  var arr = [1,2,3];
  var a2  = arr.map (double);  // -> [2, 4, 6] 

Above "double" is a function which returns its argument times two.  Writing such code I occurred to me  to ask did I write it correctly. Or should I have instead written:

  var a3 = double.map (arr);  // ???

Luckily I had it correct no problem. I usually don't' make errors like that I congratulated myself. But then I started thinking, is there any rule-of-thumb I could use to easily remember the correct order? Is there perhaps something obviously wrong in the "wrong order" ?

I couldn't find anything obviously wrong with it. So I started thinking, why does it have to matter which way I put it? If both ways would produce the same result then I could more easily remember the simplest rule: Order doesn't matter!  If something seems good either way, we shouldn't have to think much about which way to do it.

So, went to work and implemented the function "fpmap()".  Calling it to first install Function.prototpe.map(),  it now allows me to write:

  var a3 = double.map (arr); // -> [2,4,6] 


2. AN INSIGHT AND A REVELATION

This made me feel almost like I had discovered complex numbers!  Why?  Because it seemed the possible ways of using the same operation, with different types of arguments had now greatly expanded. It was almost like jumping out of line to the plane around it! Let me explain...

With [1,2,3].map(double) the "recipient" must always be an Array, and it seems argument-type must be Function, to make it useful in general. Regardless of what type the Array elements are, you can then always put in as argument some function that accepts those array-elements as argument.

With double.map([1,2,3]) it came obvious to ask a follow-up question: What if I use something else as argument, perhaps an Object like:  "double.map({x: 1, y: 2})" ?  Is there something useful such an expression could do?  YES OF COURSE. It can iterate over the fields of the argument-object, like  {x:1, y:2}.

You could't really do such an expansion with Array.prototype.map(), unless you start adding the method "map()" to all built-in prototypes in JavaScript. That is a possibility but there's no need for that if we can make Function.prototype.map treat different types of arguments in different ways. The area of the standard library that needs to be extended this way stays smaller, and you choose and alternative method-name to use as desired. You can install it as  Function . prototype . map9() if you wish to use a more unique name

With this re-arrangement there  seems to be no reason why the argument could not be a non-Array "object". Which leads to the further question: What else?  What are the argument-types that could be passed to Function .prototype .map, to accomplish something useful, some economies of the amount of code you must write, read, and understand?  What should be  the behavior of 'map' with such possible argument-types?


3. THE USEFUL ARGUMENT-TYPES OF Function.prototype.map 

The previous blog-posts described  three argument-types so far: Array, (non-Array) Object, Function. Yes. Function.prototype.map() can also take a function as its argument, the result being the "composition" of the two functions. And you can compose a whole series, a "pipeline" if you will:  funkA . map(funkB) . map(funkC) ;

But turns out there are still a few more argument-types with different, useful  behavior. In the end, currently "fpmap" now supports the following behaviors on the following six (6) argument-types:

A) Array

Like standard Array.prototype.map() but with recipient and the argument-types switched.

B) Object

Similar to Arrays but iterates over named properties of the object rather than array indexes.

C) Function

Implements function-composition. Like:  var result =  funkA . map(funkB) . map(funkC) ;

D) RegExp

Returns a function which can be used to Iterate over all matches of a given Regular Expression for any string-argument.

E) Number

Returns a function which when given an initial argument will call the source-function with it, then call it again with the results and so on N times, where N is the number that was given as argument to fmap(N). Naturally requires that the source-function result-type is the same as its argument type. Useful for creating numeric series like Fibonacci's but also for building arbitrary recursive data-structures.

F) String

Iterates by repeatedly calling a function that incrementally consumes parts of the argument string, in effect parsing it according to the language specified by the recipient-function.



4. WHAT UNITES THEM ALL

What unites the different argument types described above is they are all used in the same manner, as argument to Function.prototype.map. So it's kind of easy to remember how to use them, if not exactly what each of them exactly does.  But that you can look up from documentation.

For detailed documentation of the above and other features of fpmap() see the unit-tests-file fpmap_test.js. Tests don't lie. The code of  the tests serve as examples of how to use fpmap() with different arguments, and what to expects as result. There's also explanatory comments. The README.md of course is a good source for documentation  as well.

Could there  still be other additional, useful argument-types besides the above? Possibly. But the above is a good start.



5. LINKS

GitHuh:   https://github.com/panulogic/fpmap
Npm:      https://www.npmjs.com/package/fpmap
Twitter:   https://twitter.com/panulogic

_____________________________________________________________
Copyright © 2017 Panu Viljamaa. All rights reserved unless otherwise noted.
Reuse of source-code in this blog-post is allowed under the terms of 
Creative Commons Attribution 4.0 International (CC BY 4.0) -license 






Monday, July 7, 2014

A Memory Leak in IE-9

I recently read David Glasser's blog-post "A surprising JavaScript memory leak found at Meteor" about a JavaScript memory-leak in Chrome. That blog-post is about a year old so I wanted to check if things might have improved since then.  I tried a simplified version of his example in IE-9 and surprisingly could reproduce the leak with even fewer statements.

Here's my modified, simplified version of David's example:
 
  var variableOfOuterScope = null;

 function runManyTimes() 

 {var previousValue    = variableOfOuterScope ;
  variableOfOuterScope 
  { bigArray:       new Array (2000000).join('*')
  , aRefToAFunction: function () {}
  };
  // previousValue = null;
  // Un-commenting the above line will fix the leak.
 };
  
 for (var i=0; i < 30 ; i++)
 { runManyTimes () ;  
 }
 // See in Windows Task Manager how the memory used  
 // by IE9 has grown significantly, to about 240 mb
 // after running the code above.


After running the code it seems the browser now uses about 240 mb instead of the 24 mb it used before running it. This is not good, memory is bursting at the seams! Why does it  happen? Why does the memory leak?  I assume it goes something like this:

When you call runManyTimes for the first time it creates a new "context" which the anonymous function inside it holds on to. This context refers to variables that exist outside the anonymous function, so that if it wanted to, it could refer to their values which were in effect at the time runManyTimes exited.  This context refers to the variable 'previousValue' whose value when runManyTimes returns first time is null. But the value of variableOfOuterScope now contains a very big Array. By the time you have called it the 2nd time,  previousValue points to that very big Array and  variableOfOuterScope then contains yet another big Array.

Each time you call runManyTimes  this chain of very big Arrays gets one bigger.  But if you un-comment the fix-line and set previousValue to null, this chain is broken, and  garbage gets collected.

One more thing is required to cause the leak to happen: The  variableOfOuterScope  must contain a REFERENCE to the anonymous function. If you just created a simple inner function without referring to it, there is no leak. Saving the anonymous function to a field in  variableOfOuterScope  means each of its values refers to the anonymous function (created on a specific call  of runManyTimes) which holds the context which refers to the previous value of  variableOfOuterScope and so on. Without that the variableOfOuterScope  would not refer to the function which holds on to the context, which refers to the previous value, which refers to the previous value and so on. But since it does, it now refers to the whole chain of the big arrays, thus consuming the memory.


Ah, but then, I ran the example on Chrome v. 31. There was no memory leak, even without setting previousValue to null!  Chrome is able to prevent the leak on its own. IE-9 is not. Maybe Chrome realizes that the anonymous function is not referring to any variables, so it need not create a "context" for it.

The moral of this story then is: Beware of memory-leaks in  JavaScript, when creating functions within functions.  It is fairly easy to detect the leaks by observing the amount of memory your browser consumes, when running your application. Don't worry too much about what causes them exactly, because results might differ on different browsers. Try to reset variables whose values you no longer need to null, and that may fix it.  Help the garbage-collector a bit!


 © 2014 Panu Viljamaa. All rights reserved

Tuesday, July 1, 2014

Partial Partial Application

"Partial Application" (PA) means applying a function to only part of its arguments, and getting back a function which can take in the remaining ones. This post is about it and what I like to call "Partial Partial Application" -  meaning the resulting function can do partial application on its own, as well.

In a previous blog-post I wrote about "currying", a related concept. I posted that currying is the process of implementing a multi-argument function as a combination of single-argument functions, and calls to them. I'll discuss the difference and relationship of Partial Application and Currying, briefly.

Partial Application is something your program can do. "Currying" is something you, or your compiler or interpreter does. So PA seems like a  more straightforward concept to implement. And yes, there is an accompanying code-file that does it for you.

Let's start by asking:  If we had an implementation of the function 'applyPartially()' or applyP() for short, how would we use it? Let's write some test-cases! Ah, this is Test-Driven-Programming, we write the test-cases first?  Well maybe something like that. But let's start by writing the function applyP(), a 'dummy' version of it first. That dummy version says something about what it should do when it grows up, what kind of arguments it expects etc.

  function applyP (baseFunction, a, b, c, d, e)
  { 
   /**  ... NOT READY   
    Return a function that is like the argument 
    'aFunction' except that its leading arguments 
    will be "fixed" to be those given by the rest 
    of MY arguments. So, my result is a function
    which will (typically) take FEWER arguments 
    than my 1st argument, 'aFunction'.  
    */
   ...
  }

The 1st argument  of applyP( ) is called  baseFunction because the result of applyP() will be  derived  from it.

Now let's write one test for it:

 function f2(x,y)
 {return x + y.
 } 
 var f2b     =  applyP (f2, 1);
 ok (f2b (2) == 3);

Above we partially apply f2 with '1' as the fixed value of its first argument, and get a function f2b as the result.  Then we call f2b() passing only one argument '2' to it. Then verify that the result is 3 with our simple test-utility function 'ok()'. There, almost done. Should we go further? No, unless we can answer the following question:

What is it good for? Absolutely nothing? No. Partial Application is good whenever some arguments of a function come from a small fixed set. That usually means you will be calling the function many times with the same values from that fixed set. In such a case it makes sense to partially apply the function to those frequently used values. That will give you new functions that are simpler to call and easier to understand. They will be simpler because they take fewer arguments. They will be easier to understand because they can be given more meaningful names.

A typical example is any function that takes a boolean as one of its arguments, indicating a caller-preference of some kind.  Example:

  function runTest (haltOnError, testCase)
  { /* Run the test and if 1st argument is true
       and test-case fails, throw an error. If
       1st arg is false just return a boolean
       telling whether the test succeeded or not.
     */
    ...
  }

Now if you call runTest() many times,  sometimes with true,  sometime with false,  it might be a good idea to refactor it into two single-argument functions, by using  Partial Application:

   var runTestHalt   =  applyP (true,  aTestCase);
   var runTestNoHalt =  applyP (false, aTestCase);
   ...
   runTestHalt (myTestCase);
   //   runTestNoHalt (myTestCase);

The new partially applied functions are easier to understand because their names can express more about their semantics, because the semantics is simply simpler.There are fewer or no IF-THEN conditions you need to understand.  If you instead use the original test-function, your code would look like this:

   runTest (false, myTestCase) ;

Looking at the runTest() -call above it's not clear at all what is the meaning of the first argument. We can see it is false, but what does that MEAN?  It's hard to remember, takes some effort to look it up, and easy to pass a wrong value to it. Maybe you changed its meaning, and forgot to change some places where it was already called. When the error hits the fan in production, start debugging.

The First Rule of O-O Programmers:  Beware of IF-THEN !

In the accompanying code-file I provide an implementation of ClassCloud.applyP() which does partial-application for you. More than that, it returns functions that can successively partially apply themselves, to further arguments. Here's an excerpt from the unit-tests inside the code-file that show how it can be used:

   function f2 (x,y){return x + y}

   ok (applyP(f2, 1, 2)          == 3);
   ok (applyP(f2, 1   ) (2)      == 3);

   ok (applyP(f2      ) (1) (2)  == 3);
   ok (applyP(f2      ) (1,2)    == 3);


The last two tests above are interesting because they show that we can do partial application by providing ZERO arguments to fix, even though the function really needs more to calculate its value. Why would we do partial application with zero fixed arguments?  The last two lines  give us the clue: applyP(f2) returns a function that can be called exactly like its argument-function f2:
 
   ok ( applyP (f2) (1, 2) === f2 (1, 2) );

So it can do the same thing. But, it can also do MORE:  It can apply  ITS arguments partially, in separate calls as shown above and here again, still returning the same result as f2:

   ok ( applyP (f2) (1)(2) === f2 (1, 2));

We could say that applyP(f2) is not just a different version of f2(), it is a BETTER version of it. It can do everything  f2()does, and then some:  It can take its arguments incrementally.

applyP() as shown by above examples does partial application. But depending on how many arguments you give it, there may be more  partial application left you can do with its result.  Hence the title of this blog-post: Partial Partial Application. The results of applyP() can take care of the further rounds of partial application themselves, and they can do that in multiple stages as well - partially. applyP() can do partial application partially, or fully.


So how is Partial Application related to currying?  My previous blog-post was about currying. In that post I showed  how a function for calculating  max. of two numbers could be implemented in the "curried form" as two single-argument functions, one inside the other, the inner function returned as the result of the outer one:

  function max(a)
  { return maxB;
    function maxB (b)
    { return a < b ? b : a;
    }
  }

Note that the above function is not doing "currying". It is the result of you (or me) having done it. Making your compiler do it automatically is possible but a lot of work; it basically means implementing your own PL. Some PLs do it for you.  Whereas creating a function like applyP() should be within the realm of the practical, as shown by the accompanying, rather small file of JavaScript.

If you look at that code you will see that applyP()is mostly implemented by applyPBasic()which contains AND RETURNS the inner function newFunk(). That is basically the curried form shown for max() above. Currying is the way to implement Partial Application!

There's one more thing to know about ClassCloud.applyP():  It relies on the number of declared arguments of the base-function. If you use it with functions that rely on varying number of arguments, your results might vary (pun intended!). If you call it with more than the declared number of arguments you get an error, which is useful for error-checking. It checks that your assumptions about how many arguments a function takes are correct.  

You can copy the MIT-licensed implementation of applyP() including its tests from http://panuviljamaablog.blogspot.com/2014/07/classcloudapplypjs.html .


 © 2014 Panu Viljamaa. All rights reserved


Saturday, June 28, 2014

Currying Explained Simply

I know there are many articles about "currying" on the web, especially aimed at JavaScript programmers.  Do we need another one?  Well last time I looked I didn't find a really easy-to-understand article about it, so let me try my best. It can be a confusing topic and I admit I have been confused myself, at least dazed. Maybe I can help you if you feel that way too.

The reason it is confusing is that most articles about it are based on the unspoken assumption that you NEED currying, regardless of your PL. But you rarely do in JavaScript.  I'll try to explain in this blog-post why not. And then you need to understand what currying is NOT, why it's not the same thing as "partial application". But I'll focus on explaining "currying" in the simplest way possible.

It is confusing to try to understand something if you don't know why you need it. And even more so if you really don't need it.  So here we go ...

Imagine your programming department has the rule that functions can only take max. one argument. You think, who would make such a silly rule. But there are programming languages where a function can take just one argument. Wink wink: Haskell, F#.  Then your manager asks you to write a piece of code that calculates the maximum of two numbers:

  function maxOfTwo (a, b) 
  { // Return a if it is bigger than b, 
    // else return b.
    ...
  }

You're in a pickle. You're supposed to return max of two numbers, but your function can only take one argument. What to do? The answer, the secret sauce:  currying.  Curry to the rescue. Can you do it? You can, if you can write something like this:

  max (5) (22);   //  ==  22

Notice above you are not passing multiple arguments to a function.  You are doing something else. You are calling max(5) and it seems to be returning something you can pass (22) into.  This is only possible if  max(5) RETURNS A FUNCTION. Yes, functions can return functions, this is JavaScript!

So how would you write the above function 'max'?  Like this:

  function max(a)
  { return maxB;
    function maxB (b)
    { return a < b ? b : a;
    }
  }

Try it.  You see it works. "max(5)" returns the function 'maxB' and if you pass 22 to that, you will get the result 22.

The process of implementing 2- or more argument functions by combining 1-argument functions in this manner is called "currying". 

So is currying useful?   How often do you have 1-argument functions laying around you  want to combine in this manner, to do the job of a 2-argument function?  Maybe you do, but typically it is much simpler to write a 2-argument function to start with - if your language allows it. 

Haskell and F# don't because "pure functions can only take one argument".  But they "fake it".  If you write the equivalent of  max(a,b) in them, they automatically, behind the scenes, turn it into the form of our single-arg max(a) above. Why? That would be another blog-post. But if you program in JavaScript you don't need to know. 

If you program in Haskell or F# you never need to DO currying, it is done for you. If you program in them it's good to KNOW about it, so you know what goes on "behind the scenes".  

In JavaScript, you can forget about it. We rarely start with a two-argument function which we want to turn into two 1-argument functions.  If we already have a 2-argument function we just use it. 

The "pattern" in the max -example above is in fact a very useful JavaScript idiom. You could call it "currying" if that is the thought-process that led you to write it in that manner. But note that executing the function max() does not DO currying. The function  max() is the RESULT of you  doing currying, writing a two-argument function in the "curried form". And it is not doing 'partial application' either. That will be the topic of my next blog-post, I hope.

So what is "currying"?  Let me offer this definition:
 
"Currying is the process by which a function of N arguments is implemented as N single-argument functions such that first of them takes in the first argument and returns a function which takes in the 2nd argument and so on, until the Nth single-argument function finally returns the value of the multi-argument function being implemented."


 © 2014 Panu Viljamaa. All rights reserved

Monday, March 10, 2014

Objects vs. Functions round 1: Currying vs. Instantiation

This article is about the difference between two Design Patterns: "FP Currying"  and "OO Instantiation". This is NOT about comparing the benefits of different programming languages, Object-Oriented, or Functional. We will use JavaScript examples to illustrate both patterns.

CAVEAT:  We will use the term "Currying" loosely here, to mean how we  would implement "something like it" in JavaScript.  It seems the proper definition of currying is calling a function with a subset of its arguments, and then getting back a function that has the previously given arguments fixed to the values you gave them.  The proper term for what we do below is "Partial Application"  meaning you pass in a function + some of its arguments into a function that returns a function where the given arguments have been fixed to values you gave.  You can read detailed explanation of the difference between currying and partial application here

It is often said the defining characteristic of Functional Programming (FP) is "Referential Transparency", or "immutability". But there is no reason why  OO "objects" can't be immutable.  And all FP languages must more or less allow things to "mutate", because they must deal with input-output in some fashion. A function that returns some data from the user most likely will return a different result the next time you call it.

For purposes of comparing FP and OO styles of programming I'd say the main difference is this:   In FP you create and call individual functions (which can return other functions).  In OO you create groups of functions called Classes which you then "instantiate" into Objects.


A well-known feature of FP is "currying" which loosely speaking means you can "fix" some of the arguments of a function to specific values to get another simpler function where those arguments will have the fixed values you gave. This means you don't need to re-enter that same value again and again.  "Currying" (or more properly "partial application") could be used in JavaScript  as follows:  

 function multiply (aNumber1, aNumber2){...}  
 var multiplyBy2 = curry(multiply, 2);
 var six         = multiplyBy2(3);

The benefit is that if you need to  multiply many different numbers by two you no longer need to pass both numbers as arguments of each call, one is enough. As mentioned the above is more "partial application" than "currying". But both serve the same purpose: Getting a simpler function out of a more complex one, by fixing some of the argument-values. I offer this characterization of the subtle difference between the two: "Currying is automated Partial Application"


So is there a way to achieve similar benefits with OO?  Yes. It is called instantiation. You define a "class" with a set of methods and a set of data and then "instantiate" it:

 function Multiplier () {...}    

 Multiplier.prototype.multiply = function multiply () {...}
 var multiplier2 =  new  Multiplier (2);
 var six         =  multiplier2.multiply(3);

Above  Multiplier  is the class,  multiplier2 its instance.

Based on the above examples it would seem currying is somewhat simpler. Fewer lines are needed. But what if you are looking for a solution that handles other numbers besides 2 as well?  The situation changes.

A Class is a group of functions parameterized  by the data defined for that class.   Therefore we can easily extend that group and add more functions or 'methods' to our class, to handle other calculations. So let's give our function/class a more general name, and  add methods for  different calculations:

 function Calc () {... }
 Calc.prototype.multiply = function () {...} 
 Calc.prototype.divide   = function () {...} 
 Calc.prototype.add      = function () {...} 
 Calc.prototype.subtract = function () {...} 
 Calc.prototype.raisedTo = function () {...} 

Then at runtime we can instantiate that class, with any number we want:

 var calcWith2 = new Calc (2); 

Feels a bit like currying, right?  If  we use traditional currying instead to create  multiple functions with a fixed parameter 2,  we  would write thus:

 var multiplyBy2 = curry(multiply, 2);
 ...
 var raisedTo2   = curry(raisedTo, 2);


Now imagine you need to handle other number as well: 3, 4, 5 , 99, etc.  What's so special about number 2 anyway?  Doing that by currying you need to apply currying to each function for each number we want to use as the fixed parameter:

 var multiplyBy3  = curry (multiply, 3);
 ...
 var raisedTo3    = curry (raisedTo, 3);

 var multiplyBy4  = curry (multiply, 4);
 ...
 var raisedTo4    = curry (raisedTo, 4);

 var multiplyBy5  = curry (multiply, 5);
 ...
 var raisedTo5    = curry (raisedTo, 5);

 ...

 var multiplyBy9  = curry (multiply, 9);
 ... 
 var raisedTo9    = curry (raisedTo, 9);



Using the OO -style we only need to write:

 var calcWith3 = new Calc (3);
 var calcWith4 = new Calc (4);
 var calcWith5 = new Calc (5);
  ...

With OO-instantiation we reuse the same parameter, say 4, and get a version of all  our math-functions, with a single call to instantiate the class Calc.  We don't need to re-curry all our methods for all numbers we need, 3,4, ... 99.  The advantage OO has is that the fixed  parameter 4 can be shared by ALL methods of the object-instance, by making a single call which creates that instance.

This benefit is not accidental.  It is a direct consequence of a defining feature of Object-Orientation: All functions ('methods') of an instance share the same set of data. Another way to put it:  By instantiating a class, you are currying multiple functions with a single call.

Which "pattern"  to use depends on what you need. If  you need a general, reusable, extensible solution, OO-style is the way.  If you just want a function that can multiply its argument by 2, currying is simpler. Especially if your language supports it. So I'm not saying "currying is bad". I'm saying it is not missed much in the Object-Oriented way of programming.

There are two additional benefits instantiation has over "currying" (or "partial application").  In a typical implementation of currying you can't curry an argument without currying the arguments before it as well. Can you?  Whereas with instantiation you can decide which subset of data-members of the instance you "fix" with non-default values.  Secondly if your language supports currying out of the box it can't support default arguments: If you don't provide a value for an argument, it doesn't mean a default value will be used for it. It means currying ensues.    


© 2014 Panu Viljamaa. All rights reserved  

UPDATE:  Thanks for several posters at Google+ who pointed out the subtle difference between "Currying" and "Partial Application".  I modified the text above to make it clear my use of the term 'currying' is technically incorrect.

Saturday, January 25, 2014

What does f() mean?

When we write about a JavaScript function named 'f', we often refer to it as f().  We might write in an email, "You should call the function f() at this point". By choosing that way of writing we want to make it clear we are talking about a function, not about an "ordinary variable", which in JavaScript can hold any kind of object.

But, the notation "f ()" should not be used to refer to the function 'f'. Why?  Because "f()" refers to the value returned by the function 'f' .

But doesn't this make it too easy to confuse 'f', which is a function, with variables named 'f', which may hold any type of object as well?  Yes, it makes it more difficult.

But not really IF we take the viewpoint that a variable whose value never changes represents a function that takes 0 arguments, and will thus always "return" the same value - assuming we never change its value. And, it's good to use the convention that JavaScript itself uses.  In JavaScript 'f()' means the value returned by the function 'f' when f is called.

According to functional programming a "function" is only a (pure) function if it always returns the same result for the same argument. Many JavaScript "functions" thus are not (real) (pure) functions. Variables which refer to values that are not JavaScript "functions" can be conceptually seen as "0-arity functions", if we never change their value after initial assignment. Or we should more properly say that the values stored in such variables are in fact 0 -arity functions.

I think the benefit of being able to distinguish between referring to a function f, and its value f(), is more important than the ability to indicate with a special form or syntax whether we are referring to a function or a variable holding some other type of value.


UPDATE:  It needs to be emphasized that what I write about here is a convention for referring to JavaScript functions when writing about them. You can of course pick your own convention as you like. The way we define a function named 'f' in JavaScript is:  "function f(){...}". Therefore it can be argued that a shorthand for that is "f()". I have used that convention myself in the past. But now I think I've seen the light:  "f" stands for the function, "f()" for its result.

To emphasize that this is about how to write about JavaScript  functions, I also changed the title of this post and dropped "... in JavaScript" from its end. This is not about "What f() means in JavaScript". That means what it means in JavaScript, the programming language. This post is about what f() means when we write about the JavaScript function 'f'.

Note the added expressive burden I face when writing this blog-post. I must not only make it clear whether I am referring to a function or its application. I also need to make clear whether I'm talking about JavaScript code, or writing about JavaScript (or even writing about writing about) code in a blog-post like this for instance. I hope I was able to be at least somewhat understandable!


 © 2014 Panu Viljamaa. This work is licensed under a Creative Commons Attribution 4.0 International License

Sunday, January 12, 2014

Improved map() & reduce() ?

In a previous post JavaScript function F () I presented the function F () which allows you to create functions from simple String expressions.

F() makes using JavaScript map() and other "functors"  more concise, allowing you to replace:
  [1,2,3].map(function (x){return x * 10});
with:
  [1,2,3].map(F('x * 10'));

But I and some commentators felt the above still looked a bit cryptic for common use.  Having to know what F() means is an extra mental load for readers of this code, as is the extra set of parentheses needed.  And F() needs to be more or less cryptic, because it is supposed to be a shorthand after all.

So,  here might be a better solution (but see the caveat at the end of this post):

1. Go to section titled "Polyfill" at MDN's Array.prototype.map. It gives the code to implement map() on older browsers which don't support that natively.

2. Read and be aware of the license(s) provided under which you can use their code, linked to at the bottom of their page.

3. Copy their code as instructed to your own script.

4. Replace the beginning of their code :

  if (!Array.prototype.map)
  { Array.prototype.map = function(fun /*, thisArg */)
  ...
  
with this:

  function F (aString)
  { return new Function("x", "y", "z", "w", "return " + aString);
  }

  Array.prototype.map 
  = function (funARG)
  {  var fun = funARG;
     if (typeof fun == "string")
     { fun = F(fun);
     }
   ...

The above replaces the native implementation of map() if it did exist with our enhanced version of MDN's polyfill. If it didn't, it creates the method map() for the Array prototype.

You can now replace:
  [1,2,3].map(F('x * 10'));

with the more simple:
  [1,2,3].map('x * 10');

You can do a similar enhancement to their reduce() -code, available on the same site. Then you can write:
  [1,2,3].reduce('x + y');  

Documentation of map() and reduce() and their polyfills can be found at  https://developer.mozilla.org/. Interestingly, I think the above makes the case that using a polyfill is sometimes better than having the native implementation (which theoretically can differ between browsers as well).

In general I think the point is that using functional expressions like map() should make programming simpler, not more verbose and complicated. It would be great if ECMA at some point added a shorthand syntax for anonymous functions to the JavaScript standard.  But, it can in fact be argued that the solution above is good just because it does not require any new syntax, just an 'overloaded' semantics for map() and other functors.


UPDATE / CAVEAT:  In fact I can not  recommend this solution for general use.  Depending on your application and the JavaScript libraries it uses, the solution above might break your application.. The reason is that when you add a method to the prototype of Array, it means that when looping over an array, that added property will on some browsers become one of the properties being looped over. That might break some existing code not only in your application but also in the libraries you use.  So, for me at least it is back to using the  function F(). Avoid adding your own methods to JavaScript built-in prototypes, at least things you can iterate over!


© 2014 Panu Viljamaa. This work is licensed under a Creative Commons Attribution 4.0 International License