Functional Programming – Wrapping Basic Functions in High-Level Languages

functional programmingprogramming-languages

I'd like to know if there's a general guide or best practice for wrapping basic functions.

Let's take J for example. It has several 1-or-2 character "functions" called primitives. Examples:

  • , : Flatten a matrix or append to a vector
  • { : Catalogue combinations or take nth item of a matrix
  • {. : Take first or n elements of a matrix
  • } : Amend items in a matrix

Some J programmers think it best to use them as such, other will wrap them in functions like so:

  • Append =: ,
  • TakeFirst =: {.

I found that's not always practical because I'm used to the actual "symbols", but that basically means I'm biased.

So, any advice on the best practice to use? To wrap or not to wrap?

Best Answer

Many years ago, before the legions of Pascal programmers had been routed by the C hordes, some Pascalians tried to adapt to the new reality by doing this:

#define BEGIN {
#define END }

so that they could write:

void main(int i)
BEGIN
    printf("Hello, world!");
END

There were often other, similar macros designed to hang onto even more Pascal syntax. It wasn't long before they realized that they were only torturing themselves and either gave themselves over to the C side willingly, or perished.

If you're going to use a language, use the language. That may require learning it first. Gluing on a bunch of nonstandard names for standard operators may make things easier for you to grasp in the very short term, but you end up with code that can't easily be understood by other people well versed in the same language.

Wrappers make sense when you need to adapt one class or language to another. For example, you might have a Java class that wraps calls to C or C++ functions to make that functionality easier to use and more accessible for Java developers. If you're going to use a wrapper, make sure that it really does simplify the code, prevent bugs, or otherwise adds value. Don't do it just to avoid learning the syntax.