Overview
K shares key features with APL. They are both interpreted, interactive languages noted for concise and expressive syntax. They have simple rules of precedence based on right to left evaluation. The languages contain a rich set of primitive functions designed for processing arrays. These primitive functions include mathematical operations that work on arrays as whole data objects, and array operations, such as sorting or reversing the order of an array. In addition, the language contains special operators that combine with primitive functions to perform types of iteration and recursion. As a result, complex and extended transformations of a dataset can be expressed as a chain of sub-expressions, with each link performing a segment of the calculation and passing the results to the next link in the chain.
Like APL, the primitive functions and operators are represented by single or double characters; however, unlike APL, K restricts itself to the ASCII character set (a feature it shares with J, another variant of APL). To allow for this, the set of primitive functions for K is smaller and heavily overloaded, with each of the ASCII symbols representing two or more distinct functions or operations. In a given expression, the actual function referenced is determined by the context. As a result K expressions can be opaque and difficult to parse for humans. For example, in the following contrived expression the exclamation point “!” refers to three distinct functions:
2!!7!4Reading from right to left the first ! is modulo division that is performed on 7 and 4 resulting in 3. The next ! is enumeration and lists the integers less than 3, resulting in the list 0 1 2. The final ! is rotation where the list on the right is rotated two times to the left producing the final result of 2 0 1.
The second core distinction of K is that functions are first-class objects, a concept borrowed from Scheme. First-class functions can be used in the same contexts where a data value can be used. Functions can be specified as anonymous expressions and used directly with other expressions. Function expressions are specified in K using curly brackets. For example, in the following expression a quadratic expression is defined as a function and applied to the values 0 1 2 and 3:
{(3*x^2)+(2*x)+1}'!4In K, named functions are simply function expressions stored to a variable in the same way any data value is stored to a variable.
x:25 f:{(x^2)-1}Functions can be passed as an argument to another function or returned as a result from a function.
Read more about this topic: K (programming Language)