439 points · by kick · 6y ago · 422 comments
design goal: speed
write fast, run fast, modify fast.
minimize product of vocabulary and program size.
https://a.kx.com/a/k/readme.txt comprehensive programming environments
(programming, files, comms, procs, ...)
are depressingly complex.
commonlisp, c/lib/syscalls, java, winapi
are all in the 1000's of entry points.
many with multiple complex parameters.
with k we try to do more with less
in order to write correct programs faster.
https://web.archive.org/web/20041024065350/http://www.kx.com... > Just curious, but does the state of California charge you a large tax
> for each character in a variable name?
yes.
we also try to fit our algorithms onto licence plates.
https://web.archive.org/web/20040823040634/http://www.kx.com...For some 'licence plate' K algorithm dissections, you might like this Twitter account:
print<>!~($/=$")+2*map 1..$s{$_%$'}++,<>I can easily skim thousands of lines of Perl and Java in seconds and have a rough idea of what the code does. Reading K, however, requires careful and deliberate attention to every single character. I found it useful to maintain documentation on how to /read/ the code (almost a literate programming approach).
I write a line once for a 100 times I read it.
Conifer forest
Vs
Pine Pine Cedar Spruce Pine Cedar ...
Also it has (or had, maybe they fixed it) a bunch of weird quirks, like "sum foo" skipping all the NAs in a list while "+/foo" didn't, resulting in NaN. (Or maybe it was +/ over an int array didn't work while a double array did. I forget.) Arrays of dicts were immediately turned into tables, which didn't work the same as an array of dicts, etc.
But, yeah, it's not crazy implementing things in q/K, as long as they're mostly linear things. Trees are hard, iterative methods are hard, and it's really hard to skim code, other than to just rely on names and comments.
q)a: 1 2 3 0N 3 4
q)sum a
13
q)+/[a]
13However, I still find it problematic, and it's not really about the language itself: it's more about how it's promoted in the article, by the people in this thread, and in general. Specifically, the claims it's perfectly readable, and anyone who says anything otherwise is either stupid, lying, or too poor to understand it are not useful. (Yes, you know who you are for that last one. You're not helping your case.) The fact of the matter is that most programmers are used to ALGOL-esque syntax, and there is significant value in being able to lift concepts and interoperate between those languages at a superficial level. Every "inspired" languages hits these issues, depending on how "strange" it is: Objective-C is ugly, Lisp is alien, and on the far end APL derivatives are simply labelled as unreadable. That doesn't mean they're bad languages, but to those promoting it: drop the attitude, and understand why we have reservations. Your language isn't the "true" way to program, that only the chosen elect can understand and lecture us on. Don't ignore or gloss over languages that have similar features to yours. We want to hear what the interesting things are that you can do in the language, actual guidance for how we can adapt to the language (not: "one-letter identifiers are just what we do; deal with it"). Thanks.
It's like learning Chinese. Everyone learns it in China, and everyone there will tell you that it's perfectly readable and you don't need to be extraordinarily intelligent to speak it. But if you expect to figure it out based on your knowledge of English, it will be terribly frustrating. This does not mean that German or Dutch (which share roots with English) are better languages, or even easier to learn. Do not expect your Chinese teacher to give you a different answer from "these weird symbols are just what we do; deal with it".
This article is quite good. Clearly the author understand your reservations and he is saying: give it a try and it will click. The learning material might be better, but it's there (start with Iverson and work from that). It's much easier than learning Chinese!
I'm not sure Chinese is necessarily a good example for the point you're trying to make.
Native Chinese speakers _probably_ spend more effort acquiring full competency in Chinese than native English speakers need to learn English. For one thing, reading and writing is harder to learn, even for natives (source: am Chinese and haven't acquired full literacy, despite years of half-hearted effort).
English is generally easier to learn, not only for German and Dutch speakers, but for most people in the world who speak languages that are unrelated to both of them.
One hypothesis[1] is that English has been learned by foreigners multiple times in the past and slowly lost it's more difficult native features (noun declension, many forms of inflection). Chinese has tones, which are rare amongst world languages and, as many learners will tell you, difficult to achieve proficiency with as as an adult.
On a practical level, the British and Americans have had hegemonic influence over the world for about 2-3 centuries, so many idioms and concepts in the language will be familiar to a learner; less so Chinese, which is far more coupled to the culture of China and its history.
Like, every schoolchild in China learns a bit of Tang poetry as part of their education, and 成語 idioms are part of daily speech across all social classes.
https://en.wikipedia.org/wiki/Middle_English_creole_hypothes...
The claim that noun declension and inflection is harder to learn isn't well founded. If your native language has these, it'll be more natural for you. All languages have semantic declension and inflection, in the sense that context signals the kind of each word even if it's not syntactically inflected. For example in English the position of the word can signal whether a word is an object or subject "John hit Sally" vs "Sally hit John", the order of John and Sally signals who hit whom. In an agglutinate language you could signal this by putting a prefix like "John hit Sallyum" or "Sallyum hit John" would be parsed the same. My native language is Turkish, I've been learning English since I was 5 years old, but this "order matters" thing eternally confused me. It doesn't make sense to me when people say suffixes are more confusing than this order thing.
Ohoh, this line sparked a thought in my head:
"English is the JavaScript of human languages."
> ..slowly lost it's more difficult native features
That may be true of creole and English spoken as a second language (which, I believe, is more dominant in the world than English spoken by natives). Maybe also true about losing inflections, thank goodness, that surely must have made the language easier.
On the other hand, English as spoken by natives do contain plenty of quirks, exceptions, phrases that don't make sense explicitly (with implicit meaning you have to have learned/memorized)..
Microsoft's sample application "Your First Windows Program", written in C, using Win32 calls, can be translated into TXR Lisp literally, almost expression for expression:
https://docs.microsoft.com/en-us/windows/win32/learnwin32/yo...
The "meat" part, without the FFI declarations that precede it:
(defun WindowProc (hwnd uMsg wParam lParam)
(caseql* uMsg
(WM_DESTROY
(PostQuitMessage 0)
0)
(WM_PAINT
(let* ((ps (new PAINTSTRUCT))
(hdc (BeginPaint hwnd ps)))
(FillRect hdc ps.rcPaint (cptr-int (succ COLOR_WINDOW) 'HBRUSH))
(EndPaint hwnd ps)
0))
(t (DefWindowProc hwnd uMsg wParam lParam))))
(let* ((hInstance (GetModuleHandle nil))
(wc (new WNDCLASS
lpfnWndProc [wndproc-fn WindowProc]
hInstance hInstance
lpszClassName "Sample Window Class")))
(RegisterClass wc)
(let ((hwnd (CreateWindowEx 0 wc.lpszClassName "Learn to Program Windows"
WS_OVERLAPPEDWINDOW
CW_USEDEFAULT CW_USEDEFAULT
CW_USEDEFAULT CW_USEDEFAULT
NULL NULL hInstance NULL)))
(unless (equal hwnd NULL)
(ShowWindow hwnd SW_SHOWDEFAULT)
(let ((msg (new MSG)))
(while (GetMessage msg NULL 0 0)
(TranslateMessage msg)
(DispatchMessage msg))))))
Full code here: https://www.nongnu.org/txr/rosetta-solutions-main.html#Windo...If you look at this and the C side by side, you can easily see where the parts match up.
It's not really meaningful to compare the readability of sentences in English versus Chinese. On the other hand, it's both meaningful and important to compare readability of program snippets - and readability is more than just the first-time learning burden.
Overly-concise code being difficult to maintain is a well-accepted fact. The response shouldn't be to demand fluency - that's just sticking your head in the sand.
> Overly-concise code being difficult to maintain is a well-accepted fact.
Your well-accepted facts do not apply to this totally different paradigm. You seem to think those well-accepted facts are universal. They are not.
I have spent the last two years learning about array languages and think it is a fascinating topic, so I tried to give some advice (based on my own experience) to those who want to make the same journey. My point is not that you need fluency (you need some fluency to understand anything complicated), it is that the fluency you have in other languages may be counterproductive. Your comment is an excellent example of this.
Try to read a tutorial. Rewrite it using "meaningful names". All we have done that at some point, and all we started finding the sort names more comfortable to work with after a while. Don't take my word, give it a try.
Many seasoned APL/J/K programmers state that conciseness is an asset. I would trust their judgment on that. There are ways in which that and the quoted statement could both be true at the same time.
it is if one speaks both languages and is qualified to comment. part of 'overconciseness' is domain/cultural experience - what is overconcise in one context is not in another.
I like the choices of primitives in K and the novel ways they can be combined to do things more efficiently (and with fewer pieces!) than you may expect. Good examples are 'where' (&), the grade twins (< and >), scan (\), and eachprior (':).
I love the adverb syntax: each (') lets you map a function over a data structure with zero syntactic effort, and 'over' (/) and 'scan' (\) make reductions trivial.
With regards to an on-ramp, I started with John Earnest's oK REPL and did a bunch of Project Euler and Advent of Code problems. I then moved to trying to understand the examples on kparc.com. I then converted a spreadsheet application from JS to k7. In all of this, John's documentation was essential.
For me, having single variable names isn't paramount, but in some cases - particularly functions - I can see it helps to 'drive' your mind towards finding simpler ways to do things. It lets the characters that do the 'real' work come to the forefront.
You also would be much better off learning X's idioms. These are standard ways of saying something. They're standard for a reason - because they work, and because everybody understands them. If you can't read them, then a lot of code is going to be difficult to understand.
That's just table stakes for using X. If you want to use X, but don't want to learn the syntax and the primitives, then you don't really want to use X. You may want the benefits that you think X would get you, but you don't actually want X.
Now for the other side: If you're a proponent of X, you need to remember that many languages are magic within certain domains, and anywhere from "meh" to horrible outside it. Take K, for instance. I'm pretty sure it wouldn't be a good fit for most embedded systems. I'm fairly sure it wouldn't be a good fit for web programming. I'm not sure I'd want to do text processing in K. So it's not "the one way" (except possibly within certain domains). It's not "the way of the future" (except possibly within certain domains). It's not "what all the smart and enlightened people are using" (except possibly within certain domains). And, unless we're working in those certain domains, it really isn't all that important whether the rest of us learn it or understand it.
I suspect that looking like C or ALGOL would not be all that useful for K (or Lisp, or Haskell, or Forth). The semantics are too different. A surface similarity in syntax isn't enough to bridge the gap in a meaningful way.
Yes: It is perfectly readable once you know how, and anyone who says anything otherwise is just plain wrong. Including you 58 days ago.
I don't know if you are wrong because you are lying, or you believe this because you are stupid. I wrote off at the time that it was well-meaning ignorance, but it doesn't really matter: The key thing, that is, the thing holding you back from reading it, is you.
I believe you can learn to read it and read it as well as me as quickly as with a few months of study. If you think anyone else is telling you otherwise, ignore them.
I don't believe you need to not be "poor" to do it - everything you need is available to you.
It's all about whether you want to do this or not.
> Every "inspired" languages hits these issues, depending on how "strange" it is: Objective-C is ugly, Lisp is alien, and on the far end APL derivatives are simply labelled as unreadable. That doesn't mean they're bad languages, but to those promoting it: drop the attitude, and understand why we have reservations.
We understand because we were once you: Every X-evangelist you're talking to (where X is Lisp, or Objective-C, or in this case K) was once like you in at least the way of not knowing X, so we know you are wrong in a way (as we now know X) that you simply cannot comprehend yet. Think about that. Maybe re-read Paul Graham's blub article and appreciate really what it means to be the blub programmer.
Many K programmers have some familiarity with APL. Some (like myself) have used Objective-C and Common Lisp (I've got over a decade of professional history in CL), and loads of other languages. Until you learn K, all you have is our testimony; our gospel that this is worth learning. You can literally do anything in blub, being able to do it easier is the point.
Now do the same with well-written, verbose C-style or Python code (no shorthand/abbreviations, no lambdas, no ternary notation, etc.).
Shorthand code in any language is bad in the long run because it's unmaintainable except by people who work with it on a regular basis. You are making the same arguments as Perl fanatics who used every possible abbreviation in their language 25 years ago. How much of that is even comprehensible now without a major reverse-engineering effort?
Perl is inscrutable in a different way: It is impossible to insert an instruction reliably into a statement allows the student to observe what is going on without changing it: Program flow can change mid-sentence. This isn't true of K.
> Take a break from K (or any other shorthand language of your choosing) for a year or five, then come back and try to figure out what the code you wrote when you were using it frequently is actually doing.
I've been looking at K code for more than five years at this point, and I don't have any problems reading code written by K programmers a decade ago or more.
I think you're completely wrong about this.
Then it's not perfectly readable. That, or your definition of readable is useless because then any programming language is readable given enough study time.
> being able to do it easier is the point.
I still haven't seen any example where it is actually easier. Shorter? Yes. Easier? Very debatable.
Given a fragment of Chinese, if you do not know Chinese, would you say it is unreadable?
What possible definition of "unreadable" could you have that would make that a useful statement?
No, I don't think speaking to a language as being "unreadable" is particularly helpful. A very careful reader might interpret your claim that "K is unreadable" as "gjulianm can't read K" but I wonder what exactly is the point of even saying it in the first place? Maybe you mean "approachable" -- a fully reasonable statement, but one reflecting your inability to say anything else meaningful about it.
On the other hand, if I know Chinese, it's entirely possible for me to point to a gibberish statement (for example, on a tattoo), and say that it's unreadable. I'm definitely referring to something else here.
Now maybe we just accept having two different definitions for "readable", but I think yours has real harm. I think referring to something that you do not understand with the same word that means nobody can understand it might confuse people, and I just cannot understand for the life of me, why so many programmers would want to intentionally confuse people like this.
If I pick up some random K code, I can read it. I could make a change to it, and other K programmers will understand what I did and why. That's good enough for me.
> I still haven't seen any example where it is actually easier. Shorter? Yes. Easier? Very debatable.
I think the max of list example is a good one. I've also previously observed some examples that might be less mathematical.
[1]: https://news.ycombinator.com/item?id=22467866 - Here I beat a custom "database" by 50x with one line of q (a very similar language to k)
[2]: https://news.ycombinator.com/item?id=21799376 - A six-character solution to the rock-paper-scissors game, using q to analyse the creation of the solution
[3]: https://news.ycombinator.com/item?id=21680743 - Here's our friend the bin operator again, showing how it appears in production.
[4]: https://news.ycombinator.com/item?id=19659590 - One of my favourite k/q features is views.
[5]: https://news.ycombinator.com/item?id=16851862 - String parsing is "obvious" in k/q where it isn't in other languages
In these cases (and many others) q/k is "easier" because it gets the job done faster. If you can beat my k with your JavaScript then good for you (And I'd like to see it! I can always get better!), but I usually can't. I find the solution faster with k, the program runs faster with k, and those are the things that matter to me when I say "easier".
I absolutely do not mean "more approachable".
It doesn't increase linearly though. #:'=: is seven characters that mean as much as 68 separate lexemes in lisp:
(defun count (list)
(let ((hash (make-hash-table)))
(dolist (el list)
(incf (gethash (cadr el) hash 0) (car el)))
(let (result)
(maphash (lambda (key val)
(push (list val key) result))
hash)
result)))
so you don't need all that. You don't even bother to create that "helper" function because you don't need it.The choice of operators (and their definitions) was made with great care in an effort to maximise this effect.
The hashing stuff feels a little "bolted on" in ANSI CL. Add-on libraries can round out the functionality.
In another dialect, TXR Lisp, the whole (let ...) part above reduces to this:
(hash-pairs hash) ;; get key-value pairs as two-element lists
such a function could be had in ANSI Lisp.To reduce a sequence into a histogram returned as a hash in TXR Lisp, we would do a group-reduce
[group-reduce (hash) identity (op succ @1) INPUT-LIST-HERE 0]
The idea here is that the input items are projected through a function (here specified as identity, to take the items themselves) and grouped into buckets by the projected value.Within each of these buckets, an independent reduce (i.e. left fold) is going on, whereby a hash table holds the reduce accumulators.
For maximum flexibility, group-reduce asks the caller to specify the hash table rather than making one implicitly; hence the (hash) argument.
Likewise, the initial value for the reduce (shared by all the buckets) is specified explicitly. reduce is too general a concept to justify making it a defaulted optional argument that goes to zero.
Here, we somehow abuse reduce. We start the accumulator at 0, and at each reduction step, we ignore the new value coming in, and instead produce the successor of the accumulator as the new accumulator value, so all we do is count the reduction steps in each bucket, thus producing a frequency histogram.
(op succ @1) is needed rather than succ because the function it denotes takes two or more arguments (it gets called with two), whereas succ requires exactly one argument. If succ ignored arguments after the first one, it could be like this:
[group-reduce (hash) identity succ INPUT-LIST-HERE 0]
But relaxing the checks on the number of arguments in library functions for the sake of code golfing isn't a good idea. Further, if the function constructed the hash implicitly, and geared toward numeric processing, making the default accumulator zero, it could look like: [group-reduce identity succ INPUT-LIST-HERE]
and if we cripple group-reduce by taking out the projection we can get it down to: [group-reduce succ INPUT-LIST-HERE]
Basically, Lisp can be succinct to the point of diminishing returns, if you have the right set of functions for the task at hand.The traditional, mainstream Lisps assume that the developers will make these for themselves, especially for tasks outside of list processing.
The one where shallow and social compatibility is seen as important.
The one where depth and seemingly looking sharp concepts is important.
If you care about your devs only be able to read some business logic then good, syntax familiarity is great. If you care about advanced problem solving, this is unimportant. And people prefer to iterate concise formulas presenting powerful concepts rather than instance-level readability (as in overlyVerboseNamingSchemes)
Could K become a general purpose language? Maybe, but it always strikes me as odd that that feasibility as a mainstream language comes up so frequently when K is discussed. It's not the high-order bit of the conversation.
The idea that concise formulas provide this (and that more modular solutions can't) appears to be a conceit.
+ / ! 1000+1. All of these "compact" languages (I'd even extend it to Perl to some extent, the way some write it), are seriously lacking in the ergonomics department. Sure, J Leet Hacker might have no problem parsing pages of the stuff. What about the coworker with dyslexia, ADHD, vision problem, etc?
Even if you aren't, what are the real gains? It seems resistant to tabcomplete, git diffs are probably near-inscrutable, grepping for snippets is probably an exercise in judicious application of backslashes... it's cute, but I don't see where this holier-than-thou is coming from (not that ANY language justifies that attitude)
Edit: oops, touched a nerve, I see. I'll add to the above the 7 +/-2 rule [0]. Sure, lets say even you COULD write a program in 1/100th or 1/1000th of the lines in k. I don't WANT a source code that looks like that. Way too much information density.
I'll give them this: perhaps the criticism is that ALGOLikes are too sparse, could stand to be denser, and k is the manifestation of the far other end of the spectrum.
- https://en.m.wikipedia.org/wiki/The_Magical_Number_Seven,_Pl...
Beyond a point however, I cannot read my own regex's after a month's absence. Which is why I use perl's /x modifier extensively to split up regex components onto multiple lines and to document them thoroughly, even if they are for throwaway scripts, because I don't always throw them away!.
For example:
$_ =~ m/^ # anchor at beginning of line
The\ quick\ (\w+)\ fox # fox adjective
\ (\w+)\ over # fox action verb
\ the\ (\w+) dog # dog adjective
(?: # whitespace-trimmed comment:
\s* \# \s* # whitespace and comment token
(.*?) # captured comment text; non-greedy!
\s* # any trailing whitespace
)? # this is all optional
$ # end of line anchor
/x; # allow whitespace
(source: https://www.perl.com/pub/2004/01/16/regexps.html/)This is where K fails me. It may not be a fault of the language, but everyone in the community has bought into this strange idiomatic style. I can't imagine debugging it, or checking it for correctness, or foisting it on a less experienced developer. Here's a canonical example an xml parser, on their website.
https://a.kx.com/a/k/examples/xml.k
Where's the pedagogy? Where are the comments? Why is this line noise considered acceptable?
> Where's the pedagogy? Where are the comments?
Most of that document _is_ comments. There's a comment on almost every line, very similar to your perl example. Comments begin with a "/" character which doesn't have a function to the left (e.g. whitespace).
First we have some constants (L,W,B,S,R) which refer to the left-bracket, whitespace (which includes blank), blank space, and slash and right-bracket. We've also got some utility functions (cut;join). These are simple enough they don't require any special explanation to the K programmer who reads this.
Then we have a function that produces an xml-entity from a character. The author assumes octal is required, so (needlessly) converts to that. The octal string (with a leading zero) is concatenated onto ";&#" then rotated so the ";" appears at the end (1! is cute). I would probably write this differently, because: 1!";&#",$_ic is shorter.
We then have a function that does the reverse, cutting off the first three characters after rotating (which is the ";&#" string again) and converts the octal digits back into decimal. This is probably wrong because real XML documents will probably prefer decimal entities, but perhaps the author wasn't dealing with these. I would certainly write this differently if I changed oc (as above).
Now we have the helper function xc and cx (whose names suggest they are converting from character-to-xml and xml-to-character respectively). This is a stylistic observation, we can also see this from the comment, or by reading the code (if we know what XML is). These implementations are pretty basic, just using ssr to do repeated search/replace on the entities (note that ssr knows that ? character means any).
You get used to it.
> Why is this line noise considered acceptable?
One major challenge reading inscrutable perl scripts is knowing where the execution begins. Perl just has so many rules for parsing it you really need either wizardry or patience to know how to pull it apart, but K is extremely regular: there's only one way to parse it, and shortly after learning it you also learn (quickly) you can insert trace statements that don't change the meaning of the rest of the statement to learn a new operator (or a new use of an operator you didn't know). I note this especially as it is extremely hard to do in perl (and even other Iverson languages including APL and J).
Line noise is a subjective quality that goes away (at least in this case) when you become more fluent in K. I don't believe this is necessarily true of all compact languages though.
I've read a lot of human oriented, commented code which meant nothing to me, because the overall state space / architecture was fuzzy.
Whether it's a oneliner or a framework, readability is quite secondary IMO
ps: this also connect to the mathematician views about naming vs structure.. names are mostly arbitrary, it's the structure that drives the logic and the device.
$_ =~ m/^ # anchor at beginning of line
The\ quick\ (?<adjective>\w+)\ fox # fox adjective
\ (?<verb>\w+)\ over # fox action verb
...While I can understand how that code can be intimidating to a programmer with a more “traditional” background… there are 26 (non-empty) lines of comments, and only 15 lines of code.
In this context, "intimidating" and "less tradational" are euphemisms that stem from cognitive dissonance reduction.
You don't have to like it, but the existence of K, et. al. shows that most of us are wasting a huge amount of time and energy using bad tools. These things are so powerful and not that hard to learn.
This little system runs circles around entire sub-industries of other software. The fact that it exists and uses one or two orders of magnitude less time and code than other systems is significant.
It's like axes vs. chainsaws. If the job is to log a forest the latter will be better than the former.
If people can make working, maintainable software other ways, particularly if those other ways have large, established ecosystems of dependencies, then they are likely doing it right regardless of how much you like apl.
The example with a for-loop for summing a range is a blatant strawman. In which modern language would that be idiomatic?
Furthermore the examples only show a particular use case: Processing lists of numbers. How does the benefits measure up for all the other stuff a million-line program does?
That said, if you really have a million-line program doing mostly numerical processing, then I'm sure it would be a massive benefit to switch to a programming language optimized for this task.
Golang?
Oh, you said modern. Never mind.
It adds up! Consider something like this:
(defun count (list)
(let ((hash (make-hash-table)))
(dolist (el list)
(incf (gethash (cadr el) hash 0) (car el)))
(let (result)
(maphash (lambda (key val)
(push (list val key) result))
hash)
result)))
That's just #:'=: (defun count (pair-list)
(let ((hash (make-hash-table)))
(loop for (val key) in pair-list
do (incf (gethash key hash 0) val))
(loop for key being the hash-key of hash
collect (list (gethash key hash) key))))
This drops us from 10 to 7 lines, which is clearly shorter. But, it's also relatively simple to change it from summing a list of (<count> <key>) to a list of (<key> <count>), something that I genuinely can't comment on for the K version. I suspect it would be as simple as first doing a permutation on the input, and (if needed) un-permute the result.But we can play this game both ways. What's the K for (Counter(a) & Counter(b)).most_common(3)?
I’ve personally found 20-30x compared to Java - admittedly not the most compact language.
In a 'code golf' language where you reduce a 1 million line program to 1000 lines, the 1000 line program is going to be just as hard to read. More concise syntax doesn't help as the same number and complexity of concepts are going to exist in both programs, and that's what the human has to understand.
There are languages where more powerful concepts are available for less code. Erlang for instance, with concurrency. In those cases, yes, readability is aided and maintainability is improved.
[1] https://www.sciencemag.org/news/2019/09/human-speech-may-hav...
Claim B: The intelligibility of a computer program is proportional to its complexity of the problem it solves, not to the number of characters in its source code.
First off, I don't see how B follows from A.
Secondly, even if there does seem to be some similarity, one of the reasons any comparison breaks down is that human languages are evolutionarily adapted to our cognitive capacities, whereas programming languages are designed, for the most part without a very rigorous understanding of how they interact with our cognitive capacities (this is an active area of research, but not very advanced, I think.)
Finally, I reject claim B. The intelligibility of a computer program is heavily affected by how clearly the underlying concepts that define a solution to the given problem are mapped into the structures available in the given programming language, and that is obviously heavily affected by the choice of programming language. And I believe that in general more concise languages are more concise precisely because they make available more and more straight-forward mappings from problem-space to language-structure space. So more concise languages make it possible to write more easily comprehensible programs once you are over the barrier of holding all the mappings they make available in your head.
> The intelligibility of a computer program is heavily affected by how clearly the underlying concepts that define a solution to the given problem are mapped into the structures available in the given programming language, and that is obviously heavily affected by the choice of programming language.
I don't think so. Nobody uses "just" a programming language. They use a generic programming language plus libraries (or DSLs) plus their own code that maps the concepts of their problem to code. Unless the problem to be solved is really generic and/or simple, a programming language alone is very very far of having direct mappings from problem to language.
And you can't escape the complexity of the problem at hand. You can hide it, but in this regard there's no difference between hiding it behind a compiler, behind libraries or behind your own code. You still need to understand the problem and the underlying concepts.
That's what they're designed for, but why does that mean they aren't also evolutionarily adapted to our cognitive capabilities?
When my assumptions about the underlying problem are wrong a million line program is much easier to fix than a thousand line one.
Or rather, a thousand line concise program in a quirky language will become a million line program in a quirky language when exposed to changing business requirements.
>Languages that are often derided as write-only include APL, Dynamic debugging technique (DDT), Perl,[2] Forth, Text Editor and Corrector (TECO),[3] Mathematica, IGOR Pro and regular expression syntax used in various languages.
We have this style in the programming world. It's called Literate Programming. How many K programmers write in that style?
More than you would think. I had a very nice gig at a hft years ago where we were using noweb+k extensively.
The only place were I edited source code by hand with paper, pen and paste.
A mathematical paper introducing some meaningful worker function uses English because mathematical notation is insufficient for describing computation. That's one of the important goals of Iverson's notation.
> We have this style in the programming world. It's called Literate Programming. How many K programmers write in that style?
Quite a few! I would actually suggest there are more literate K programmers than there are literate C programmers! Every 4-5 lines of code probably has 2-3 lines of prose in a large application that I work on, but in another language that might be something like 500 lines of code for 2-3 lines of prose which puts the prose offscreen for most of the code it's describing.
Some C programs will try to keep the prose-to-code density higher than that, but even amongst Knuth's code that's rare.
In your example, assuming that a million-line program is well done in its language, you'd have exactly the same complexity but now in a thousand lines, meaning that now each line does more, is more complex and changing it/understanding it is more difficult and prone to errors. It would be equally (if not more) impossible to understand.
If it were me, I'd choose the million-line program and keep the ability to understand parts of it and performing maintenance with just the program reference by my side, not the language reference too.
Disagreed. Reductio ad absurdum: It's not a good idea to force everyone to program in machine code, writing sequences of 1s and 0s. Why? Because the right abstractions (and associated notation) do make complexity more manageable.
Of course, assembly is far better than machine code. C is almost always better than assembly, because it maps better the mental ideas to code than assembly. After that, you have higher-level languages and then the change is not that clear. High-level languages tend to hide the complexity of dealing with the computer: in Python, JS, Haskell or K you don't need to worry about memory allocations, or how objects are defined, or how to pass arguments to functions. Sometimes you need to worry about that, and having a language that does that for you makes your program harder to understand (how does JS work with parallelism? When is an object an object and not a copy? Suddenly you need to know how does JS do certain things and that complexity reappears in your program).
Now, for the example, when I said that the million-line program is well done, I was thinking about some JS, Python, C++, or Java application without too much unnecessary cruft and that maps properly problem concepts to code concepts. If the 1000x line reduction (if that even exists) is done on the basis of smart one-liners, unreadable code and constructs and language-specific, it's not worth it. Say your application was a physics simulator of a certain situation. Most people would want the million-lines Python code where each function and each part is understandable and lets you focus on the problem at hand, instead of a thousand lines where you not only have a difficult problem but also a difficult code.
Especially so if you don't count library code, and I don't because otherwise you end up doing things like counting the number of lines of code that back the Win32 APIs in your program line count, which doesn't seem sensible. Most of the time we treat libraries as black boxes, except on rare occasions, so don't tend to think of them as part of "our" codebase[1].
Most million line plus systems are broken down into subsystems (applications, services, libraries, etc.) that in isolation are smaller, and in many cases much smaller.
Even with those rare million line of code monoliths, for the most part there's some level of organisation in the codebase: layers, subsystems, components, or a mixture of these and whatever else is appropriate.
This organisation, and particularly when coupled with modern tooling, facilitates the understanding of even very large systems.
I don't say that it's necessarily easy but, then again, neither is understanding a large, complex system implemented in K.
[1] Except when thinking about security because third party code has been shown to be a rich source of vulnerabilities.
Alan Kay' VPRI's STEPS project used PEG parsers to create math-like DSLs to in their attempt to go "from the desktop to the metal in 20,000 lines of code."
f:{11 22 33 x}
.[f;,1;:]
0 22
.[f;,4;:]
(1;"index")
If a signal is not trapped, K pauses execution and opens the debugger, where a user may interactively inspect the environment, evaluate code, and resume: f 4
index error
{11 22 33 x}
^
> x
4
>
Overall not that different from try...catch in a garden-variety interpreted language with a REPL.> If each punctuation character in the K is a separate part of speech, and you reverse their order
+ / ! 100
plus reduce range 100
This seems to be how this works.
Compare that to math equations like these ones:https://en.wikipedia.org/wiki/Maxwell%27s_equations#Formulat...
You would not expect them to read them like a paragraph. You are expect to read them symbol by symbol and unpack from the inner out.
K seems to be a dense language. Expect to read it symbol by symbol, not word by word or line by line.
If will be come more readable if you (1) slow down (2) get used to the programming patterns.
Not saying K is a good language or anything. But the frustration of the author seems to have more to do with impaticence and mismatched expectations than with flaws in the language itself.
As someone who has a bunch of letters before my name because of physics, no. You don't read physics symbol by symbol. You expand those symbols to pages and pages, meditate on those pages and achieve enlightenment on one small aspect of the problem. There is so much implicit state in those equations they are basically meaningless.
A nice book that deals with all the implicit state and terrible unclear notation used in physics: https://en.wikipedia.org/wiki/Structure_and_Interpretation_o...
So for the k/q/APL/array language gurus out there: in what situations would I not want to use k or another array language, if the relative obscurity of the syntax and mental model were not a factor (e.g., assuming you, your team (if any), and anyone who would ever look at your code would be very familiar with the language and idioms)?
I may not want to choose Go or Java because of latency concerns, or Rust because of compilation speed/iteration time concerns, or C/C++ because of safety issues, or Python/Ruby/Javascript because of performance issues. Why would I not want to pick k?
Also, think about distribution. With most of the array languages, it is commercial, so I'd be cautious about building a business around it. With other languages, it is free to use and deploy as you see fit and some have binary executables that don't need a runtime. K is very expensive. Dyalog APL is pretty reasonable, but still costs money to use and royalties in certain situations.
I think any decent developer can pickup array languages, but many won't want to as they'd rather have something more mainstream (Java, JS, C++, Python...etc) on their resume. So it might be difficult to hire.
Do APL/j/k/q work well for some performance-sensitive situations but not others? Some of the comments here by people who appear to be very familiar with the language make it seem like it performs quite well compared to the traditional high-performance languages.
Distribution is definitely something I hadn't considered; I guess I've been spoiled by the variety of free/open languages available these days.
I've always wanted to try to pick up an array language to expand my horizons a bit (e.g., that one bit of advice that programmers should learn one of the four main types of languages --- ALGOL-based, Lisp, functional, array-based), but I just haven't had the time.
Arthur Whitney's a biased source, of course, but the kparc site has a bunch of little programs in which he beats the equivalents from rather influential people (like the UNIX/Plan 9/Inferno authors http://www.kparc.com/z/bell.k ) for bragging rights.
k losing to some really nicely-written C and most Fortran seems plausible, Java and C++ not so much.
K/Kdb/q seems very happy with this state of affairs, which is really strange: if they O/S'd it I could see a lot of goodwill/mindshare going their way, but I think their Morgan Stanley roots view O/S as commie nonsense. Meanwhile, it's definitely viewed as legacy in the bulge-bracket banks that use it b/c it's so hard to hire for, not to mention its limited applications for teams (kdb is NOT a good multi-user database). However elegant it may be, it's doomed to be a COBOL if this is where its main userbase stays.
J is open source, but I can't get a handle on how battle-tested it is. It always seemed like Kdb was the real product that got used in anger.
Personally I think array-heads should spend more time with Haskell, since it has the ability to be massively terse and point-free, has type inference, loves infix gobbledygook, can be tuned for great performance, and is thoroughly open-source.
It's not too hard to grok: if they freed it, they'd lose money. $200,000,000 in revenue last year from Kx alone. Goodwill compared to cash, executive picks cash every time.
I have no idea what Shakti's doing, but they, too, are probably making a substantial amount of money.
but for once K makes me go "oh shit!" and not because of the craziness of its syntax... rather, if that syntax is so precise/terse, and even if to the outsider it looks fucking insane, does it have a wicked lower TCO because you literally have insanely less lines of liability in your code, libraries, dependencies, etc?
Is that the reason finance uses it, they maybe empirically know what the rest of us don't seem to grasp? Or just because it's so domain specific? Or... something else entirely?
Yes. q (a language and distribution of k4) has a built-in webserver with websockets, messaging, all types can be serialised over IPC (except pointers to C code) and most data structures have an efficient on-disk representation.
You might've recalled a few days ago someone announced a specialised database for doing "have-i-been-pwned" lookups in 49µsec. I wrote[1] one line of q that is about 10x faster:
[1]: https://news.ycombinator.com/item?id=22467866
It's just a single operation, and it's built-in, so maybe you think Python could just have mmap-efficient variables and a bin operator and you'd be there, but those things don't exist in Python. If I had the same problem as the author, it certainly wouldn't materialise as "custom database" of any kind, because I'd already be done.
In fact, one of the biggest challenges with "big data" is choosing an efficient representation. The author spent a lot of time on this, but my language just had one built-in. How much time? What's the target? I mean, if I've already paid for q it's clearly a no-brainer, but q isn't free either (even if you get it for no cost: you still need to learn it!)
> Is that the reason finance uses it, they maybe empirically know what the rest of us don't seem to grasp? Or just because it's so domain specific? Or... something else entirely?
Back in the day, k was the only thing you could put tick data into. Now there's lots of systems, and computers are a lot faster, so quants can use Python. Their code doesn't need to be "fast", but "fast enough".
My code still needs to be fast though.
There are non-terse APLs out there; the most obvious one floating around is Nial[1]. Culturally though, once you've figure out how to read and write in the compressed ascii runes, it's kind of hard to go back to the other way. J is actually denser because of the hooks, forks[2], rank and full tacit aspect of things. Personally whenever I've composed an algorithm in J I feel like I really understand it in a way that pretty much nothing else gives me with all the extra typing.
I personally find the given example harder to read than the equivalent in python/matlab/javascript with lodash/probably many other languages
sum(range(10))
sum(1:10)
With "K", you have to know a few new conventions. In the second case you just have to read, and the data flow is more obvious.
https://web.archive.org/web/http://shootout.alioth.debian.or...
Note that the relevant k program here is contained entirely on the last line of code and denoted by a comment telling you what it does:
http://c2.com/cgi-bin/wiki?WardNumberInManyProgrammingLangua...
Most Joy people are also k people, and Joy appears to be the only one similar, although still very large.
The C++ program is lost to link rot now, but by the author's own admission, was substantially larger than even the substantially large examples within that page.
1 2 29 k
23 70 498 scheme
25 111 768 otherhaskell
44 135 1096 erlang
53 125 1043 rb
67 190 1419 ocaml
74 346 1693 haskell
80 357 2586 java
Keep in mind that by their own admission, everyone in the c2 thread's code was hard to read (outside of the Joy program), and many were buggy. Meanwhile, the k program is quite simple to read.These are just some basic examples, though.
Even the word “product” would introduce certain ambiguity in context of real world codebase: is it “math” product or some “domain” product?
It’s even worse with most other words.
So if in any given codebase you still have to know the specific meaning of every word, how is it different from having to know specific meaning of every K symbol?
So you never encountered namespaces then? Because that's why you use namespaces. The number of symbols is limited, which is the reason why the whole "a symbol is more explicit"-argument simply doesn't hold in general. It breaks apart pretty quickly. That's why you'll find the following sentence pretty much verbatim in most maths and cs publications: "Throughout this paper, unless otherwise specified, we use the following notations," followed by half a page of definitions. Plot twist: different authors often use different notation even within the same field of research.
https://people.csail.mit.edu/gregs/ll1-discuss-archive-html/...
So by that estimate, if you switch to Python you're another halfway to Lisp (three quarters of the way from C++).
Python, maybe.
the closest i got to finding some pattern is this:
>>> xs
'34210'
>>> grade(xs)
[4, 3, 2, 0, 1]
>>> grade(grade(xs))
[3, 4, 2, 1, 0] # :O
where grade = lambda xs: (
[i for (i,_) in sorted(enumerate(xs), key=swap)]
)
swap = lambda p: (p[1], p[0])
no clue what it means though.(i guess "ordinal" really is too ambiguous...)
EDIT
alright, i see it now - `<<xs` is "for each item x of xs, where does x land when you sort xs?
x: 10?A:"abcdefghijklmnopqrstuvwxyz"
x
"ysyselacwl"
+`x`y`z!(x;<x;<<x)
x y z
--- - -
"y" 6 8
"s" 7 5
"y" 4 9
"s" 5 6
"e" 9 2
"l" 1 3
"a" 3 0
"c" 8 1
"w" 0 7
"l" 2 4
So <x gives a sort index, <<x tells you how far each element is from the minimum in that sort index x:“baced“
<x
1 0 2 4 3
<<x
1 0 2 4 3
That is, for example, when sorting, the item at position 1 in the original string (“a”) moves to position 0 (the beginning of the sorted string). So in the end you get “abcde”.What does column y mean? If I sort the original with it, I get “wllaysysce”.
Has this changed between versions of K?
xs = "cab"
<xs = [1,2,0] =
{
0 → 1
1 → 2
2 → 0
}
<<xs = [2,0,1] =
{
0 → 2
1 → 0
2 → 1
}
which is exactly what "ordinal" is supposed to do!
it kinda makes sense - grading the indexes given by `<xs` gives a permutation list that maps each index back to its actual position (i.e. [1,2,0]==>[0,1,2]). or at least it seems that way if you stare long enough, would be good if someone could confirm!One interesting philosophical difference, at least among some APL programmers, is that building abstractions should be avoided. TFA has a hint of that philosophy, in its suggestion that perhaps naming (the root of abstraction) hinders clarity. I think this is definitely worth considering, and it doesn't really have anything to do with the (supposedly) cryptic syntax.
One reason I don't like K/APL-ish vector programming is performance. I once spent some time working with others on a GPU-targeting APL compiler, and I found that some common programming patterns are quite antithetical to good performance. In particular, the use of "nested arrays" (not the same as multidimensional arrays) induces pointer structures that are difficult to do anything with. Such nested arrays are typically necessary when you want to do the equivalent of a "map" operation that does not apply to each of the scalars at the bottom, but perhaps merely the rows of a matrix. Thus, control flow and data are conflated. This is fine conceptually, but makes it difficult to generate high-performance code.
Another concern is that encoding control flow as data requires a lot of memory traffic (unless you have a Sufficiently Smart Compiler; much smarter than I have ever seen). Consider computing the Mandelbrot set, which is essentially a 'while' for each of a bunch of points. An idiomatic APL implementation will often put the while loop on the outside of the loop over the point array, which means it will be written to memory for every iteration. In other languages, it would be more idiomatic to apply the 'while' loop to each point individually, which will then be able to run entirely in registers. You can also do that in APL, but it is normally not idiomatic (and sometimes awkward) to apply complex scalar functions to array elements.
Just look at this Mandelbrot implementation from Dyalog; they do it in exactly the way I described: https://www.dyalog.com/blog/2014/08/isolated-mandelbrot-set-...
Specifically, the conceptual 'while' loop has been turned into an outer 'for' loop (this is OK because the 'while' loop is always bounded anyway):
:For cnt :In 1↓⍳256 ⍝ loop up to 255 times (the size of our color palette)
escaped←4<coord×+coord ⍝ mark those that have escaped the Mandelbrot set
r[escaped/inds]←cnt ⍝ set their index in the color palette
(inds coord)←(~escaped)∘/¨inds coord ⍝ keep those that have not yet escaped
:If 0∊⍴inds ⋄ :Leave ⋄ :EndIf ⍝ anything left to do?
coord←set[inds]+×⍨coord ⍝ the core Mandelbrot computation... z←(z*2)+c
:EndForhttps://github.com/indiscible/qmandel
And Arthur's version in k (also below):
I should convert it to k9 (Shakti)...
+/~^+/b*b:49{c+(-/x*x;2**/x)}/c:-1.5 -1+(2*!2#w)%w:10Humans need abstractions to think. What programmers need are abstractions that are not black boxes. I.e. can be opened.
> the use of "nested arrays" (not the same as multidimensional arrays) induces pointer structures that are difficult to do anything with
J doesn't allow nested arrays by default; if you want to create such a structure, you have to use boxes (and then unbox the values inside of them to get at them), which makes it explicit and reduces its usage. AFAIK, k doesn't have nested arrays at all.
Most likely available through your package manager.
Free software K interpreter:
Arthur's K interpreter isn't actually that expensive for casual use anymore (it's free for most non-commercial use and you can download it off the Shakti website pretty easily), though. Not that I'd recommend it: Arthur's a genius, but nothing's worth using proprietary software for.
What I usually recommend for learning the paradigm is J, largely because it has far better resources than anything else in the space. J's labs are wonderful, and the books Ken Iverson wrote before he died (all available for free) are great both for learning the language and also for learning many other things.
GNU APL is nice, and by no means am I trying to diss it: it's just not the best for learning, in my opinion. Its info pages are really nice though, like most GNU info pages.
Once you see e.g. input verification or other more "tedious" parts of programs, things get decidedly less cryptic.
And less optimized/concise, of course. A bit like the people who complain about GUI hello world programs taking 10 lines.
I'm asking because the article is poking at C-like languages, i.e. implying that K is good for general-purpose use. Yet all I hear about is that K is good at multiplying numbers and matrices, which is a pretty limited playground.
OpenFirmware (previously seen in Power Macs, pretty much every Sun device until Sun died, so on.
Canon Cat (greatest text editor of all time, by Jef Raskin, the guy who made the Macintosh)
Forth Has Been to Space (multiple times, but who's keeping score?): https://www.forth.com/resources/space-applications/
OKAD, which was used to create the processor with the lowest power usage per instruction in the entire world.
k:
Important, no, but a substantial volume of stuff. Text editors, GUIs, window managers, operating system completely independent of any other, a pretty important and very expensive database, so on.
k, unlike Forth, came after software was seen as IP. Software as IP has made a lot of people very angry and been widely regarded as a bad move.
k's ancestor, APL, was used in quite a few things quite elegantly, and while k is different, it's not different enough to be a different paradigm. Some examples: first practical electronic mail system, first widely-used electronic mail system (used for Carter's successful Presidential campaign, for example), first worldwide computer network, I could go on.
That k hasn't seen as much groundbreaking work done in it is less because of the language itself and more because of the insane costs, trigger-happy lawyers of kx, and money.
Of course, when you asked this of Forth the other day, you were trolling ( https://news.ycombinator.com/item?id=22319154 ), so I imagine I might be wasting my time.
> It had a text-based interface without a mouse, icons, or menus
sigh
The Forth in space thing is just some drivers/firmware for spaceships. I.e. once again nothing that an ordinary user would care about. The APL part is devoid of links to real contemporary software. Not even something of Notepad++ quality...
Please don't waste your time as you don't seem to want to understand my question. Thank you.
Is it still as elegant?
Knuth tried to move us to that state with Literate Programming. How many K programmers use Literate Programming? One? Two? Any?
I could easily see myself becoming dejected after printing out a few cheat sheets and buying some relevant books. I would have attempted some exercises and done whatever toy projects with an increasing feeling of dread that I was simply aping what was before me only to find what I thought I had learned had slipped away in a weekend. Should I get much further than that, I would then try to solve an actual problem I had with it and that would be the end of it as I would stagger into realms of development environments and dependencies to try to get the right libraries in order, I would look for advice online and tentatively ask questions only to be blasted for using the wrong dialect of whatever, or have my questions misconstrued until I could be informed that what I really have is an XY problem, I don't really want what I asked for after all. What a relief to me.
At that point I throw in my hat and go back to what I am used to.
I know myself well enough to know that I just haven't the grit or patience to torment myself with trying to find an application for the befunge du jour and, as such, learning it becomes a Glass Bead Game for me. If my life depended on it, perhaps, but this reminds me too much of the "executable line noise" I escaped: Perl, with a kind of sly terseness I associate with any number of obfuscations as a kind of puzzlebox monument to the "cleverness" of packing something into a single line I have had to slam into while programming.
I lack the vim to tilt at these windmills.
I write K for a living, and J for fun. J is WAY crazier, and I learned it specifically because it was so weird and crazy. I kinda wanted to remember what it was like to be a beginner again.
In all these languages, you can always fall back to doing things the "old way"... They all pretty much support structured and functional programming with loops and functions and whatnot. It's just there are lots and lots of shortcuts, and you get used to them over time.
(Also for what it's worth, the communities around vector languages do tend to be pretty friendly and welcoming...)
Domain specific languages have syntax optimized towards specific tasks. This often means very compact symbolic expressions which looks completely inscrutable to outsiders but are highly efficient when you know the language. String processing in Perl, pointer arithmetic in C, selectors in jQuery. Nobody can guess what the code does by looking at it, you have to learn the language. But it is worth the investment when the task in question is often used.
So the question is, are you working in a domain where the investment in learning a particular DSL will pay off?
But this context is completely absent in the article. By comparing the K syntax for "reduce" with a for-loop, it assumed the competition is systems languages like C or Go where a for-loop is idiomatic. But then the question is, how often do you use "reduce"-like operations in this domain anyway? It is really worth optimizing the langauge towards?
If on the other hand the article admitted K is a domain specific language optimized for numerical processing, then a reasonable comparison would be against Numpy or Matlab, perhaps Haskell, not for-loops.
If anything, the most successful applications seem to be with databases (not math), but it's also pretty great for interactive graphics:
https://github.com/JohnEarnest/ok/tree/gh-pages/ike
I work at the same company as the author, and we use K3 for all kinds of things -- system administration, network servers, interactive web apps.
It's a pretty general purpose language. And you can even do old-school loops if you want. It's just very concise.
Also, in K, there's a whole set of one-or-two-character symbols that allow you to express other uses of loops in traditional languages.
> Leaning back in your chair, you think to yourself:
> |/
what does this translate into?
let max = list[0];
for (let i = 0; i < list.length; i++) {
max = Math.max(list[i], max);
}
With a|b, you get the maximum between a and b. / is reduction. So, |/list, will be equivalent to list[0]|list[1]|list[2]|...|list[n], i.e. the maximum value in the list. Math.max(...list); > Math.max(..._.range(0, 1000000))
Thrown:
RangeError: Maximum call stack size exceededYes, that kind of syntax can be wonderfully terse when doing simple arithmetic operations on lists of integers.
Most programming work does not consist of doing simple arithmetic operations on lists of integers.
If you want to convince me that this languagy useable for anything but toy problems specially chosen to demonstrate the language's strengths, show me how it can be used to handle an HTTP request with some special cases for certain headers, or to parse a custom date format with variants, or to implement a game with realtime user input.
This^^^.
And even when doing simple arithmetic operations on lists of integers it's hard to read unless you've become very familiar with it.
This is no good.
We actually have an in-house DSL with a symbolic representation that looks very similar to K for our reporting system. It's one of my many missions to gradually phase it out in favour of something with either Python or SQL syntax. This will ease onboarding and drive adoption.
The advantage of a language like Python, for example, is that although I wouldn't say I know it, I can read it and understand what's going on most of the time. Same with SQL or Ruby or various other languages.
This makes it easy for people to understand what something is doing just by reading it, and opens up the possibility of learning along the lines of "How did Susan do that?", look at Susan's code, and see something that's fairly easy to read, understand, and remember, as opposed to a screed of arcane looking symbols.
https://gist.github.com/chrispsn/da00835bb122c42f429a084df83...
E:[u:();e:{a::?[a;x;y];J(x)+#y};cz:{$[#u;e/_`u;]};kx:{u,:,(j,j+#x;k_a);e[k]x};kb:{$[=/k;J j-1 0;];kx""};cx:{kx cc`};cv:{kx@9'`}] A:[w::_W%F;j::k;k:0 0;J:{k::2#0|x&#a};lx:{J j+x};y::V+F0,j;z::1'(V;w[1]$a)],E
U:{(`Z,'!Z).'+x};V:0;i:0;I::`Z,(!Z)(#Z)!i;y:{I .`y};zf:{$[`kt=x;i+:1;^`W`F?x;I . x;. x]};u::F[0]!#Z;W:{U`V,,u,'0;U`W,,(-':1_u,x),'x 1};z:{U`z;1'(V;U[`a]{$[#x;"";y]}'$!Z;3)} Z:`to`cc`subj`!A$/:4#()
This looks like an exercise in obtuseness.
Properly formatted and with comments, it almost looks readable.
The insistence to use one- or two-letter identifiers that you then have to look up the meaning of in a comment makes it look pretty childish, though. "Look ma, it's still super terse even when doing something real!" Yes kid, it is when you refuse to do the one obvious thing that could actually make it readable.
Actually, that's perhaps a bit harsh.
I have some pretty obscure hobbies, and there's certainly nothing wrong with doing this sort of thing if you want to. Still, having done so it's a bit rich to then look askance at the rest of us like we're all idiots for not choosing to go down a similar route with our own systems.
In the original code[1] these changes are trivial to make, even for someone new to the code base. How would they look in k? As others I struggle to see past the terseness, but maybe it would make more sense if I could see the program evolve.
[1]: https://web.archive.org/web/20070822025008/http://www.ffcons...
K +/!100
Python sum(range(100))
Haskell sum [0..99]
Rust (0..100).sum()
Ruby (0..99).sum
There are plenty of ultra-concise languages for toy problems like these; they are called ‘golfing languages’. Ultimately it's a bit pointless since most of the time people aren't playing code golf.(The issue with setting everything to obscure ultra-compressed keywords isn't that it's not possible to learn those keywords, but that most of the time programming is done over specific and customized domains with larger and problem-specific vocabularies.)
Python/numpy is most accessible and probably closest to “instant gratification”. Mathematica is great for, you know, mathematics, but you’ll need a license. And there is always haskell.
None of the languages you listed are quite as readable as k to someone who knows it.
All of the languages you listed are significantly slower and feature none of the benefits of a concise notation, even with fast.ai's Python style guide made to imitate Arthur Whitney.
http://www.eecg.toronto.edu/~jzhu/csc326/readings/iverson.pd...
It mocks it, but it doesn't present a convincing argument. Switching from an imperative language to K is making several changes at once, so we can't really conclude anything about the details of which changes are good or bad. The closest I've seen to a controlled experiment is something like: on a Haskell codebase, switch between using symbolic names like "^>>" and alphabetic names like "promap". And my experience has been, in a real-world mixed-ability team, that overall the alphabetic names had the advantage; if this isn't so for K, then we should try to understand the reasons why. The OP gestures at this, but unconvincingly: why yes, "ordinal" is much clearer than "<<", thank you very much. "Ordinal" may mean different things in different contexts, but so too does "<<" for anyone who knows other programming languages; a name that can help with intuition is a good thing even when it isn't perfect.
I'm very much a believer in concise notation (more than most people I've worked with), but the advantages of having a name that can be unambiguously spoken are large enough to outweigh a small constant factor. I sketched a mainstream-FP implementation of the famous 1-liner APL game of life, which became something like three lines (not counting implementing the equivalents of the APL operators, which require slightly fancy polymorphism to do the right thing on vectors and matrices but are otherwise not that special) that could actually be read and talked about. That seemed like a good tradeoff.
One can - and should - write code that's much denser than the current maintstream style. I do think the industry massively underestimates the value that comes from fitting a function or class on a single page. But I remain unconvinced that it's worth going all the way to code that can't be communicated verbally.
I don't believe this holds up to scrutiny. APL as a language was made to be spoken, and it seems to have succeeded in that. Alan Perlis briefly touched on that in a great paper,[1] and just about everyone who's worked with the language and its derivatives agrees that your statement isn't true.
The idea that APL and its derivatives can't be "read and talked about" is frankly ignoring reality by any stretch of the imagination.
For example, here's [2] [3] [4] some videos disproving your statement, the first two being APL, the last being k itself.
For extra bonus points, see Aaron Hsu's talks [5]; pick any of them, they're all pretty good, and most have a segment in them explaining how that viewpoint is wrong.
[1] https://www.jsoftware.com/papers/perlis77.htm
[2] https://www.youtube.com/watch?v=a9xAKttWgP4
[3] https://www.youtube.com/watch?v=DmT80OseAGs
Symbols can be communicated verbally. You can make up new symbols and give them a verbal meaning.
I think the big issue here is that programmers are lazy and whine about anything they aren't able to pick up within a weekend with their prior experience and some hard staring. "I looked and I didn't get it so it's unreadable." By the same token, Greek, Russian, Japanes, Korean, and many many other languages must be unreadable, along with like mathematics.
Meanwhile, I'm happy that we have concise syntax for mathematics, even if you have to go out of your way to learn to read all these fancy symbols. Notation as a tool of thought and all that.
Actually, the post pretends you know nothing about functional programming and then presents K as the solution–but, as the grandparent points out, it’s not the only one. The post actually has no comment on this.
(I should also note that smugly mocking a mindset by reducing it to a caricature might help explain why people are exasperated by the post’s patronizing tone.)
> Does giving a K idiom a name make it clearer, or does it obscure what is actually happening?
sum: +/
raze: ,/
ordinal: <<
> The word “ordinal” can mean anything, but the composition << has exactly one meaning. (That one took a while to click, but it was satisfying when it did.)(Didn’t click for me but I also didn’t spend a while on it, whatever.)
However, one should note that it's not like other functional languages don't have their share of cryptic operators, intuitiveness up to debate of course. Here's a list for Mathematica: https://mathematica.stackexchange.com/a/25616
At the end of the day this approach doesn't scale very well and skews nicer when you look at very simple examples like +/!100.
Anyway, I'll take my sum(range(100)).
A great example of a tautology. Every language in existence passes this test...
The real test is a language that is readable by those who don’t know it.
It is not just about abstraction level either: Python gives me intense discomfort.
I have not used K, but quite like the way it looks.
That's not true. Languages vary tremendously in how readable they are to people that know them. Especially if you set the bar for "knowing" at a consistent number of hours invested.
A language that's total noise at hour zero could also be the easiest to read at hour 20, and 40, and 100, and 1000...
When a language is something you're supposed to be doing real work in, as a core part of your job, it's perfectly reasonable to require some amount of training before you're set loose.
Incidentally, if you have a relatively recent Raspberry Pi you already have a Mathematica license.
How many times have you opened a Java/C#/C++ project and opened up class file after class file trying to understand how the whole thing is pieced together, faced with a monstrous system and, days later, still no understanding of how the system works at a macro level and how everything is connected.
How many times have you started browsing a GitHub repository looking for where something is implemented, opening file after file only to give up an hour later with absolutely no understanding of the organization of the system or being able to predict where any particular functionality is implemented.
Most people would say Python is a fairly legible language. You can write a class or function and most programmers can understand how it works fairly easily. However, with Python (or any mainstream language) you are only looking "down". You see what the function uses and how. You cannot see how the function itself is used. The other part of a function's meaning is how it's used idiomatically and what problems are solved by it. This is why, when figuring out how to use a library, most people prefer to look for an example than to browse the code. I believe any codebase of sufficient size effectively becomes a sort of library for solving its specific problems in its specific ways. There is a sort of hierarchy of increasing domain-specificity from language to library or framework to codebase, where each level has its own idioms and preferred ways of doing things.
Even ignoring the seemingly unnecessarily obtuse notation (which you really do get used to reading, but I recognize it's a hard sell to say "use it regularly for a few weeks/months and it'll all be perfectly clear trust me"), K (and J, and APL which I'm more familiar with) are legible in a way that other languages are not. When the entire system fits in a page of code you can understand everything about it from the top down. APL allows you to look "up". From any function you can see, instantly, without endless scrolling and switching between dozens of files, everywhere the function is used and how and what functions it's used in conjunction with. You do not need to press "switch to header file" ever. You do not need to press "go to definition" ever. The definition is right in front of you. Often since APL prefers idioms to building giant towers of abstraction, the definition is the name.
Not using "for" loops is not really the point of APL. The point of APL is that being really, incredibly, seemingly unnecessarily concise fundamentally changes how you read code.
APL is very legible.
Do these languages have a module system, or just copy-paste?
What do you do when you get more than a page of code? I'm skeptical of a claim that every program fits on one page.
You could find cross references…
Do you have an opinion of Octave?
/(?<!c)i(?=e)/
list.reduce!maxdo:
- Explain what particular use cases the language is optimized for
- Show its advantages compared to the alternatives
- Tell me honestly what tasks it is not suited for
do not:
- Use blantant strawmen to make the alternatives look worse.
- Tell me I am an idiot
Essentially that's just the Blub Paradox in action.
Sadly, at the moment I'm on this side of the Blub Paradox in a weird way. I do acknowledge the power of specialist syntax and short notation (studied Maths which is full of this) but haven't dedicated sufficient time to it for it to be fluid to me.
"!", on the other hand...
There simply aren't enough professors to maintain that breadth of courses in those departments.
A CS or Maths course should certainly involve some functional language element.
For someone reading thinking of CS at university, whether there's a requirement or option in such would be a good question to ask (you're interviewing them as much as they're interviewing you).
I'm sorry, but that sounds like the juvenile fantasy of someone who is still in their programming puberty.
Good luck fitting an operating system, web browser or air traffic control system into a page of code.
What PeCaN said there is no different from what masters like Chuck Moore and Arthur Whitney say. Maybe you disagree, maybe not everyone is like those guys, but "juvenile fantasy" and "programming puberty" is an extremely shallow dismissal—which https://news.ycombinator.com/newsguidelines.html specifically ask you to avoid.
We detached this subthread from https://news.ycombinator.com/item?id=22523047.
>Good luck fitting an operating system, web browser or air traffic control system into a page of code.
Aaron Hsu's co-dfns compiler (optimizing compiler for a subset of APL to the GPU) is 3 screens https://github.com/Co-dfns/Co-dfns/tree/master/cmp (I can fit the entire codebase on my three monitors).
This K text editor is way less than one screen https://kparc.com/edit.k (Funny you should mention OS. I'm eager to see how many pages kOS is. AW notoriously hates scrolling.)
Web browsers are a lost cause, I'll give you that one.
Where's the handling of encoding when loading and saving? Where's the handling of different line-endings? Where's the error handling?
Would have been nice to see something approaching real-life code rather than these toy samples.
For larger applications what PeCaN was saying still mostly holds true.
I work on large (1-10 million loc systems) enterprise java code bases and write some side projects in k as a hobby.
I can get the equivalent of around 30-40 java class files on screen at once with k.
Even on poorly written enterprise code bases code is clustered and your “working set” of code files is quite small and is not strewn all over the codebase.
Of course you still need to understand the core system abstractions + base platform + common library code.
If you see many different usages of the same identifier then it’s probably a common construct/pattern you aren’t aware of.
In the same way as ‘i’ tends to be used as the current array index in a for loop - but devs don’t get confused by seeing ‘i’ used in lots of different loops.
Or kotlin devs seeing ‘it’ or class based language devs seeing ‘this’.
there's a lot of room for improvement in conciseness of code. I would still be surprised if it was meaningfully possible to write a full-featured modern OS with one page of APL
ABTASTTSBMR than the whole sentence. OK.
I'm happy with just text.