# Views

A view is a calculation that is re-evaluated only if the values of the underlying dependencies have changed since its last evaluation.

Splayed tables

To use views with splayed tables make sure you invalidate the data when it changes; this can be done for example by reloading the table.

## Why use a view?¶

Views can help avoid expensive calculations by delaying propagation of change until a result is demanded.

## How is a view defined?¶

The syntax for the definition is

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


Terminating semicolon

The result returned by a view is the result of the last expression in the list, just as in a lambda.


q)a: til 5
q)uu:: a
q)uu
0 1 2 3 4
q)vv:: a;
q)vv
q)vv ~ (::)
1b
q)vv ~ {[];}[]
1b 

The following defines a view called myview which depends on vars a and b.

q)myview::a+b
q)a:1
q)b:2
q)myview
3


Defining a view does not trigger its evaluation.

A view should not have side-effects, i.e. should not update global variables. Although ; is permitted at the end of the definition, it would mean the view returns (::). As a view should have no side-effects, returning (::) would make the purpose of the view redundant.

A view definition can be spread over multiple lines in a script as long as it is indented accordingly (e.g. exactly like a function definition). e.g.

$cat v.q t:([]a:til 10) myview::select from t where a<5 / note this line is indented by one space$q v.q
KDB+ 3.2 2014.08.26 Copyright (C) 1993-2014 Kx Systems
m64/...

q)myview
a
-
0
1
2
3
4


Within a lambda, :: amends a global variable. It does not define a view.

q)x:2
q)y:3
q)v::x+y           /view
q)v
5
q)x:10000
q)v                /depends on x
10003
q){v::x+y}[10;20]  /v now a global variable
q)v
30
q)x:-1000000
q)v                /global variable, no longer depends on x
30


## How to list views¶

Invoke the views function (or \b) to get a list of the defined views.

q)a::b+c
q)d::b+a
q)views
s#ad


## How to list invalidated views¶

Invalidated (pending) views are awaiting recalculation.

Invoking \B will return a list of pending views.

q)a::b+c
q)\B
,a
q)b:c:1
q)\B
,a
q)a
2
q)\B
q)b:1;0N!v;b:0;v
q)v::$[b;1;v+1] q)v 'loop  From V3.2 view-loop detection is no longer performed during view creation; it is checked during the view recalc. ## Dot notation¶ Views do not support dot notation. q)t:.z.p q)t1::t q)t.date 2014.09.03 q)t1.date 'nyi  ## Multithreading¶ Views must be evalulated on the main thread, otherwise the calculation will signal 'threadview. E.g. with q using 2 slave threads $q -s 2
KDB+ 3.2 2014.08.26 Copyright (C) 1993-2014 Kx Systems
m64/...

q)a::b+c
q)b:c:1
q){a}peach 0 1
k){x':y}

Views are not parsable, e.g. eval parse "a::b+c"`