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
Lists:
Ordered collection of items of the same type.
Code snippet
Dictionaries:
Unordered collection of key-value pairs.
Code snippet
Tables:
Two-dimensional array with named columns.
Code snippet
Operators
Q provides a comprehensive set of operators for arithmetic, comparison, logical, and other operations.
Arithmetic Operators:
Code snippet
Comparison Operators:
Code snippet
Logical Operators:
Code snippet
Other Operators:
Code snippet
Examples
Code snippet
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.
= <> < <= > >= // Equal, not equal, less than, less than or equal, greater than, greater than or equal
and or not // Logical AND, OR, NOT
$ // Type cast
# // Count
in // Membership
// 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