Basic Syntax and Data Types in KDB+ and Q
Introduction
KDB+ and its associated language, Q, offer a unique syntax and data model that is designed for speed and efficiency. This chapter will introduce the fundamental building blocks of the Q language, including its syntax, operators, and data types.
Basic Syntax
Q is a functional language, meaning it relies heavily on functions and expressions. It uses a concise syntax that is often described as terse but expressive.
Comments:
Code snippet
// This is a single-line comment \c This is a multi-line comment
Assignment:
Code snippet
x: 10 // Assign the value 10 to the variable x
Functions:
Code snippet
f[x] := {x*2} // Define a function f that doubles its argument
Control Flow:
Code snippet
[x>5; "greater than 5"; "less than or equal to 5"] // Conditional expression
Data Types
Q supports a rich set of data types, each optimized for performance.
Atoms:
int
: Integer (e.g., 1, -2, 0)float
: Floating-point number (e.g., 3.14, -0.5)char
: Character (e.g.,a
,Z
)symbol
: Symbol (e.g.,AAPL
,IBM
)
Code snippet
x: 10 // int y: 3.14 // float c: `a // char s: `AAPL // symbol
Lists:
Ordered collection of items of the same type.
Code snippet
list1: 1 2 3 4 list2: (`a`b`c)
Dictionaries:
Unordered collection of key-value pairs.
Code snippet
dict1: (AAPL:100 IBM:200 GOOG:50)
Tables:
Two-dimensional array with named columns.
Code snippet
table1:([] date:2023.01.01 2023.01.02; price:100 120)
Operators
Q provides a comprehensive set of operators for arithmetic, comparison, logical, and other operations.
Arithmetic Operators:
Code snippet
+ - * / % // Addition, subtraction, multiplication, division, modulo
Comparison Operators:
Code snippet
= <> < <= > >= // Equal, not equal, less than, less than or equal, greater than, greater than or equal
Logical Operators:
Code snippet
and or not // Logical AND, OR, NOT
Other Operators:
Code snippet
$ // Type cast # // Count in // Membership
Examples
Code snippet
// Create a list of numbers
numbers: 1 2 3 4 5
// Calculate the sum of the list
sum numbers
// Create a dictionary of stock prices
prices: (`AAPL:100 `GOOG:200 `IBM:150)
// Access the price of AAPL
prices[`AAPL]
// Create a simple table
trades: ([] time:10:00 10:01 10:02; price:101 102 99)
// Select rows where price is greater than 100
select from trades where price > 100
Summary
This chapter has introduced the fundamental building blocks of the Q language. By understanding these core concepts, you'll be well-prepared to explore more advanced features and applications of KDB+. In the following chapters, we will delve deeper into data manipulation, time series analysis, and other key areas of KDB+ development.
Note: This chapter provides a basic overview. KDB+ offers many more data types, operators, and functions than covered here. Refer to the official Kx documentation for a comprehensive list.
Last updated
Was this helpful?