K is like APL with fewer built-ins. The syntax is ASCII-only, and most built-in functions are heavily overloaded single bytes of ASCII punctuation.
There are several implementations with subtly varying behavior. code.golf uses ngn/k, which is not so well-documented. Your best bet might be to read the oK Manual as a general introduction to K, and then click "help" here to see an overview of ngn/k specifically.
Example
Let's look at a program that outputs all of the input arguments with their length appended to them: `0:{x,$#x}'x
(Try it on United States: it outputs Nebraska8
Rhode Island12
…)
`0:{x,$#x}'x
x Get the list of inputs.
{ }' Apply some lambda function to each input.
({} makes a lambda, and the adverb ' means each.)
x x Inside a monad lambda, "x" refers to the single argument.
# Monad # means "length"
$ Monad $ means "convert to string"
, Dyad , means "concatenate"
`0: Output the list of strings line by line.
0: is a dyadic writing-lines-to-a-file verb,
and the left argument ` (the empty symbol) means "write to STDOUT".
You can see that K is essentially read and written "right-to-left", much like J and APL. x,$#x
means (x,($(#x)))
. There's no operator precedence.
Golf tips
\
preceded by a space is "trace" (an identity function for debugging that prints its argument to STDOUT). This can be shorter than using`0:
. Trace however passes its argument through the K formatter before printing, so this may only be useful for numbers.$[x;T;F]
can becomex{T}/F
whenx
is a non-negative integer.x
in the global scope is a list of the command line args.
External resources
- The K tree, a StackExchange chatroom about K.