One cannot overstate the rend in the universe that an APL terminal presented, catapulting me decades into the future. I quickly dreamed in APL. For $3 an hour for ten hours (a massive overcharge) I took a professor’s 300 line APL program translated literally from BASIC, and wrote a ten line APL program that was much faster. One line was classic APL, swapping + and * in an iterated matrix product for max and min. The other nine lines were input, output. The professor took years to realize I wasn’t also calling his code, then published my program.
Summer of 1977 I worked as a commercial APL programmer. Normally one never hires college students for the summer and expects them to be productive. The New York-based vice president was taking the train every day to Philadelphia because the Philly office was so far underwater, and desperate to try anything to save himself the commute. He knew Swarthmore had a terminal, and heard about me. At my interview I made a home-run derby of the questions from the Philly boss. The VP kept trying to intervene so he could put me in my place before hiring me. The tough questions were “dead key problems”. How do you write the following program, if the following keys are broken?
Our client was a mineral mining company, our task a reporting system. The reports were 2-dimensional projections of a 9-dimensional database. The accountants wanted all totals to be consistent across reports, and to be exactly the sums of their rounded components. I broke the news to our team that we needed to start over, rounding the 9-dimensional database once and for all, before generating each report. This took a few weeks; I wrote plenty of report generation helper routines. My coworkers overheard me say on a phone call that I was being paid $5 an hour, and at the time I didn’t understand which way they were shocked. I didn’t have much to do, the rest of the summer.
The mining company VP found me one morning, to ask for a different report, a few pages. He sketched it for me. He found me a few hours later to update his spec. He loved the printout he saw, imagining it was a prototype. “It’s done. I can make your changes in half an hour.”
At a later meeting he explained his own background in computing, how it had been key to his corporate rise. Their Fortran shop would take a month to even begin a project like I had knocked off in a morning, then weeks to finish it. He pleaded with me to pass on Harvard grad school and become his protege.
Some Lisp programmers had similar experiences, back in the day. Today, APL just sounds like another exotic language. In its heyday it was radical.
I've never heard of this style of programming question. It's fascinating that we've gone through so many styles of interview over the decades, from pair programming against unit tests to Google-style whiteboard algorithms to early-2000s Microsoft-style brain teasers and "why are manhole covers round".
I grew up with PCs and a Commodore 64 in the 80's, which I think was the golden era of personal computing, but I absolutely love stories from earlier!
Fresh out of college, my father helped a senior programmer at Kodak automate testing for their film developing chemical baths. This replaced dozens of people. Kodak found them other positions, and moved my dad to the research labs. He used computers from the beginning, and told me many stories. On a family night in the 1960's I got to play the original "space wars".
In 1974 he came up with the color sensor pattern now used in nearly all digital cameras.
Wondering though...I visited the Rochester labs in the mid-80s -- hardware I had a hand in was being used there for projects that I suspect were secret at the time such as computer simulation of photochemistry and warping of photoint images to conform to map data. I wonder if I met your father?
> Some Lisp programmers had similar experiences, back in the day.
About 20 years ago (so not quite so far back) I was an engineering intern in an industry (nuclear energy) with two main tools: heavy number crunching software in Fortran, and Excel for everything else. The plant I was working at had just gotten some software for managing and tracking fuel movement (reactor cores are comprised of several hundred fuel bundles, which are re-arranged every 1-2 years), and my task was to set it up and migrate historical data from Excel spreadsheets, either by entering data manually with the GUI (which wasn't really that good) or using the primitive built-in import/export functions (CSV-based probably). Good intern task, right?
At some point I noticed this odd window running in the background whenever I started the program: "Gold Hill Common Lisp". Hm, what's this, it seems to have some kind of command line... and so I dived down the rabbit hole of the CL REPL and live image manipulation. I discovered the apropos command (or maybe GHCL had an actual UI for it?), which let me learn about all the internal data structures and methods, which I was able to use to quickly configure the plant specifics and import data.
"Oh, you're done already? OK next we need to get these custom reports out, talk to the vendor about implementing them. And see if you can now export data into our old report generator" (another spreadsheet of course). So I dutifully started the requisition process to get custom reports added, but while that was working through the system, I was stretching my new-found Lisp knowledge to not just dump out report data, but add the functionality to the UI. Coming from a background in C and Fortran I was fully ingrained with "write, compile, run" being how things worked. Image how much it blew my mind when I found out I could call a function in the REPL and actually add a menu to the running program!
One feature of the software was it could be used for "online" fuel movement tracking, which was traditionally done on paper, in duplicate. It's probably still done that way for good reasons, but still nice to have that electronic tracking. I was so proud when we were demonstrating it to the reactor operators, and they asked if we could add some little functionality (the details escape me), and I was able to say "yep no problem!" No requisitions, then back-and-forth with the vendor, eventually getting the feature in a year maybe. Really wish all software was so powerful (although admittedly my hijinks were a bit of a QA nightmare, but the software wasn't considered safety-related since there were many checks and paper records).
Fast-forward a couple years, after much coursework in Fortran and Matlab, I'm about to graduate and am now interviewing with the vendor. Question comes up "so what would you change about our software?" "Well, the interface is a bit clunky, I'd probably want to re-write it in a modern language like C++" :facepalm:.
Only years later, re-discovering CL, along with Racket and Clojure, did it occur to me how much was wrong with that response, and how sad that the key lesson of that semester internship had gone over my head.
For "production" math research, nothing comes close to Haskell for me. Every time I consider straying, the ease of parallelism draws me back.
I have written a fair bit of Scheme, using my own preprocessor that avoids most parentheses. I stay clear of that loaded debate, this is for personal use. The code is poetic, though not as dense as APL or Haskell. As Bill Joy once opined, what you can fit on a screen matters.
My own favorite Haskell code is a very terse implementation of monadic parsing. Typed trees are not far off from strings, and then one has algebraic data types as parsing. (Pattern matching is parsing a bit at a time, without reifying the activity for program control.)
APL gets unexpected mileage from a core of array handling. I dream of a Lisp-like language tuned to parse algebraic data types as its core activity, with macros as its "middle of the plate" pitch rather than as a strapped-on afterthought. (I'm not trolling here, this is my honest opinion. In 10,000 runs of the simulation, I doubt Lisp macros would be this clumsy in most runs.)
Ultimately we all long for better language tools to express pattern as code. My electric guitar never sounded like what's in my head, and for code I'm still reaching too. Though APL was wonderful in its day.
Writing this, I'm reminded how J felt full of "tricks" much like using Perl: there are these tricks you can use to get the result you wanted that isn't necessarily the most faithful expression of the problem.
Easy, here is some time travel,
"Alan Kay's tribute to Ted Nelson at "Intertwingled" Festival"
https://www.youtube.com/watch?v=AnrlSqtpOkw
"Eric Bier Demonstrates Cedar"
https://www.youtube.com/watch?v=z_dt7NG38V4
"Yesterday's Computer of Tomorrow: The Xerox Alto │Smalltalk-76 Demo"
https://www.youtube.com/watch?v=NqKyHEJe9_w
However to be fair, Java, C# and Swift alongside their IDEs are the closest in mainstream languages to that experience, unless you get to use Allegro, LispWorks or Pharo.
> I took a professor’s 300 line APL program translated literally from BASIC, and wrote a ten line program that was much faster.
The professor translated BASIC->APL, and you translated APL->more concise APL?
thanks for this story btw
I wrote the solution in APL in about an hour and it only had 3 lines of code. The rest of the class spent days on their terminals and keypunches trying to solve it. Most solutions took hundreds of lines of code.
I got a D from my professor. I questioned why and was told that it was unreadable, and that the solution was inefficient. This annoyed me because he didn't know APL, and I figured that since I solved the problem in one hour, while the rest took days, it was very efficient.
I protested the result with the department head (who liked APL) and ended up getting an A+. As you can imagine, all the rest of my assignments, written in a variety of languages, were graded by that AI prof with significant prejudice.
I passed nonetheless. I loved APL and ended up working for one of the major APL providers as my first job out of school.
I often tell people that Spanish is unreadable if you don't know Spanish. This also applies to language features! It's only fair to call things "unreadable" if you have the full context to understand but still find it hard.
That is such a bad faith argument, how can a brute force solution be efficient or inefficient?
There was a discussion on array programming languages here recently where someone proudly showed off a K language solution to a simple problem, stating that the K solution was efficient because it could solve it in 1.2 microseconds. I used Rust to solve it in 5.5 nanoseconds, which is nearly 200x faster. Both used "brute force" with no cleverness, but there's "bad" brute force and "good" brute force.
I've had a similar experience at university while using Haskell. It's a very elegant lazy pure functional language, but it's glacially slow. The natural, low-friction path is very inefficient. The efficient path is unidiomatic and verbose.
I hear people making similar observations about F# also. It's fast to program in, but if you also need performance then it is no better than more mainstream languages -- in fact worse in some ways because you're "going against the grain".
But Haskell vs most others, it’s faster and compiles down to a binary executable.
F# runs on .NET and is comparable to Haskell but not AOT.
Well, if you run a Haskell program on a "C-Machine" of course a comparable program in a "C-Language" will be faster — as it don't need to bridge any gap in execution semantics.
The point is: Mostly all modern computers are "C-Machines". Modern CPUs go even a long way to simulate a "PDP-7 like computer" to the outside world, even they're working internally quite different. (The most effective optimizations like cache hierarchies, pipelineing, out-of-order execution, JIT compilation to native instructions [CPU internal "micro-ops"], and some more magic are "hidden away"; they're "transparent" to programmers and actually often not even accessible by them). So not only there's nothing than "C-Machines", those "C-Machines" are even highly optimized to most efficiently execute "C-Languages", but nothing else! If you want to feed in something that's not a "C-Language" you have to first translate it to one. That transformation will almost always make your program less efficient than writing it (by hand) in a "C-Language" directly. That's obvious.
On the other hand running Haskell on a "Haskell-Machine"¹ is actually quite efficient. (I think depending on the problem to solve it even outperforms a "C-Machine" by some factor; don't remember the details, would need to look through the papers to be sure…). On such a machine an idiomatic C or Rust program would be "glacially slow", of course, for the same reason as the other way around: The need to adapt execution semantics before such "no-native" programs could be run will obviously make the "translated" programs much slower compared to programs build in languages much closer to the execution semantics provided by the machines hardware implemented evaluator.
That said, I understand why we can't have dedicated hardware evaluators for all kind of (significantly different) languages. Developing and optimizing hardware is just to expensive and takes to much time. At least if you'd like to compete on the status quo.
But I could imagine for the future some kind of high level "meta language" targeting FPGAs which could be compiled down to efficient hardware-based evaluators for programs written in it. Maybe this could even end the predominance of "C-Languages" when it comes to efficient software? Actually the inherently serial command-stream semantics of "C-Languages" aren't well fitted to the parallel data-flow hardware architectures we're using at the core now since some time (where we even do a lot of gymnastics to hide the true nature of the metal by "emulating a PDP-7" to the outside world — as that's what "C-Languages" are build for and expect as their runtime).
To add to the topic of the submission: Are there any HW implementations of APLs? Maybe on GPUs? (As this seems a good fit for array processing languages).
It also supports defining syntax extensions which is used by the standard library to provide imperative syntax, which means you can mix traditional APL together with your familiar if/else statements, etc.
At this point there isn't much documentation, and the implementation isn't complete, so I'm not actually suggesting that people run out to try it unless they are really interested in APL. I just took this opportunity since APL is mentioned so rarely here.
https://github.com/lokedhs/array
There is an example of a graphical mandelbrot implementation in the demo directory, that may be interesting.
Anyway, I like reduce, shape, membership, find, and/or, and ceiling/floor. I actually like dealing with arrays in this way.
IMO, that is why numpy/matlab is so much better than APL.
[1] http://web.archive.org/web/20210207121250/http://esr.ibiblio...
I personally can't stand languages that are "spoken description". I understand the appeal to others but the languages just don't mesh with my way of thought. When I'm programming or building a system I'm thinking in the sense of abstract transformations and structures not in any spoken structure. Often times for me it's easier to draw out what I'm thinking of rather than explain it since there's not necessarily a verbal representation behind what I'm thinking of until I sit down and try to come up with one.
I tell my students that Columbia undergraduates are of course smarter, but still...
Aaron Hsu has some talks showing this off about his co-dfns compiler.
So I don't know of any APL that allows module-defining scripts. This is really unfortunate since there's no technical reason to prevent it. With lexical scoping (Dyalog has it, GNU doesn't), it's easy to define a module system and I did this in my APL reboot called BQN: https://mlochbaum.github.io/BQN/doc/namespace.html .
For someone that wants to get started with array languages and does not have any need to be compatible with APL, then this is probably the best place to get started.
It also has good documentation, unlike my array language. I need to put a lot of effort into it to get even close to what BQN did.
Seeing pure APL for XML parsing is.. interesting. Most interpreters support saved/read of functions in a more procedural way.
It would be a win / win, you gain the strength of J, K and APL for array processing, without the weakness of them for anything else.
And just like with regex, you'll get fat disclaimers in doc telling you to not get carried away too much as it can quickly become unreadable.
I used APL professionally every day for ten years. I can read it. I can touch-type it. And I don’t need a specially-labelled keyboard (even thirty years later).
This should not be surprising at all. A pianist does not need labeled keys and people familiar enough with the above-listed spoken languages can touch-type them without much effort.
While, sadly, APL has no practical application in modern software engineering (it stagnated and became irrelevant and impractical) it is wrong to look at the brilliant use of notation as a tool for the concise communication and expression of ideas and list it as a negative. Not being able to speak, read or write Chinese does not make it a bad language.
Well that's the problem. Not being able to read or write APL makes it more fun to learn.
The operations could be the same. There are classes, and operators for matching 0, 1, or more repetitions, etc.
Array languages are powerful especially when you have arrays with arbitrary elements, including arrays themselves. Good luck using a regex DSL to match a sequence of strings, where you might want to define a string class (analogous to a character class) as a regex itself.
You can. It's not typically built into a programming language's standard library. But there are plenty of general-purpose automata-building libraries out there, and some of them do provide DSLs. At least to the extent that the regular expressions you're using are actually regular (many aren't), all a regex is is a domain-specific specialization of nondeterministic finite automata.
I sometimes lament that I don't see them, or hand-coded automata, more often. This was CS101-level stuff when I was in college, and it's pretty easy to code your own even if you don't have a good library available in your language. And, for problems where they're appropriate, using them typically yields a result that's simpler and easier to maintain than whatever ad-hoc alternative you might see instead.
http://p3rl.org/retut#Defining-named-patterns
https://docs.raku.org/language/grammar_tutorial#The_technica...
If you want a demo, reply with a concrete example I can implement.
A well designed regex system is enough without tokenization.
The parser for the Raku language, for example, is a collection of regexes composed into grammars. (A grammar is a type of class where the methods are regexes.)
We could probably do the token thing with multi functions, if we had to.
multi parse ( 'if', $ where /\s+/, …, '{', *@_ ) {…}
multi parse ( 'for', $ where /\s+/, …, '{', *@_ ) {…}
…
Or something like that anyway.(Note that `if` and `for` etc are keywords only when they are followed immediately by whitespace.)
I'm not sure how well that would work in practice; as hypothetically Raku doesn't start with any keywords or operators. They are supposed to seem like they are added the same way keywords and operators are added by module authors. (In order to bootstrap it we of course need to actually have keywords and operators there to build upon.)
Since modules can add new things, we would need to update the list of known tokens as we are parsing. Which means that even if Raku did the tokenization thing, it would have to happen at the same time as the other steps.
Tokenization seems like an antiquated way to create compilers. It was needed as there wasn't enough memory to have all of the stages loaded at the same time.
---
Here is an example parser for JSON files using regexes in a grammar to show the simplicity and power of parsing things this way.
grammar JSON::Parser::Example {
token TOP { \s* <value> \s* }
rule object { '{' ~ '}' <pairlist> }
rule pairlist { <pair> * % ',' }
rule pair { <string> ':' <value> }
rule array { '[' ~ ']' <arraylist> }
rule arraylist { <value> * % ',' }
proto token value {*}
token value:sym<number> {
'-'? # optional negation
[ 0 | <[1..9]> <[0..9]>* ] # no leading 0 allowed
[ '.' <[0..9]>+ ]? # optional decimal point
[ <[eE]> <[+-]>? <[0..9]>+ ]? # optional exponent
}
token value:sym<true> { <sym> }
token value:sym<false> { <sym> }
token value:sym<null> { <sym> }
token value:sym<object> { <object> }
token value:sym<array> { <array> }
token value:sym<string> { <string> }
token string {
「"」 ~ 「"」 [ <str> | 「\」 <str=.str_escape> ]*
}
token str { <-["\\\t\x[0A]]>+ }
token str_escape { <["\\/bfnrt]> }
}
A `token` is a `regex` with `:ratchet` mode enabled (no backtracking).
A `rule` is a `token` with `:sigspace` also enabled (whitespace becomes the same as a call to `<.ws>`).The only one of those that really looks anything like traditional regexes is the `value:sym<number>` token. (Raku replaced non capturing grouping `(?:…)` with `[…]`, and character classes `[eE]` with `<[eE]>`)
This code was copied from https://github.com/moritz/json/blob/master/lib/JSON/Tiny/Gra... but some parts were simplified to be slightly easier to understand. Mainly I removed the Unicode handling capabilities.
It will generate a tree based structure when you use it.
my $json = Q:to/END/;
{
"foo": ["bar", "baz"],
"ultimate-answer": 42
}
END
my $result = JSON::Parser::Example.parse($json);
say $result;
The above will display the resultant tree structure like this: 「{
"foo": ["bar", "baz"],
"ultimate-answer": 42
}
」
value => 「{
"foo": ["bar", "baz"],
"ultimate-answer": 42
}
」
object => 「{
"foo": ["bar", "baz"],
"ultimate-answer": 42
}
」
pairlist => 「"foo": ["bar", "baz"],
"ultimate-answer": 42
」
pair => 「"foo": ["bar", "baz"]」
string => 「"foo"」
str => 「foo」
value => 「["bar", "baz"]」
array => 「["bar", "baz"]」
arraylist => 「"bar", "baz"」
value => 「"bar"」
string => 「"bar"」
str => 「bar」
value => 「"baz"」
string => 「"baz"」
str => 「baz」
pair => 「"ultimate-answer": 42
」
string => 「"ultimate-answer"」
str => 「ultimate-answer」
value => 「42」
You can access parts of the data using array and hash accesses. my @pairs = $result<value><object><pairlist><pair>;
my @keys = @pairs.map( *.<string>.substr(1,*-1) );
my @values = @pairs.map( *.<value> );
say @pairs.first( *.<string><str> eq 'ultimate-answer' )<value>;
# 「42」
You can also pass in an actions class to do your processing at the same time.
It is also a lot less fragile.See https://github.com/moritz/json/blob/master/lib/JSON/Tiny/Act... for an example of an actions class.
---
Note that things which you would historically talk about as a token such as `true`, `false`, and `null` are written using `token`. This is a useful association as it will naturally cause you to write shorter, more composable regexes.
Since they are composable, we could do things like extend the grammar to add the ability to have non string keys. Or perhaps add `Inf`, `-Inf`, and `NaN` as values.
grammar Extended::JSON::Example is JSON::Parser::Example {
rule pair { <key=.value> ':' <value> } # replaces existing rule
# adds to the existing set of value tokens.
token value:sym<Inf> { <sym> }
token value:sym<-Inf> { <sym> }
token value:sym<NaN> { <sym> }
}
This is basically how Raku handles adding new keywords and operators under the hood.Apparently that always happens:
Try APL in your browser - https://news.ycombinator.com/item?id=9774875 - June 2015 (27 comments)
Try APL online - https://news.ycombinator.com/item?id=4090097 - June 2012 (4 comments)
APL Since 1978 [pdf] - https://news.ycombinator.com/item?id=23510433 - June 2020 (21 comments)
Basically you type the name of the operator in latin characters and get the proper symbol autocompleted.
I only see direct key to symbol mappings which might be fine for a full time APL dev but offer a bit too much of a learning curve for just trying it out.
`i => ⍳ (iota)
ii<tab> => ⍳
In some editors you can change the prefix character (in emacs I think the default is . or I changed it to . almost immediately). Also in emacs (though I didn't try this with APL) you can use an entry method based on TeX so if you type: \iota
You will get ⍳https://corecursive.com/065-competitive-coding-with-conor-ho...
Get yo actuary tables on.
A question I had with APL was how do you actually type it in, and it turns out you just use a back-tick as a prefix, like a leader key in vim. Conor walked my through solving something with TryAPL in this video:
(I've always wanted to try doing a white-boarding interview in a visual language like Scratch)
I had Haskell, OCAML, and Ruby thrown at me (no, none of those were on the list). None actually ran on the first try, but I could rehab the Ruby to working (it was a silly mistake, only a small amount of score knocked off), but I could not rehab the Haskell nor the OCAML, so that ended up with a "recommend no-hire".
Bit of a shame, had they chosen the Python that the CV indicated they preferred, it may well have been a "strong hire" (but, failure to produce runnable code, that can't be easily fixed, in a language explicitly recommended against indicates that there are some possible red flags).
~~~~ TryAPL Version 3.4.5 (enter ]State for details) Thu Jun 10 2021 14:30:06 Copyright (c) Dyalog Limited 1982-2021 2 + 2 4 4 2 3 + 8 5 7 12 7 10 ⍳100 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 !10 3628800 +/⍳10 55 +/⍳10 SERVER ERROR ~~~~
At which point a housemate walked up to it and coded the Sieve of Erasthosthenes prime number algorithm in something like 11 characters and out came a list of primes. Holy. And I thought I'd grokked APL.
This is so long ago, that I had to google it. Here it is, OK, more than 11 characters but maybe the code is not exactly the same.
(~v∊v∘.×v)/v←1↓⍳100 ⍝ primes to 100.
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Taken from here with explanation how it works: https://dfns.dyalog.com/n_sieve.htmIt might be added that when the ratio of human:computer processing power was still more in favour of "human", insanely cryptic "hero languages" were popular. Thinking about the lowest-level of scripting in text formatters, APL, the vi macro langauge, and the nastier aspects of Perl.
These days, readable code trumps all, and it's the compiler's job to turn it into incomprehensible gibberish.
> A different keyboard is not required to enter Dyalog glyphs. However, if you would like one, Black Cherry G80-3000 keyboards with Dyalog glyphs engraved are available in UK, US, DE and DK layouts. USB and PS2 adapters are included. The keyboards have been tested using both Microsoft Windows and Linux
https://www.dyalog.com/apl-font-keyboard.htm
I wonder if there are keyboard sticker sets available somewhere. I think I've seen some in the past for video editing software.
I've had keyboards made by "WASD" with Yiddish keycaps (which are slightly different from Hebrew -- there's a double-vov, double-yud, kometz aleph -- here's an online version if you're curious https://keymanweb.com/#ydd-hebr,Keyboard_yiddish_pasekh ) Just upload your graphics and they'll make it.
You can order it custom also: https://www.pckeyboard.com/page/product/KBDCFG - US APL.
https://www.pckeyboard.com/page/product/KBDCFG - choose a color and than select Language -> US APL
https://careers.digitalroute.com/jobs/98847-implementation-c... has a code sample (https://stuffthatiliketoshare.files.wordpress.com/2014/07/no...) which does not look like APL at all.
I would personally love to have a built-in APL scripting language for interacting with data.
APL takes care of binary-vs-decimal inexactness too, so 3×(1÷3) is really 1:
3×(1÷3)
How is this done? How well it scale? I suppose well, because APL is good for math, rigth? But then I remember that must be slow...?However, Dyalog just uses IEEE doubles (with an error in place of infinities or NaNs; also you can configure to use higher-precision decimal floats), no different from JavaScript. The result of, say, 0.1+0.2, is not the same as 0.3, it's just equal under tolerant comparison.
[0] https://www.dyalog.com/blog/2018/11/tolerated-comparison-par...
The "fun" is with, e.g. `0.1 + 0.2`. I just tried on the website
0.1 + 0.2 - 0.3
2.775557562E¯17
which agrees: julia> 0.1 + (0.2 - 0.3)
2.7755575615628914e-17 say 3×(1÷3)
# 1
It works because `1÷3` is a rational number. my \rat = 1÷3;
say rat.numerator; # 1
say rat.denominator; # 3
If you multiply it by 3, you get another rational number which represents 1. my \result = 3×rat;
say result; # 1
say result.numerator; # 1
say result.denominator; # 1
---Now that this may be slower than using floating point numbers, but it isn't that much slower. You only have two integers that you have to manage.
Actually on many older processors there wasn't built in support for floating point numbers, so it might actually have been faster to use rationals like this.
(I'm not sure if this is how APL handled it.)
---
APL happens to be one of the languages Raku copied ideas from
×/⍳10
Translated to Raku [×] 1..10
That is rather than `×/…` it is written `[×] …`. Partly because `/` is the ASCII version of the division operator.We could go further towards replicating it.
{
sub prefix:<⍳> (UInt \n){ 1..n }
sub infix:</> (&f, +list){
[[&f]] list
}
constant term:<×> = &infix:<×>;
say ×/⍳10;
# 3628800
}The only things I remember are that a symbol could could do 3 things when used with a monad, dyad, or infix, and that it was very hard to read anyone else's code because it was so terse.
They also went through a phase of naming their Java classes things like com.a.b after getting used to K's terseness. Fortunately, that didn't last very long.
3 1 3 */ .s <1> 1 ok
import numpy as np
from collections import Counter
print(2+2)
print(np.array([4,2,3]) + np.array([8,5,7]))
print(np.arange(1,11))
print(np.arange(1,100001).sum())
print(np.arange(1,11).prod())
avg = lambda x: x.sum() / x.shape[0]
print(avg(np.array([1, 6, 3, 4])))
throws = np.random.randint(1, 7, size=(10000,))
print((throws == 1).sum())
print(Counter(throws))
print(Counter("Mississippi"))Consider a game that starts with white moving their king side knight to the square in front of the pawn on the bishop's file. Here is how that would have been written through the ages [1].
Early 1600s: The white king commands his owne knight into the third house before his owne bishop.
Mid-1700s: K. knight to His Bishop's 3d.
Early 1800s: K.Kt. to B.third sq.
Around 1850: K.Kt to B's 3rd.
Around 1860: K.Kt to B. 3d.
Around 1870: K.Kt to B3.
Around 1890: KKt-B3.
Early 1900s: Kt-KB3.
Mid 1900s: N-KB3.
Last quarter of 1900s to present: Nf3 or ♘f3 if you want to avoid language-specific piece names.
Reading that numpy code compared to reading APL is like reading a record of a chess game from around 1700.
[1] https://www.knightschessclub.org/the_history_of_notation.htm...
Here: https://medium.com/@jansson.sebastian/apl-in-the-eyes-of-a-p...
But there are trade-offs doing that, and "amount you can look at at once" is a huge one.
What I find really annoying is how many people confuse this property ("accessible to those not trained in it") with readability.
You can do arrays on python, but python is not an array language.
In other words, the moment you mix 2 paradigms, them will mismatch in direction of the most dominant one.
If you're looking for a performance, opensource APL, try j. Though if performance is not a priority then, as the sibling says, dzaima/apl or april should be more than adequate.
NB. NARS is also very decent, though it only runs on windows.
And, the APL interpreter/compiler was weird. if you typed an F followed by a backspace, followed by an L, it would merge those into an E, as if they were typed on top of each other, like a typewriter.
α = qalpha
β = qbeta
↑ = qup
∀ = qall
¬ = qnot
Since you read code more often than you write it, I think it is actually preferable to work with a language like this.
In ~/.exrc/.vimrc
ab qalpha α
ab qbeta β
ab qup ↑
ab qall ∀
ab qnot ¬
Also, for rlwrap users:I program in Raku, which can be written using only ASCII, but it can be clearer if you mix in a bit of Unicode.
For example, a raw quote can be written like this using only ASCII
Q[C:\Windows\]
Or you can write it like this 「C:\Windows\」
To get those two characters I have added these two sequences Compose [ [
Compose ] ]
I use them so often that it was worth making them a double press of the same key. The other options would have probably been `Q[` and `Q]`.Another example is
* * *
That is a lambda that takes two arguments and multiplies them together. It is also much clearer as * × *
I didn't even have to add this Compose x x
There is also 1, 2, 3 <<+>> 40, 50, 60
1, 2, 3 «+» 40, 50, 60
@array>>.is-prime
@array».is-prime
These were also already there Compose < <
Compose > >
Most of the compose sequences I have added match the ASCII equivalent. Which makes it very easy to remember them, even though I may not use them often. π pi
τ tau
∪ (|)
⊎ (+)
∩ (&)
≡ (==)
≢ !(==)
(That is I type `Compose p i` for `π`, and it is equivalent to `pi`.)or are at least similar
Unicode
Compose
# Actual ASCII
∅ set # set()
(That is I type `Compose s e t` and it is equivalent to `set()`.)Though some of the ASCII operators are apparently too long to do that with.
∈ (el) # (elem)
∉ !(el) # !(elem)
∋ (co) # (cont)
∌ !(co) # !(cont)
I would like to point out that I actually had to read my .XCompose to remember how to type this last four. I don't use them as often as `「」`, and they don't match the ASCII like `≡`.There are also some that I had to make the compose sequence longer.
∘ &o # o
---There are some codes that I just remember for some reason like `U2424` is ``. (That's not even an operator in Raku, though it is useful for messaging the camelia eval-bot on irc.)
The other problem is that I would bet that a lot of the early use for APL was done better by Excel spreadsheets on desktops. By the time APL moved off the mainframe, it was too late. Of course, I'd imagine as far as code maintenance goes, APL beats a very large spreadsheet with a lot of VBA. Excel also has built-in charts and other functionality that is far clunkier, even in the best APLs.
EDIT: see https://news.ycombinator.com/item?id=27462828 too
Of course, I’ve been wrong for about a decade. but we have to be getting close
There are two (nearly identical) talks by Emily Shea
- Perl Out Loud https://www.youtube.com/watch?v=Mz3JeYfBTcY
- Voice Driven Development: Who needs a keyboard anyway? https://www.youtube.com/watch?v=YKuRkGkf5HU
Even for the on-screen keyboard - at least make it have a few rows, not everything on a single row. Jeez.
Context: I used APL professionally every day for about ten years and was quite active in the community at the time.
J is fine, great, easier license, has a larger and more powerful set of primatives.
Please.
You are free to provide a counter-argument.
Here’s the key question you have to answer:
After decades of not only inventing, but using, promoting and educating about the advantages of a specialized notation for programming. Did Iverson start J because it was a distinctively better path than APL?
No. Of course not. After nearly thirty years of brilliantly creating and promoting his notation Iverson made a mistake. It would not be the first time in the history of technology this happened, and it won’t be the last.
It has no context-free grammar (but neither does APL). Scoping is local or global: if a variable in a function is local, even inner functions can't access it. It has namespaces (locales), but they are not first-class and are instead referenced by numbers or strings, so they can't be garbage collected. Until this year, there was no syntax to defined a function—even though control structures had dedicated syntax! System functionality has no syntactic support, so it's provided by passing a numeric code to the "foreign" operator. To enable recursive tacit functions, functions are passed by name. Not just as arguments, anywhere. The name is just a string with no context information, so if you pass a function to an explicit modifier and the name means something different in that scope it will do something different (probably a value error, fortunately). Oh, also these names store function ranks, and if you define the function later it won't pick it up, so even the tacit recursion thing is broken.
The designers of J weren't familiar with design principles that are common knowledge outside the APL world, and it really shows. J was my first programming language (well, except TI basic) and while I'm still a big fan of array programming it really held me back from learning these things as well.
No, I don't hold a grudge against J. That's preposterous. Silly, really. These are tools.
No. I don't prefer one symbol to two characters. That is also silly.
You have to understand the HISTORY in order to understand my statement.
APL was, at the time, brilliant. Remember that it started in the 60's. Way ahead of its time. I learned and worked with it professionally in the 80's and early 90's.
Ken Iverson, the creator of APL, understood the power of notation as a tool for thought. In fact, he famously authored a paper with exactly that title [0].
I had the pleasure of being at an APL conference where Iverson himself presented and discussed this paper. I also took advantage of tutorials and sessions by Iverson and many of the early APL luminaries of the time.
The power of notation might not be easy to understand without truly internalizing APL or having good command of a reasonable analog. For example, a classically trained musician appreciates the value of musical notation. While not perfect, the alternatives have failed to deliver equivalent results, power, expression, etc. The day something else is used to score and perform orchestral performances we might have something to consider.
There are other examples of the power of notation and the paper covers the subject well.
So, why is it I say J is an abomination?
History.
Why does J exist? Why did Iverson go this way after correctly noting and promoting the idea that notation was a powerful tool?
He made a mistake, likely driven by a failed attempt to improve business outcomes.
Here's the history part.
Back in the '80's doing APL characters was not easy. On mainframe based systems we either had to use specialized IBM or Tektronix terminals and printers. When the IBM PC came out we had to physically replace the video card's character ROM (not sure most people know what this is these days) in order to get APL characters.
A common hack was to install a kludgy setup with a toggle switch so you could switch between APL and standard characters. The keyboard, for the most part, got stickers glued to it on the front face of the keycaps. You could, eventually, buy new keycaps for the IBM PC standard keyboard.
Printers suffered a similar fate. You had to reprogram and hack Epson and other printers in order to be able to print the characters.
Incidentally, if you wanted to use a PC for, say, Japanese and English back then you had to resort to the same kinds of hacks or buy specialized video cards and software.
I could go on. The point is that you had to be truly determined to do APL back then and it was a pain in the ass. Convincing an employer to hack 500 PC's so you could migrate to APL was an exercise in futility. Financials and other industries where the power of APL could be put to good use took the plunge, nobody else did. I did an APL-based DNA sequencing tool for a pharmaceutical company back in the 80's.
APL wasn't going to go very far beyond academic and corner-case circles under those conditions.
That's when Iverson came up with the J concept of transliterating APL characters to combinations of standard ASCII characters. It was hard to impossible to sell APL to the masses given the issues of the time. Iverson thought the transliteration would open the doors to the wider audience. Well, it did not. Among other things, notation, believe it or not, is much more practical and easier to learn than a seemingly random mish-mash of ASCII characters.
From my perspective Iverson suffered from a lack of conviction based on likely business pressure. The hardware of the day was conspiring against being able to push APL out to the masses. He did not have visibility into what was coming. Shortly after he took the J trip, the IBM PC went fully graphical and universal multi language (spoken) characters could be rendered without hardware hacks. Except that now Iverson, the creator of APL, had his business interests firmly attached to J. Here we had a situation where the creator of APL pretty much abandoned the language he brilliantly developed, taught and promoted for over twenty years.
The J enterprise, as a business, deviated his path and likely seriously damaged APL. And it failed. It absolutely failed. Nobody who used APL for any non-trivial application was going to consider J. Not due to some test of purity. No, it was because the power of notation is such that J was, in fact, a complete abomination. The only way anyone I knew would consider it was if by force. I can't think of any APL-ers of note of the era that truly jumped on the J bandwagon. The proof that J failed is simple. It's just as dead as APL. Corner case use, sure. Just like APL. I used APL professionally for ten years and I would not touch it at all for any real application today. Anyone doing so would be crazy to make that choice. The only exception would be in maintaining or extending an existing system. Even then, you have to very seriously consider porting it to a modern language.
Notation isn't "funny characters". It's a powerful tool of both expression and thought. If notation is "funny characters" what do we say about every written human language with "funny characters" (Chinese, japanese, greek, arabic, hebrew, etc.). Do we convert every word in Chinese into ASCII transliterations of the symbols just do it doesn't look "funny" and to make Chinese more popular? No, this would be an abomination. Chinese is a rich and expressive language, complex, yes, of course. And yet the power of this language, among other things, in the notation used to put it to paper.
Imagine converting every "funny character" human language to a mish-mash of ASCII just because the IBM PC could not display them in the early days. Imagine then saying that someone calls these abominations because "he prefers one fancy character to two ugly characters" or "He holds a grudge against <language>". The first thing that comes to mind is "ignorant", followed by "misplaced". Learning about and understanding history and context is very important.
Can J be used for useful applications? Of course. So can COBOL, FORTH and LISP. Yet this does not mean it is a good idea. And using J to write research code (which I did with APL in school as well) is nowhere near the realities of real code in real life at scale and maintainable over time and hardware evolution. Extending this to mean that abandoning the power of APL notation due to hardware issues was a good long-term idea is, in my opinion very wrong. J has no future. Neither does APL in its current form. I still think everyone should be exposed to languages like FORTH, LISP and APL in school. There's a lot of value in this.
EDIT: Imagine if Guido had abandoned Python just before it started to become popular and went in a different direction. The language would have stagnated and likely become irrelevant. That's what happened to APL. And J went nowhere as well. Iverson confused and antagonized the APL community to go after perceived business opportunities. In doing so he pretty much destroyed APL and J.
[0] https://www.eecg.utoronto.ca/~jzhu/csc326/readings/iverson.p...
due to the way APL is written and it's sort of philosophy of computation if you tried to be literal about you'd end up with a bunch of inscrutable nonsense anyways
consider https://www.aplwiki.com/wiki/FinnAPL_idiom_library#Inner_Pro...
(⌽∨\⌽' '∨.≠X)/X would be
(reverse or scan reverse ' ' or prod = X) reduce X
or that infamous Game of Life one liner life←{⊃1 ⍵ ∨.∧ 3 4 = +/ +/ 1 0 ¯1 ∘.⊖ 1 0 ¯1 ⌽¨ ⊂⍵}
life set {disclose 1 X or prod and 3 4 = + reduce + reduce 1 0 -1 bind prod rotf 1 0 -1 rot each enclose X}
Still just nonsense right? You'd end up writing very different code.This just looks like Haskell.
The advantage of using symbols for array operations is the same as the advantage in math of using them for arithmetic. A symbol can be read much faster than a word, and it makes syntax easier, not harder, to discern. This is because you only have to mentally group symbols into expressions instead of grouping characters into words and words into expressions. When programming with keywords you'd probably mitigate this by writing shorter lines in order to move some of the structure to a higher level.
Keywords have the advantage that the ones the user writes aren't any different than the ones the language provides. This can be nice, although I find that distinguishing user-defined words from symbols can also be helpful: those words tend to give a good summary of what's going on, while the primitives around them just do all the data-shuffling detail work required to make it happen. So it's easier to ignore those details and quickly get the bigger picture.
Hot take: take a look at numpy.
In general, I would say no. One of the main points is that the notation is terse so that the experienced readers can at a glance see what is going on. Notation as a tool of thought, and all that.
I think without the special keyboard APL is a no-go these days.
Unicomp, the company who bought the rights and tools for the venerable IBM Model M keyboards, do still sell to this day both IBM Model M keyboards and sets of APL keys (!).
1. https://github.com/JuliaLang/julia/search?q=apl&type=issues
I so liked the APL squiggly characters (mostly Greek letter based glyphs). Made for very succinct code. Combined with right-to-left precedence resulted in very low overhead to write and read code. Most people who complained about it APL as “write-only” seemed to be outside the community of serious APL programmers. Once you learned to read the language it was very easy to comprehend at regular reading speed...
In contrast NumPy seems absurdly wordy, and waiting for the completion menu in an IDE tends to derail my train of thought.
However I do tend to like NumPy for being APL-like, so it’s not a damning contrast as far as getting things done.
IMO Its pithy syntax was just not worth it, even back then, so haven't returned since and don't see any reason to break my 40 year hiatus.
(Some parts of the syntax are brilliant and would be awesome if adopted by modern languages. Others ..... not so much).
It is semantically more like “map” than “foreach”, but syntactically emphasized the applied function rather than the fact that it is applied to the container - and that shows especially when nested - f””x or f”[2]x means “apply at depth two”. Compare that to a nested map/foreach
There are other syntax features I like, but most of them do interact with semantics (some more, some less). This one is useful in any language.
[0]: https://corecursive.com/065-competitive-coding-with-conor-ho...