Elements

Ontology asks, What exists?,
to which the answer is Everything.
— W.V.O. Quine, Word and Object

Comments

Line comment

q)/Oh what a lovely day

Trailing comment

q)2+2  /I know this one
4

Multiline comment

/
    Oh what a beautiful morning
    Oh what a wonderful day
\
a:42
\
ignore this and what follows
the restroom at the end of the universe

Nouns

noun examples
atom 42; "a"; 1b; 2012.08.04; `ibm
vector (43;44;45); "abc"; 0101b; `ibm`goo; 2012.09.15 2012.07.05
list (43;"44";45); ("abc";0101b;);(("abc";1 2 3); `ibm`abc)
dictionary `a`b`c!42 43 44; `name`age!(`john`carol`ted;42 43)
table ([]name:`john`carol`ted; age:42 43 44)
keyed table ([name:`john`carol`ted] age:42 43 44)

Atoms

An atom is a single number, character, boolean, symbol, timestamp… a single instance of any datatype.

Lists

Lists are zero or more items, separated by semicolons, and enclosed in parentheses. An item can be any noun.

q)count(42;`ibm;2012.08.17)    /list of 3 items
3

A list may have 0, 1 or more items.

q)count()              /empty list
0
q)count enlist 42      /1-list
1
q)count(42;43;44;45)   /4-list
4

An atom is not a 1-list

A list with 1 item is not an atom. The enlist function makes a 1-list from an atom.


q)42~enlist 42
0b

A list item may be a noun, function or adverb.

q)count("abc";0000111111b;42)  /2 vectors and an atom
3
q)count(+;rotate;/)            /2 operators and an adverb
3

Vectors

In a vector (or simple list) all items are of the same datatype. Char vectors are also known as strings.

type example
numeric 42 43 44
date 2012.09.15 2012.07.05
char "abc"
boolean 0101b
symbol `ibm`att`ora

Vector syntax

Attributes

Attributes are metadata that apply to lists of special form. They are often used on a dictionary domain or a table column to reduce storage requirements or to speed retrieval.
# Set attribute

For 64-bit V3.0+, where n is the number of items and d is the number of distinct (unique) items, the byte overhead in memory is:

example byte overhead
`s#2 2 3 sorted 0
`u#2 4 5 unique 32*d
`p#2 2 1 parted (8*d;32*d;8*d+1)
`g#2 1 2 grouped (8*d;8*n)

Attribute u is for unique lists – where all items are distinct.

Grouped and parted

Attributes p and g are useful for lists in memory with a lot of repetition.

If the data can be sorted such that p can be applied, the p attribute effects better speedups than g, both on disk and in memory.

The g attribute implies an entry’s data may be dispersed – and possibly slow to retrieve from disk.

Some q functions use attributes to work faster:

Dictionaries

A dictionary is a map from a list of keys to a list of values. (The keys should be unique, though q does not enforce this.) The values of a dictionary can be any data structure.

q)/4 keys and 4 atomic values
q)`bob`carol`ted`alice!42 39 51 44   
bob  | 42
carol| 39
ted  | 51
alice| 44
q)/2 keys and 2 list values
q)show kids:`names`ages!(`bob`carol`ted`alice;42 39 51 44)
names| bob carol ted alice
ages | 42  39    51  44

Tables

A dictionary in which the values are all lists of the same count can be flipped into a table.

q)count each kids
names| 4
ages | 4
q)tkids:flip kids  / flipped dictionary
names ages
----------
bob   42
carol 39
ted   51
alice 44

Or the table specified directly using table syntax, e.g.

q)/a flipped dictionary is a table
q)tkids~([]names:`bob`carol`ted`alice; ages:42 39 51 44)
1b

Table syntax can declare one or more columns of a table as a key. The values of the key column/s of a table are unique.

q)([names:`bob`carol`bob`alice;city:`NYC`CHI`SFO`SFO]; ages:42 39 51 44)
names city| ages
----------| ----
bob   NYC | 42
carol CHI | 39
bob   SFO | 51
alice SFO | 44

Names and namespaces

A namespace is a container or context within which a name resolves to a unique value. Namespaces are children of the root namespace (usually just root) and are designated by a dot prefix. Names in the root have no prefix. The root namespace of a q session is parent to multiple namespaces, e.g. h, Q and z. (Namespaces with 1-character names – of either case – are reserved for use by Kx.)

q).z.p                         / UTC timestamp
2017.02.01D14:58:38.579614000

Namespaces are dictionaries

Namespace contents can be treated as dictionary entries.


q)v:5
q).ns.v:6
q).[v]      / value of v in root namespace
5
q).ns[v]    / value of v in ns
6
q).v       / indexed by juxtaposition
5
q).nsvv
6 6
q)..ns@\:v
5 6

Names in context

Functions

Functions are:

  1. operators and primitive functions, eg +, count
  2. as defined in the lambda notation, eg {x+2*y}
  3. as derived from (1) and (2) by adverbs, eg +/, count'
  4. q-SQL functions, e.g. select

Functions are first-class objects and can be passed as arguments to other functions. Functions that take other functions as arguments are known as higher-order functions.

Reserved words

The following reserved words denote functions that are not also operators.

Aabs, acos, aj, aj0, all, any, asc, asin, atan, attr, avg, avgs
Cceiling, cols, cos, count
Ddelete, deltas, desc, dev, differ, distinct
Eej, enlist, eval, exec, exit, exp
Ffills, first, fkeys, flip, floor
Gget, getenv, group, gtime
Hhclose, hcount, hdel, hopen, hsym
Iiasc, idesc, inv
Kkey, keys
Llast, load, log, lower, ltime, ltrim
Mmax, maxs, md5, med, meta, min, mins
Nneg, next, not, null
Pparse, prd, prds, prev
Rrand, rank, ratios, raze, read0, read1, reciprocal, reval, reverse, rload, rotate, rsave, rtrim
Ssave, sdev, select, show, signum, sin, sqrt, ssr, string, sublist, sum, sums, sv decode, svar, system
Ttables, tan, til, trim, type
Uungroup, update, upper
Vvalue, var, view, views
Wwhere, wj, wj1

.Q.res (reserved words)

Operators

Operators are primitive binary functions that may be applied infix.

q)|[2;3]                 / maximum, prefix form
3
q)2|3                    / maximum, infix form
3
q)rotate[2;0 1 2 3 4 5]  / prefix form
2 3 4 5 0 1
q)2 rotate 0 1 2 3 4 5   / infix form
2 3 4 5 0 1

Operators are denoted by glyphs or reserved words or both – see note below on minimum and maximum. (They cannot be defined using the lambda notation.)

Glyphs

=equal<>not equal~match
<less than<=less than or equal>greater than>=greater than or equal
+plus-minus*times%divided by
&minimum|maximum
#take, set attribute,join^fill; coalesce_drop; cut
!dict; key; enumerate; ints to enum; update; delete

Minimum and maximum

The minimum operator is denoted by both the & glyph and the reserved word and. The maximum operator is denoted by both the | glyph and the reserved word or.

Reserved words

The following reserved words denote operators.

Aand, asof
Bbin, binr
Ccor, cov, cross, cut
Ddiv, dsave
Eeach, ema, except
Ffby
Iij, ijf, in, insert, inter
Llike, lj, ljf, lsq
Mmavg, mcount, mdev, mmax, mmin, mmu, mod, msum
Oor, over
Ppeach, pj, prior
Sscan, scov, set, setenv, ss, sublist, sv consolidate
Uuj, ujf, union, upsert
Vvs encode, vs split
Wwavg, within, wsum
Xxasc, xbar, xcol, xcols, xdesc, xexp, xgroup, xkey, xlog, xprev, xrank

.Q.res (reserved words)

Adverbs

Adverbs are primitive higher-order functions: they return derivatives (derived functions). They are denoted by six overloaded glyphs: ', /, \, ':, /: and \:.

q)+/[2 3 4]  / reduce 2 3 4 with +
9
q)*/[2 3 4]  / reduce 2 3 4 with *
24

Adverbs, Adverb syntax

Control words

The control words do, if and while govern evaluation.

Views

A view is a calculation that is re-evaluated only if the values of the underlying dependencies have changed since its last evaluation. Views can help avoid expensive calculations by delaying propagation of change until a result is demanded.

The syntax for the definition is

q)viewname::[expression;expression;…]expression

The act of defining a view does not trigger its evaluation.

A view should not have side-effects, i.e. should not update global variables.

Views tutorial, view, views, .Q.view (subview)

System commands

Expressions beginning with \ are system commands or multiline comments (see above).

q)/ load the script in file my_app.q
q)\l my_app.q

Scripts

A script is a text file; its lines a list of expressions and/or system commands, to be executed in sequence. By convention, script files have the extension q.

Within a script

  • function definitions may extend over multiple lines
  • an empty comment begins a multiline comment.