I’ve been an imperative programmer ever since I wrote my first “Hello, world!” program in 2007. I dabbled a bit in Scheme in one of my undergraduate courses and recently revisited Scheme following The Little Schemer and The Seasoned Schemer. But all of my jobs have been in an imperative, object-oriented style of programming.
I recently saw a video of a sudoku solver written in APL. I was immediately fascinated with APL due to its conciseness and the non-ASCII characters that seemed to magically find the values of a sudoku board.
After doing a bit of reading and watching another video of an APL program, I realized the magic was not coming from the strange syntax of APL, but from the style of programming. APL is an array-oriented, functional programming language. The shift from object-oriented to array-oriented is what was causing everything to seem like magic.
Array programming feels much more math-y than other styles of programming. It’s based on arrays, vectors, scalars, matricies and other concepts I can vaguely recall from my Linear Algebra course. There is a focus on applying functions to entire sets of data instead of specific instances of a data object.
Determined to demystify the wonders of APL, I dug around for an interpreter and a way to make those fun symbols. It is much harder to get a working installation of APL on a MacBook than I would have thought. I ended up with a buggy, open source version of APL running on Wine. After reading some forum posts, Stack Overflow and Wikipedia, I came to the conclusion that J was a better fit and an easier barrier to entry to array-oriented programming.
Instead of the unique symbols of APL, all of the notation in J is ASCII based. APL was also fairly expensive for a developer license and the open source implementation only seemed to work on Windows. With J, I was up and running with a console and a vim syntax plugin within 10 minutes on my MacBook.
The next challenge was actually doing something in J. I settled on Project Euler and am making some head bashing attempts at problem 1.
The Problem: Find the sum of all the multiples of 3 or 5 below 1000.
This is what I’ve come up with so far (note: this is probably not the J way to do things):
+/ ((0= (3 | 1+i.1000)) # 1+i.1000)
1+i.1000 yields an array from 1 -> 1000
3 | 1..1000 yields an array of modulo 3
(1, 2, 0, 1, 2, 0 ...)
0= (1, 2, 0..) yields an array of boolean values where the input array is equal to 0
(0, 0, 1, 0, 0, 1 ...)
(0, 0, 1 ..) # (1, 2, 3, 4 ...) picks each value of the right array where the left array is 1
(3, 6, 9, 12, ...)
+/ is a fold with a + operator.
Now I just have to figure out how to sum an array that mod3 or mod5 == 0…
Here are some resources that I’ve been finding helpful to learn J: