K (programming Language) - Examples

Examples

K is an interpreted language where every statement is evaluated and its results immediately displayed. Literal expressions such as strings evaluate to themselves. Consequently, the Hello world-program is trivial:

"Hello world!"

The following expression sorts a list of strings by their lengths:

x@>#:'x

The expression is evaluated from right to left as follows:

  1. #:'x returns the length of each word in the list x.
  2. > returns the indices that would sort a list of values in descending order.
  3. @ use the integer values on the right to index into the original list of strings.

A function to determine if a number is prime can be written as:

{&/x!/:2_!x}

The function is evaluated from right to left:

  1. !x enumerate the positive integers less than x.
  2. 2_ drops the first two elements of the enumeration (0 and 1).
  3. x!/: performs modulo division between the original integer and each value in the truncated list.
  4. &/ find the minimum value of the list of modulo result.

If x is not prime then one of the values returned by the modulo operation will be 0 and consequently the minimal value of the list. If x is prime then the minimal value will be 1, because x mod 2 is 1 for any prime greater than 2.

The function below can be used to list all of the prime numbers between 1 and R with:

(!R)@&{&/x!/:2_!x}'!R

The expression is evaluated from right to left

  1. !R enumerate the integers less than R.
  2. ' apply each value of the enumeration to the prime number function on the left. This will return a list of 0's and 1's.
  3. & return the indices of the list where the value is 1.
  4. @ use the integer values listed on the right to index into the list on the left.
  5. (!R) A list of integers less than R.

Read more about this topic:  K (programming Language)

Famous quotes containing the word examples:

    In the examples that I here bring in of what I have [read], heard, done or said, I have refrained from daring to alter even the smallest and most indifferent circumstances. My conscience falsifies not an iota; for my knowledge I cannot answer.
    Michel de Montaigne (1533–1592)

    There are many examples of women that have excelled in learning, and even in war, but this is no reason we should bring ‘em all up to Latin and Greek or else military discipline, instead of needle-work and housewifry.
    Bernard Mandeville (1670–1733)

    It is hardly to be believed how spiritual reflections when mixed with a little physics can hold people’s attention and give them a livelier idea of God than do the often ill-applied examples of his wrath.
    —G.C. (Georg Christoph)