Skip to content
Tech News
← Back to articles

Thinking in an array language (2022)

read original more articles
Why This Matters

This article highlights the importance of array programming languages like K for efficient, concise, and readable code, emphasizing their utility in data manipulation and algorithm implementation. It underscores how mastering such languages can streamline complex computations and foster more declarative programming practices in the tech industry.

Key Takeaways

Thinking in an array language

You can view the full source code for this chapter at GitHub.

Since you are now properly acquainted with K, let's do some programming. Most K programming happens through the REPL, because it is very useful to iterate upon previous code. ngn/k with rlfe has history with the up/down arrow keys, and that should be more than enough to begin developing bigger programs in K. Functions are tested in the REPL, and then moved to actual code. Note that ngn/k's prettyprinting always returns valid k data, and you can precompute some things beforehand to speed up your program.

A K script is always executed like it was typed in the repl, that is: Each line is executed, and its return value is printed unless it ends with a semicolon. A script also allows multiline definitions, which are convenient for readability. Oftentimes, you may save your work in a script, and want to use it in a repl. In order to use your stored data and functions, just do \l file.k in the repl, and your file will be executed, and its data will be loaded. You can load a file into the REPL more than once, overwriting older data. The repl help accessed with \ lists more useful commands as well.

K programming (and array programming in general), is a continuous process of simplifying your patterns. A big, unwieldy pattern has one or more ways to condense to a smaller, more declarative, easy to read pattern. This is discussed in a lot of detail in Patterns and Anti-patterns in APL: Escaping the Beginner's Plateau - Aaron Hsu - Dyalog '17, if you'd like to understand it better.

A common problem most people have in K is the need to translate a common, well known algorithm to K, usually taken from a programming website like geeksforgeeks, or a Wikipedia article. Let us take an example: Matrix Multiplication.

From this wikipedia article, the iterative algorithm for matrix multiplication is as follows:

Input: matrices A and B Let C be a new matrix of the appropriate size For i from 1 to n: For j from 1 to p: Let sum = 0 For k from 1 to m: Set sum ← sum + Aik × Bkj Set Cij ← sum Return C

If you want, you can try translating this to K. A direct translation would be:

matmul: { A::x B::y n::#A m::#*A p::#*B C::(n;p)#0 i::0 j::0 k::0 sum::0 { i::x { j::x sum::0 { k::x sum::sum+A[i;k]*B[k;j] }'!m C[i;j]::sum }'!p }'!n C}

... continue reading