K4 Documentation

Comprehensive guide to the K4 programming language

Introduction to K4

K4 is the next evolution of the K language family, building on the foundations of K2 and K3 while introducing revolutionary new features for modern software development.

K4 is designed to address the challenges of the next generation of computing, with built-in support for:

  • Quantum Computing: Native quantum types and operations
  • AI Integration: First-class support for machine learning and AI systems
  • Distributed Computing: Built-in primitives for distributed systems
  • Formal Verification: Advanced type system with verification capabilities

Note: K4 is currently in early development. This documentation covers the planned features and syntax, which may change as the language evolves.

Installation

You can install K4 using the official installer for your platform:

Windows

// Download and run the Windows installer from the K4 website
// Or install using the command line:
winget install k4lang.k4

macOS

// Using Homebrew
brew install k4lang

// Or download the macOS installer from the K4 website

Linux

// Ubuntu/Debian
sudo apt install k4lang

// Fedora/RHEL
sudo dnf install k4lang

// Arch Linux
sudo pacman -S k4lang

Building from Source

git clone https://github.com/k2lang/k4.git
cd k4
make build
sudo make install

Hello World

Let's start with a simple "Hello, World!" program in K4:

// hello.k4
fn main() {
    println("Hello, K4 World!");
}

Save this to a file named hello.k4 and run it with:

k4 run hello.k4

You should see the output:

Hello, K4 World!

Basic Syntax

K4 syntax is designed to be clean, expressive, and familiar to users of modern programming languages.

Comments

// Single line comment

/* 
   Multi-line comment
   spanning multiple lines
*/

/// Documentation comment for functions, types, etc.
fn documented_function() {
    // Function body
}

Variables

// Variable declaration with type inference
let name = "K4";

// Variable declaration with explicit type
let age: int = 1;

// Constants
const PI: float = 3.14159;

// Multiple declarations
let (x, y) = (10, 20);

Basic Types

// Numeric types
let i: int = 42;
let f: float = 3.14;
let c: complex = 1 + 2i;

// Boolean
let b: bool = true;

// String
let s: str = "Hello, K4!";

// Character
let ch: char = 'A';

// Optional types
let o: ?int = 42;  // Some value
let n: ?int = nil; // No value

Quantum Computing

K4 provides built-in support for quantum computing primitives, making it easy to write and execute quantum algorithms.

Quantum Types

// Qubit declaration
let q: qubit = qubit(0);  // Initialize to |0⟩

// Quantum register
let qreg: qreg = qreg(3);  // 3-qubit register

Quantum Operations

// Apply Hadamard gate to a qubit
H(q);

// Apply CNOT gate with control qubit q1 and target qubit q2
CNOT(q1, q2);

// Apply phase rotation
P(PI/4, q);

// Measure a qubit
let result = measure(q);

Quantum Circuits

// Define a quantum circuit
quantum Bell {
    // Create a 2-qubit register
    let qreg = qreg(2);
    
    // Apply Hadamard gate to the first qubit
    H(qreg[0]);
    
    // Apply CNOT gate with control qubit 0 and target qubit 1
    CNOT(qreg[0], qreg[1]);
    
    // Measure both qubits
    let result = measure(qreg);
    
    // Print the result
    println("Bell state measurement: {}", result);
}

Tip: You can visualize quantum circuits in the K4 online playground by clicking the "Visualization" tab after running quantum code.

AI Integration

K4 provides native support for machine learning and AI systems, making AI development simpler and more intuitive.

AI Models

// Create a neural network model
let model = AIModel::NeuralNetwork {
    name: "digit_classifier",
    layers: [
        Dense(784, 128, activation: "relu"),
        Dense(128, 64, activation: "relu"),
        Dense(64, 10, activation: "softmax")
    ]
};

Training and Inference

// Train the model
model.train(train_data, train_labels, {
    epochs: 10,
    batch_size: 32,
    learning_rate: 0.001
});

// Make predictions
let predictions = model.predict(test_data);

AI Integration Example

// AI-powered image classification
fn classify_image(image_path: str) -> str {
    // Load pre-trained model
    let model = AIModel::load("vision_transformer");
    
    // Load and preprocess image
    let image = Image::load(image_path);
    let tensor = image.to_tensor().normalize();
    
    // Make prediction
    let prediction = model.predict(tensor);
    let class_id = argmax(prediction);
    
    // Map class ID to label
    let labels = ["cat", "dog", "bird", "fish", "other"];
    labels[class_id]
}

Warning: AI models can consume significant memory and computational resources. Be mindful of resource usage when deploying AI applications.

Distributed Computing

K4 makes distributed computing a first-class citizen, allowing you to write distributed systems with ease.

Distributed Primitives

// Define a distributed node
node Worker {
    // State
    let data: [int] = [];
    
    // Message handlers
    fn handle_process(items: [int]) -> int {
        // Process data
        let sum = items.sum();
        data.append(sum);
        sum
    }
}

Distributed Computations

// Distributed MapReduce
distributed MapReduce {
    nodes: ["node1", "node2", "node3", "node4"],
    
    // Map function to be executed on each node
    fn map(data: [int]) -> [(str, int)] {
        // Count word occurrences
        let counts = {};
        for item in data {
            let word = item.to_string();
            counts[word] = (counts[word] || 0) + 1;
        }
        [(word, count) for word, count in counts]
    }
    
    // Reduce function to combine results from all nodes
    fn reduce(mapped: [[(str, int)]]) -> [(str, int)] {
        let combined = {};
        for node_data in mapped {
            for (word, count) in node_data {
                combined[word] = (combined[word] || 0) + count;
            }
        }
        [(word, count) for word, count in combined]
    }
}

Fault Tolerance

// Distributed computation with fault tolerance
distributed Resilient {
    nodes: ["node1", "node2", "node3"],
    retry_count: 3,
    timeout: 5000,  // ms
    
    // Main computation
    fn compute(data: [int]) -> int {
        // Distribute work
        let chunks = data.chunk(nodes.len());
        let results = parallel_map(nodes, chunks, process);
        results.sum()
    }
    
    // Error handling
    fn on_node_failure(node: str, chunk: [int]) -> ?int {
        println("Node {} failed, retrying...", node);
        // Try another node
        let backup_node = find_available_node();
        if backup_node != nil {
            process(backup_node, chunk)
        } else {
            nil  // Cannot recover
        }
    }
}

Note: Distributed computing features require the K4 runtime to be properly configured for network communication.