Next: , Previous: , Up: k9: Manual  


8 Expression Evaluation

k9 has a compact way to evaluate expressions on dictionaries. This allows one to use the dictionary keys as local variables to get to results with less code.

Expr :a+b

8.1 expr ⇒ x :y

Evaluate expression(s) y on table or dictionary x. The space between x and : is required otherwise it becomes set, i.e., assignment.

 d:[city:`Chongqing`Shanhai`Beijing`Delhi`Chengdu]; d
city|`Chongqin`Shanhai`Beijing`Delhi`Chengdu

 d,:[country:`cn`cn`cn`in`cn;size:30 24 22 17 16] ; d
city   |`Chongqin`Shanhai`Beijing`Delhi`Chengdu
country|`cn`cn`cn`in`cn                        
size   |30 24 22 17 16                         

 d :&country=`in       / using country like a local variable
,3

 d :sum'size@=country  / sum size by country
cn|92
in|17

 d :+/size*country=`cn
92

As keys come in scope as variables, variables fall out of scope. One can evaluate the variable name as string to get around this.

 d :sum size@&size>20
76

 x:20;
 d :sum size@&size>x  / out of scope
!value

 d :sum size@&size>."x"
76

Reorder a table using column index and expresssions.

 t:[[]x:`b`a`c;y:1 3 2];t
x y
- -
b 1
a 3
c 2

 t@<t :y
x y
- -
b 1
c 2
a 3

 t@<t`y
x y
- -
b 1
c 2
a 3