122 points · by snicker7 · 4y ago · 109 comments
- Dicts (same as hashmaps, associative arrays, etc.) are a native datatype, with `ab`cd!0 1 indicating a dict mapping symbols `ab and `cd to 0 and 1, for example. In K4 and later (ngn/k implements K6), array primitives work on them to do all sorts of fancy things. For example prefix &, "where", returns the indices of any 1s in an array. If given a dict, it gives you the keys corresponding to 1s.
- Partial application. If you have a function f of two arguments, f[;x] binds the second argument x to f, but leaves the first one unbound. So f[;x][y] is f[x;y]. But that's not nearly all: arrays, dicts, and functions are unified, so if fs is a list of one-argument functions, then fs[;x] applies each function to x. This is because fs[;x][i] is fs[i;x] or fs[i][x]!
ngn/k is the best implementation to use now in my opinion. It's short on documentation, but the K Wiki is a new and very nice resource for K. Maybe start with the list of all primitives at https://k.miraheze.org/wiki/Primitives .
So now I'm curious: why didn't you include some version these features in BQN? They seem pretty nice to have!
EDIT: will you ever write a "let's learn BQN by figuring out how the self-hosted compiler is implemented!" article? I doubt I'll use BQN soon but I find it a fascinating, extremely interesting language, and I'm just super-curious how you implemented the self-hosting compiler.
I don't think studying the compiler is a very good way to learn BQN, but I would like to write up parts of it (limited by time and motivation of course). I did some chat sessions on this sort of compilation during early development; see the links at the bottom of https://mlochbaum.github.io/BQN/implementation/ .
f[y;x]
why?
While refcards like this are perfectly fine, they can confuse beginners at specific parts in the text. This is where ngn/k shines. It has a robust documentation system, containing several help commands for multiple subjects (types, verbs, adverbs, etc.). They also contain examples, have clear separation between subjects, and are way less ambiguous.
Where does this madness come from, and why does it infect proponents of array-based languages to the point where they start writing C code in this style!?
Some of my complaints: * true adherence to the source material requires one to dispense entirely with all but the tersest comments * it over-aggressively tunes away whitespace (if you code like this, it's quite beautiful when you align comparable values on the same column between adjacent rows) * many of the idioms rely on undefined behavior, which makes it very frustrating to maintain, port, and extend--to a lesser degree, it makes the code hard to follow, but usually (the most frustrating part of all!) is that the intent is _clear_, it's just that it doesn't work well with the C standard * it emphasizes the placement of as many statements as possible on a single line, which is jarring when those statements don't flow together; on the other hand, the style is quite nice when you allow yourself to place complete and related concepts together, since it's clear that you're "doing something else" on subsequent lines
I said this is "unfortunate" not because I have any problem with Arthur, but because I actually wish this was part of a richer tradition of C (which I've never been able to confirm and thus came to my conclusion about idol worship). Although I happily abide by them in my professional life, I am thoroughly frustrated with coding standards that dictate variable names be complete sentence and code limited to 80 lines. I would love to adopt a rigorous style _based on_ Arthur's, although I will concede that this will probably never happen because the aesthetic of this practice conflicts so completely with the contemporary zeitgeist.
Anyway--nobody has to like it, but some people really actually do like it and accomplish work with it.
Is that true?
Isn't this style just a natural place to arrive after agreeing with and understanding "Notation as a tool of thought"?
Also while learning J/K I didn't notice much of this worship.
I'm afraid of writing off a purposely chosen style as one that has no merits and is explained by idol worship.
I want to be clear that I think this style does indeed have merit, regardless of its origins. I like it--I prefer _reading_ and _comprehending_ code rather than superficially skimming code--I believe the style serves that goal wonderfully. I do not think that a thing adopted because of one's respect and adoration for an idol figure invalidates the value of the thing, _but_ I also think I spoke much too harshly and I recognize that people are allowed to like a thing and take it from another person without idolizing the creator.
However, I still believe the style originated with Arthur. Again, I don't think that's bad, and I agree with you that there is indeed some spirit of Iverson's work spread around different computing communities in the way they write C. Then again, _I_ did not have the presence of mind to spontaneously write Arthurian C without reading his code first and thinking really hard about it, so I am perhaps making the mistake that everyone else is similarly limited. I've tried to find independent exemplars of similar styles without success. Again, I write that down as a personal failing.
Some writings on this style:
One talk I saw by a proponent explained that the intention is that you often change just the trailing character (or 2 or 3) to "twiddle" a query until it does what you want.
That interactivity makes sense to me. I do similar things with query languages like KQL.
But... in C? It's compiled! You have to "run" it!
Not to mention that it makes no syntactical sense in C to be fiddling around with suffixes. It has nested brackets that need to be properly closed! It's procedural, not declarative, so even if you condense the syntax, you don't "win" that much in the end.
There is literally no way that anyone could ever justify using single character source file names. That's just absurd. Note that the author had to put a little table explaining what each single-character file does/contains.
WHY NOT JUST NAME THEM to match their function!?
So instead of this madness:
0.c syscalls and main()
m.c memory manager
p.c parser
k.h embedding api
a.h common header
g.h header generated by g.k
Just use words like a normal human: main.c
memory.c
parser.c
embedding.h
common.h
generated.hAre there people (other than the author) who look at this source code and read it fluently? There appear to be few clues as to the meaning, in terms of naming choices (of any identifiers), comments, formatting, etc.
ngn/k is certainly a lot of fun to use. I just wish it also worked on OS X (& plan9).
To start on MacOS, can apply this patch then run `make k-libc` on OSX 12.0.1 (M1 processor):
diff --git a/makefile b/makefile
index 5b08dde..1ba3c32 100644
--- a/makefile
+++ b/makefile
@@ -10,7 +10,7 @@ w:k o/w/fs.h o/w/k.wasm o/w/index.html $(patsubst w/x/%.k,o/w/x/%.k,$(wildcard w
h:w o/w/http;cd o/w;./http
k-dflt:; $(MAKE) a N=$@ R=k O='-O3 -march=native -nostdlib -ffreestanding' L=''
-k-libc:; $(MAKE) a N=$@ R=k O='-O3 -march=native -Dlibc' L='-lm' STRIP=true
+k-libc:; $(MAKE) a N=$@ R=k O='-O3 -Dlibc' L='-lm' STRIP=true
k-obsd:; $(MAKE) a N=$@ R=k O='-fPIC -Dlibc=1 -DSYS_getcwd=304 -Dstrchrnul=strchr' L='--static -fno-pie -lm -lc' STRIP=true
libk.so:;$(MAKE) a N=$@ R=$@ O='-O3 -march=native -nostdlib -ffreestanding -fPIC -Dshared' L='-shared' STRIP=true
o/$N/%.o:%.c *.h;$M;$(CC) @opts $O -o $@ -c $<
However, Apple platforms are not officially supported (or to put it more bluntly, "officially not supported"), and there are bugs such as this one[1]. I suspect it has to do with libc differences on Mac versus Linux. If you have experience with the libc differences between Linux and Mac, I'd welcome your input! I'm not an ngn/k developer, just interested in adding support for MacOS.This is how they roll in the k world. Imagine including k.h in an external application that wants to use some k functionality and the existing code uses the single char looping idiomatic code:
for (int k = 0; k < 100; k++) {}
'k' gets redefined and LOLs all around.After the recent AoC which I've attempted to solve with BQN[1] (another array language) I've got interested in array languages and now exploring K too.
K seems like a nice blend between an array language and a lisp: list is a primary data structure in K, no multidimensional data. K is good at symbolic workloads as well — visit http://nsl.com for some examples.
Also, make sure to check out the C code style ngn/k is written with :-) another K implementation Kona (uses similar C code style) has a wiki page with explanation[2].
[1]: https://mlochbaum.github.io/BQN/index.html [2]: https://github.com/kevinlawler/kona/wiki/Coding-Guidelines
https://www.arraycast.com/ announced last year (https://news.ycombinator.com/item?id=27209093) may interest a similar audience as this announcement
First, direct links to ngn/k in the browser:
- REPL: https://ngn.bitbucket.io/k/#r
- Editor: https://ngn.bitbucket.io/k/
Second, the best one-stop shop for an overview of k6's primitives (both ngn/k and oK are based on k6). https://github.com/JohnEarnest/ok/blob/gh-pages/docs/Manual....
The best intro examples are in John Earnest's k editor iKe - there's a dropdown at the bottom right. http://johnearnest.github.io/ok/ike/ike.html
ngn/k's editor also has an 'examples' dropdown in its menu.
For an illustration of k's strengths, Razetime's matmul refactoring is brilliant: https://github.com/razetime/ngn-k-tutorial/blob/main/c-think...
Finally, some nice examples of concise k:
{$[2>#?x;x;,/o'x@&'~:\x<*1?x]} / Quicksort
(+':,)\~!10 / Pascal's triangle
{x x}{x{x[x]y}y} / Y-combinator
Executable versions of above:- Quicksort (via Kelas's KCC guide): https://ngn.bitbucket.io/k/#eJwrLLaqVok2slO2r7CusNbRz1evcFBT...
- Pascal (via Richie/Attila): https://ngn.bitbucket.io/k/#eJzT0Fa30tGMqVM0NAAADYMCZg==
- Y-combinator (via ngn): https://ngn.bitbucket.io/k/#eJyLtKquUKiora6oroiuiK2srax14IqM...
Because you get done faster.
I have no doubt any experienced C programmer could beat a k solution in run-time performance, but the k programmer will always be done faster.
> proponent give some examples of practical applications written in these array languages?
Databases are the most common: Building an API library to quickly answer questions about data is probably about the easiest thing to do in an array language, but isn't almost anything a database with a definition like that? E-commerce and storefronts, CRMs, flight trackers, and so on. In this way, I often suggest to people that the closest analogue is maybe something like SQL stored-procedures, but with a less-shit language. But this isn't exactly right.
Games are an interesting problem that aren't databases (for example), and a lot of games have vector-problems that have nice solutions in k. So let's play hangman.
If you don't know this game, we will only be playing with lowercase letters:
A:`c$"a"+!26; // A gets the characters cast [from] "a" + til 26
First, let's agree on a dictionary to use: W:0:"/usr/share/dict/words"
and I will only choose a word with at least 7 letters in it and make it lowercase
so you have a chance: w:_*1?W@&7<#'W; // w gets lowercase [the] first [of] 1 random-take [from the] Words [that/at] where 7< count each Words
Now when you make a guess: G:();g:{G::G,x}
I'll now tell you what you know, but you're only allowed N guesses. N:5
k:{@[w;&|/w=/:A^N#G;:;"."]}; // k gets a lambda, [that] amends w where the max-over [when the] word equal [to] each of-the Alphabet without [the first] N [characters] taken from the Guess
That's it. You keep guessing until you guess the word, or you run out of guesses. g"e";k[]
"...e..e..'."
g"s";k[]
"..se..e..'s"
It's a silly game. I wrote comments above (with // characters so they should be easy to spot), and I now want you to take a look at them.The comment is what I "read" when I am reading the k stanza. The square-brackets cover words (prepositions mostly) that help make it sound more like English, but look at the other words too: x=/:y is x equals each-of y. That's all it is. I am reading it and writing it that quickly. Yes it takes longer to write and read the English, and of course, any non-array language will be a lot more code to read and write as well.
That's what I think the value is in an array language: It's just so clear once you know how to read and write it, that you are simply faster. And being clear means the computer does what you expect (usually on the first try!) and so the programmer gets on to the next problem sooner.
I've written ad servers and presentation tools in array languages; I don't think there's anything I can't write (after all, almost everything is a database or a game if you squint hard enough), but there's a lot I wouldn't: I did an MP4 decoder in JavaScript once (to autoplay ads on iphones back when they blocked video playback in iframes) but I would never say JavaScript is the right language to write MP4 decoders. Array languages are tools in your toolbox -- like JavaScript or any other -- and you should try to put as many tools in your toolbox so that you have the best chance of using the right tool for the job.
In my experience it's very good at quickly developing real-time analytics applications with only a small set of developers. A couple of q developers can develop, maintain and operate the server side of 5 or 6 separate applications without breaking a sweat. Changes come in at a high speed too.
It's a highly interactive language. A bit like a lisp, you start up a q process, open a port and then you iterate and update your application live without needing to restart. Typically on our projects we've had a well iterated program running in QA for a day or 2 before opening a PR (which becomes more of a formality for getting the solution to the problem into prod at that stage).
The q language itself is quite wordy. Check the reference page: https://code.kx.com/q/ref/ Many programs written in q consist mainly of the key words with the special operators interspersed. Also see some example libraries: https://github.com/finos/kdb
It's been a fairly stable language to work with, having few breaking changes between successive versions. q code written 8/9/10 years ago on older versions will most likely still run the same today. We have source code on one project at work which hasn't had a code change in 6 years now (despite moving through different versions 2.8->3.0->3.3->3.5->4.0) and it runs daily without a hiccup.
Mostly it's a joy working with it because I feel like I get to tell the computer what I want it to do, without also having to tell it how to do it.
Is q mostly just longer aliases for k verbs or do the semantics differ?
That said we do make heavy use of the functional form of querying tables (https://code.kx.com/q/basics/funsql/#select) in the more complex parts of our systems. The toolbars in the GUIs allow users to select a wide range of possible ways to request data. It's a lot easier to dynamically generate the functional format of the different parts of a select query than it is to try and play with manipulating lots of stored procs. Anyone with experience in a LISP would be familiar with this way of manipulating code as data in this manner, since it's a similar concept.
Some would say this is k, not q and the lines are probably a bit blurred here. Either way there's no question that doing so has made things more productive.
As an aside, there's no performance difference between using k and q. Most of the q keywords are implemented in k. Programs written in k do look quite different to those written in q, even if you stick to the mantra of one thought per expression, one expression per line.
Myself, I used to only like q since it was easier, especially when I started. My only programming background was C# and Python; q made it easy to get into the different paradigm of the APL family. Now, after years working with it, I'd prefer to use k where-ever possible. The brevity is nice. When you write something non-trivial you see a lot of the same patterns of characters on the screen. And it just feels better to write one character for | instead of typing out reverse.
Personally I'd prefer to go with Arthur Whitney's advice from an interview he did years ago (that I can't find a link to unfortunately). He basically said work in k until you need to do big database work with kdb+, then pull in q. Convincing the team and management to let me do that is probably a lost cause though.
I work in finance, and literally all of my employers used it. Not much secret sauce, just simple algorithms implemented very well. No real open source competitor. Well, maybe DuckDB if they support as-of joins.
An issue in writing a thoroughly helpful response, is that successful APL and K implementations are usually applied in a largely corporate and proprietary context.
I lack a list of applications to link which you could look at.
However I'd still say APL/J/K applications require vastly less resource, and initial investment than most tools whilst providing on-par or greater computational power.
A couple of years ago I worked on a non-trivial APL application with one of my university professors and another student. We were trying to build a CPU simulator flexible enough to handle stuff ranging from PDP-11 up to Intel x86. The goal was to run some analysis on memory accesses performed by the x86 architecture. Quite an interesting project in which I worked on for around two year.
The code is still available if you're interested: https://github.com/emlautarom1/PDP_11_Simulator
The first implementation was done in APL using a book which I don't remember as reference. We had a couple of meetings where we learned APL and the general idea behind the design. Pretty soon we started to deal with a lot of issues like:
- We only found two implementations for the APL interpreter: GNU and Dyalog. GNU is free but pretty much abandoned. Support for Windows was (is?) nonexistent. Dyalogs version is proprietary so we couldn't use that (even when a "student" version was available).
- You had to use a special keyboard layout since APL uses non ascii characters, which was only available for Linux. Every time you wanted to write some operator I had to look it up in a paper sheet. Eventually you start memorizing, but it was a pain in the earlier days.
- There is literally no community support. You can't just 'StackOverflow' some APL stuff.
- Dynamic scoping + dynamic typing make working on a large codebase pretty much impossible. You don't know when things are defined, and you don't know what they are.
- The language is extremely terse. I remember that a single line of code was able to fetch, decode and execute instructions. You're incentivized to write this kind of code, and even if you're able to understand all operators you still need to figure out the semantics of the code. For reference, I work with Haskell everyday and it looks like Java compared to APL.
- The code tends to be very hacky. You (ab)use the fact that most things are arrays and solve all problems using some form of indexing/map/reduce. You tend to forget about proper conditionals or custom data types. Domain modeling is pretty much non-existent.
- There is no built in support for test, and we could not figure out how to use a third party library for that (is it even possible to use third party code?). Our tests consisted in a lot of code that checked some conditionals, and then we printed "Pass" or "Fail" on each. Very primitive stuff.
- No debugging at all. You run the code and pray for the best.
A year after we started my classmate decided to drop the project since he felt he couldn't keep up with the complexity: each line of code was non-trivial and really hard to understand.
Eventually we had to rewrite the whole project because GNUs interpreter didn't support big integers, and trying to circumvent that resulted in very poor performance. The new version was written in Julia (https://github.com/emlautarom1/Julia_Simulator), so we were able to reuse a lot of "array code". The project got cancelled in the middle of the rewrite and we kind of forgot about it.
I'm not sure why you couldn't use the student version of Dyalog? Sounds like it would have been fine. There are also many more FOSS implementations of array languages now, such as ngn/k and April. https://github.com/phantomics/april
'only available for Linux' - not true https://github.com/abrudz/Kbd/ and others (also different input modes like `w for ⍵)
'no community support' - on the contrary there is a big and helpful APL community https://aplwiki.com/wiki/Chat_rooms_and_forums that is (imo) more useful than stackoverflow
'Dynamic scoping...' - Dyalog's (and other APL's) dfns have lexical scope.
'The language is extremely terse' - is this meant to be a bad thing?
'The code tends to be very hacky' - maybe if you write bad code or try and write C in APL (it won't work)
- I see that support has improved. I didn't find any keyboard support for Windows at the time. Still, dealing with a different keyboard layout was a total pain.
- I wouldn't call the APL community "big". The're are around 2K users combining all of those platforms. Now include the language barrier (I'm from Argentina) and go back a couple of years and you can see the issue.
- The APL version we were using had dynamic scoping. TIL that there are multiple variations of the same language with totally different semantics!
- Yes, that level of terseness involves hacky code which is hard to understand, review and mantain. This is 100% my opinion.
Overall I wouldn't recommend APL or derivatives at all for any serious project.
Someone here has to post ngn’s survey of K languages: https://ngn.codeberg.page/k.html
oK is also modeled on K6 and its manual comes highly recommended.
In this specific instance, I suspect the folks who enjoy writing (and assuming they actually can - reading) code like this, completely assume that everyone has a brain with the same kind of weird quirks theirs has, namely the ability to recall almost instantly infernally long minutiae of details and thereby decipher what most people perceive as pure noise.
Or, more generally speaking, they assume that their potential audience essentially are as smart as they are.
News at 11: this is almost never the case.
And in the case of: this type of language, APL, LISP, functional programming, quantum physics, etc ... your favorite topic/programming language/hobby ends up bound to be confined to a tiny bubble of folks that are like you instead of gaining popularity.
There's a whole genre on YouTube of videos of people doing day-to-day work with skills that seem utterly superhuman, with names like "Fast Workers #230" and "People are AWESOME 2020", like https://youtu.be/YmkPoiEcgJM. Actually, though, if you practice almost any skill every day for an hour or more, working diligently to improve, after 20–40 years your ability at it will seem superhuman, even if you're average intelligence or slightly below. (Unless it's a professional sport, in which case people will be mentally comparing you to Lionel Messi or Tiger Woods, and you won't get that good. Or a popular hobby like knitting.)
It definitely does not require 20–40 years of effort to understand quantum physics or code written in K.
— ⁂ —
Now, suppose that it were true that reading poetry written in Volapuk (or whatever) were a niche interest because of some essential feature of Volapuk that inherently limits it to a small group, rather than because learning Volapuk takes time that most people haven't put in, for the standard diffusion-of-innovations reasons. Would that be bad? Would it mean that people writing poetry in Volapuk had an "utter inability to 'read the room'"?
I don't think so—to attribute their choice to do so to such a cognitive handicap, you are presupposing that you understand their motivations, and that those motivations include maximizing the popularity of their creation.
But it should be obvious upon a moment's thought that plenty of poetry, and code, is written with no thought for participating in such popularity contests; it's written for an audience of one, or two, or forty-eight. Perhaps the majority of poetry and code. So writing it in Volapuk, or K, may actually be a rational strategy if it appeals to your intended audience—not an error resulting from a mental disability, as you claim.
More generally, quoting Chip Salzenberg:
> It's usually a big mistake to assume that a number of experts on a given subject disagree with you because they don't grasp the true situation.
Probably, but then: I spent close to a year of my life writing "software" in APL.
I hated every second of it, especially the part where I'd need to zoom to the bathroom and come back 5 mn later not being able to understand how the last line of code I wrote worked.
I can't even imagine what it would take today, or to the poor soul who inherited the code.
The code I've looked at here reminds me exactly of that time.
Boy would I never go back to doing stuff like this.
Is it possible the software you were working on was shitty in a way that wasn't essential to APL?
https://ngn.codeberg.page/k.html
Note that ktye/i is actually public domain, not proprietary as that page says.
Has anyone run code like this under gdb?
The tutorial does help a fair bit, though glossing through it, it doesn't really explain why it has to be so exceptionally terse.
I mean the matmul[1] sure is impressively short in the end, and with a background in computer graphics and simulations I can absolutely appreciate working on arrays rather than singular values. But I'm sure one could get the same computational result with a bit more approachable syntax.
[1]: https://github.com/razetime/ngn-k-tutorial/blob/main/c-think...
git diff --word-diff=color --word-diff-regex=.
It highlights only the parts that have actually been changed/added/deleted.