9

I'm writing code in C++, but I really like K/APL's array-oriented style.

Does anyone know of a good set of operator overloading tricks / macros / ... to allow some K/APL -style programming in C++?

Thanks!

anon
  • 41,035
  • 53
  • 197
  • 293
  • 5
    This is just my humble opinion, but if you are going to program in C++, you should program in C++ style. – James McNellis Apr 20 '10 at 22:30
  • I don't know APL. Could you produce a "representative" example of what you call array-oriented style? Do you mean array oriented like Matlab is Matrix oriented ? – log0 Nov 10 '10 at 23:21
  • 1
    I took a look at the K Programming language. Sorts a list of strings by lengths: `x@>#:'x`. Scary – log0 Nov 10 '10 at 23:29
  • @Ugo Look at the sample at the end of my answer for an example of array programming. Basically, operations happen on vectors rather than scalars. And the k example you cite makes perfect sense with enough practice in "terse" languages. – chrisaycock Nov 11 '10 at 03:29

2 Answers2

6

For mathematics, Blitz++ is the biggest library for array programming. Here are some examples from the documentation:

#include <blitz/array.h>

using namespace blitz;

Array<int, 1> x(10);     // one-dimensional array of 10 int's
firstIndex i;            // place holder index
x = 10 * i;              // x == 0, 10, 20, 30...
x = 10 * tensor::i;      // a short form of the above two expressions

// another example, with array-level assignments and arithmetic
Array<int, 1> a(4), b(4), c(4);
a = 1, 2, 3, 4;
b = 5, 6, 7, 8;
c = a + b;

Blitz++ uses expression templates, a template metaprogramming technique similar to lazy evaluation. So the compiler-generated code doesn't use any unnecessary temporary variables, and should be as fast as hand-written loops.

Here's the equivalent k code, for the interested:

  x:10*!10
  x
0 10 20 30 40 50 60 70 80 90

  a:1 2 3 4
  b:5 6 7 8
  c:a+b
  c
6 8 10 12
chrisaycock
  • 36,470
  • 14
  • 88
  • 125
2

I haven't looked specifically at K/APL, but depending on your viewpoint, you could argue that some of the operator overloads provided by std::valarray are vaguely similar to APL. With its support for Universal Character names, you could (at least in theory) even provide APL-like names for some of them.

That still leaves some characteristics that aren't like APL at all, such as operators in C++ having precedence and associativity, which APL operators don't at all (at least if memory serves).

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111