### Complete Global Workspace Example Source: https://github.com/tsotchke/eshkol/blob/master/site/static/content/api_reference.html Demonstrates the setup and execution of a multi-modal global workspace with perception, memory, and planning modules. It shows how to register modules with their respective salience and representation logic, and then run multiple competition cycles to observe dynamic module competition. ```lisp ;; Multi-modal integration: perception + memory + planning (define ws (make-workspace 4 3)) ;; Perception module: high salience when content is "neutral" (ws-register! ws "perception" (lambda (content) (let ((novelty (- 1.0 (tensor-dot content content)))) (cons (* 0.9 (max 0.1 novelty)) ; salience drops as content fills #(0.8 0.1 0.0 0.1))))) ;; Memory module: salience increases when perception matches stored pattern (ws-register! ws "memory" (lambda (content) (let ((match (tensor-dot content #(0.8 0.1 0.0 0.1)))) (cons (* 0.7 match) ; salience proportional to match #(0.7 0.2 0.1 0.0))))) ;; Planning module: constant moderate salience (ws-register! ws "planning" (lambda (content) (cons 0.5 #(0.0 0.0 0.8 0.2)))) ; action plan ;; Run 10 competition cycles (do ((i 0 (+ i 1))) ((= i 10)) (ws-step! ws)) ;; Over iterations, modules dynamically compete based on content state ``` -------------------------------- ### Initialize Project Command Example Source: https://github.com/tsotchke/eshkol/blob/master/docs/breakdown/PACKAGE_MANAGER.md Example output of the init command. ```sh mkdir my-project && cd my-project eshkol-pkg init # => Created eshkol.toml for project 'my-project' # => src/main.esk created ``` -------------------------------- ### Complete Active Inference Example Source: https://github.com/tsotchke/eshkol/blob/master/site/static/content/api_reference.html Demonstrates setting up a Bayesian network as a factor graph, adding factors, performing inference, and updating beliefs. Requires prior setup of the factor graph. ```Lisp ;; Weather->Umbrella Bayesian network as a factor graph ;; ;; Weather (binary: sunny/rainy) ;; | ;; P(umbrella | weather) ;; | ;; Umbrella (binary: yes/no) ;; 1. Create the graph (define fg (make-factor-graph 2 #(2 2))) ;; 2. Add prior: P(sunny) = 0.7 (fg-add-factor! fg #(0) #(-0.3567 -1.2040)) ;; 3. Add conditional: P(umbrella | weather) (fg-add-factor! fg #(0 1) #(-0.1054 -2.3026 -1.6094 -0.2231)) ;; 4. Infer beliefs (define beliefs (fg-infer! fg 20)) ;; 5. Observe someone carrying an umbrella → compute free energy (define F (free-energy fg #(1.0 0.0))) ;; 6. Evaluate actions (define g-sunny (expected-free-energy fg 0 0)) (define g-rainy (expected-free-energy fg 0 1)) ;; 7. Learn: update prior based on new evidence (fg-update-cpt! fg 0 #(-1.6094 -0.2231)) ; P(sunny) = 0.2 now (define new-beliefs (fg-infer! fg 20)) ; reconverge ``` -------------------------------- ### Module Path Resolution Example Source: https://github.com/tsotchke/eshkol/blob/master/docs/breakdown/REPL_JIT.md Example of converting a dot-separated module name into a filesystem path. ```text "core.list.transform" → "core/list/transform.esk" ``` -------------------------------- ### Minimal Example: Hello World Source: https://github.com/tsotchke/eshkol/blob/master/docs/breakdown/WEB_PLATFORM.md A basic example demonstrating how to create an H1 element, style it, and append it to the document body using Eshkol's web functions. ```APIDOC ## POST /api/users ### Description Creates a new user in the system. ### Method POST ### Endpoint /api/users ### Parameters #### Request Body - **username** (string) - Required - The desired username for the new user. - **email** (string) - Required - The email address of the new user. - **password** (string) - Required - The password for the new user. ### Request Example ```json { "username": "johndoe", "email": "john.doe@example.com", "password": "securepassword123" } ``` ### Response #### Success Response (201) - **id** (string) - The unique identifier for the newly created user. - **username** (string) - The username of the created user. - **email** (string) - The email address of the created user. #### Response Example ```json { "id": "usr_12345abcde", "username": "johndoe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### Run Eshkol Example Source: https://github.com/tsotchke/eshkol/blob/master/examples/README.md Execute an Eshkol program using the `eshkol-run` command. This is the basic way to run any example. ```bash ./build/eshkol-run examples/hello.esk ``` -------------------------------- ### Start the Eshkol REPL Source: https://github.com/tsotchke/eshkol/blob/master/docs/breakdown/GETTING_STARTED.md Launch the interactive development environment. ```bash # Start REPL build/eshkol-repl ``` -------------------------------- ### Test Eshkol Installation Source: https://github.com/tsotchke/eshkol/blob/master/docs/QUICKSTART.md Verify the installation by running the REPL or compiling a simple program. ```bash # Interactive REPL eshkol-repl # Compile and run a program echo '(display "Hello, Eshkol!")' > hello.esk eshkol-run hello.esk -o hello ./hello ``` -------------------------------- ### Install Extension from Source Source: https://github.com/tsotchke/eshkol/blob/master/docs/breakdown/VSCODE_EXTENSION.md Commands to compile the extension from the source directory. ```bash cd tools/vscode-eshkol npm install npm run compile ``` -------------------------------- ### Complete eshkol.toml Manifest Example Source: https://github.com/tsotchke/eshkol/blob/master/docs/breakdown/PACKAGE_MANAGER.md A full example of a project manifest including package metadata and dependencies. ```toml [package] name = "signal-proc" version = "0.3.1" description = "Digital signal processing utilities for Eshkol" author = "Bob " license = "Apache-2.0" entry = "src/main.esk" sources = ["src/*.esk", "src/filters/*.esk"] [dependencies] numerics = "1.0.0" fft-lib = "https://github.com/example/eshkol-fft.git" ``` -------------------------------- ### Optimizer Examples Source: https://github.com/tsotchke/eshkol/blob/master/docs/API_REFERENCE.md Provides example usage of various optimizer steps and gradient safety checks. ```APIDOC ### Optimizer Examples ```scheme ;; Simple SGD training step (define params #(1.0 2.0 3.0)) (define grads #(0.1 -0.2 0.05)) (sgd-step params grads 0.01) ; params modified in-place ;; Adam with bias correction (define m (make-tensor (list 3) 0.0)) ; first moment (zeros) (define v (make-tensor (list 3) 0.0)) ; second moment (zeros) (adam-step params grads 0.001 m v 1) ; step 1 ;; Gradient safety (zero-grad! grads) ; zero before next forward pass (let ((norm (clip-grad-norm! grads 1.0))) (when (> norm 10.0) (display "Warning: gradient explosion detected\n"))) (when (> (check-grad-health grads) 0) (display "Error: NaN/Inf in gradients\n")) ``` ``` -------------------------------- ### Optimization level examples Source: https://github.com/tsotchke/eshkol/blob/master/docs/breakdown/COMMAND_LINE_REFERENCE.md Commands for setting LLVM optimization levels. ```bash # No optimization (for readable IR) eshkol-run program.esk -o program -O 0 --dump-ir # Aggressive optimization eshkol-run program.esk -o program -O 3 ``` -------------------------------- ### Install LLVM 21 on Ubuntu/Debian Source: https://github.com/tsotchke/eshkol/blob/master/docs/FAQ.md Add the LLVM repository and install the necessary packages. ```bash wget -qO- https://apt.llvm.org/llvm-snapshot.gpg.key | sudo tee /etc/apt/trusted.gpg.d/apt.llvm.org.asc >/dev/null echo "deb http://apt.llvm.org/jammy/ llvm-toolchain-jammy-21 main" | sudo tee /etc/apt/sources.list.d/llvm.list sudo apt update && sudo apt install llvm-21 llvm-21-dev ``` -------------------------------- ### Learning Rate Scheduler Examples Source: https://github.com/tsotchke/eshkol/blob/master/docs/breakdown/MACHINE_LEARNING.md Examples demonstrating different learning rate scheduling strategies. These are pure functions and do not have mutable state. ```scheme (define lr (if (< step 4000) (linear-warmup-lr 0.001 step 4000) (cosine-annealing-lr 0.001 1e-6 step 100000))) ``` ```scheme (step-decay-lr 0.1 0.1 epoch 30) ; reduce 10x every 30 epochs ``` ```scheme (exponential-decay-lr 0.01 0.95 epoch) ; 5% decay per epoch ``` -------------------------------- ### Installing a Published Eshkol Package Source: https://github.com/tsotchke/eshkol/blob/master/docs/breakdown/PACKAGE_MANAGER.md Commands to add a package from the Eshkol registry and then install all project dependencies. ```bash eshkol-pkg add my-package 0.3.1 eshkol-pkg install ``` -------------------------------- ### Install Eshkol Project Dependencies Source: https://github.com/tsotchke/eshkol/blob/master/docs/breakdown/PACKAGE_MANAGER.md Installs all declared dependencies, cloning them into the Eshkol cache and creating a symlink for the project. Ensure dependencies are added before running this. ```sh eshkol-pkg install ``` -------------------------------- ### Eshkol Gradual Typing Examples Source: https://github.com/tsotchke/eshkol/blob/master/docs/vision/PURPOSE_AND_VISION.md Illustrates Eshkol's gradual typing system with examples of dynamic typing, partial type annotations for type-guided optimization, and full annotations for maximum optimization. ```scheme ; No annotations - dynamic typing (define (f x) (* x x)) ; Partial annotations - type-guided optimization (define (g (x : real)) (* x x)) ; Full annotations - maximum optimization (define (h (x : real)) : real (* x x)) ``` -------------------------------- ### Homoiconic Metaprogramming Example Source: https://github.com/tsotchke/eshkol/blob/master/docs/vision/DIFFERENTIATION_ANALYSIS.md Demonstration of function creation in Python. ```python # No code-as-data def make_multiplier(n): return lambda x: x * n f = make_multiplier(5) ``` -------------------------------- ### Browser REPL Examples Source: https://github.com/tsotchke/eshkol/blob/master/docs/tutorials/18_WEB_PLATFORM.md The browser REPL at eshkol.ai supports Scheme primitives, exact arithmetic, autodiff, complex numbers, higher-order functions, closures, and continuations. Examples include calculating factorials and derivatives. ```scheme (define (factorial n) (if (= n 0) 1 (* n (factorial (- n 1))))) (display (factorial 20)) ;; => 2432902008176640000 ``` ```scheme (display (derivative (lambda (x) (* x x x)) 2.0)) ;; => 12.0 ``` -------------------------------- ### Eshkol Quantum Type System Example Source: https://github.com/tsotchke/eshkol/blob/master/docs/future/external/eshkol_quantum_computing.md Demonstrates Eshkol's gradual typing system extended to quantum types, including qubit, qreg, qstate, and qop. It shows a function signature for preparing a quantum state and an example of how the no-cloning theorem is enforced by the type checker. ```scheme (: prepare-state (-> (vector) qstate)) ;; This would be rejected by the type checker (define (clone-qubit q) (let ((q1 q) ; Error: Cannot use qubit q multiple times (q2 q)) (values q1 q2))) ``` -------------------------------- ### Environment Variable Operations Source: https://github.com/tsotchke/eshkol/blob/master/docs/API_REFERENCE.md Examples of getting and setting environment variables. ```scheme (getenv "PATH") (setenv "MY_VAR" "value" 1) ``` -------------------------------- ### Install and Build from Source Source: https://github.com/tsotchke/eshkol/blob/master/docs/breakdown/DEVELOPER_TOOLS.md Commands for compiling the extension and building the language server binary. ```bash cd tools/vscode-eshkol npm install npm run compile # produces out/extension.js ``` ```bash cd build && make -j8 # eshkol-lsp binary is placed in build/bin/ ``` -------------------------------- ### Right Fold Example Source: https://github.com/tsotchke/eshkol/blob/master/COMPLETE_LANGUAGE_SPECIFICATION.md The `fold-right` (or `foldr`) function accumulates a result by applying a procedure from right to left, starting with an initial value. ```scheme (fold-right cons '() '(1 2 3)) ; => (1 2 3) ``` -------------------------------- ### Line-based File I/O Source: https://github.com/tsotchke/eshkol/blob/master/docs/API_REFERENCE.md Examples of reading and writing lines to files. ```scheme (define in (open-input-file "file.txt")) (define line (read-line in)) ; Returns string or EOF (define out (open-output-file "out.txt")) (write-line out "Hello, World!") ``` -------------------------------- ### Left Fold Example Source: https://github.com/tsotchke/eshkol/blob/master/COMPLETE_LANGUAGE_SPECIFICATION.md The `fold` (or `foldl`) function accumulates a result by applying a procedure from left to right, starting with an initial value. ```scheme (fold + 0 '(1 2 3 4)) ; => 10 ``` ```scheme (fold cons '() '(1 2 3)) ; => (3 2 1) ``` -------------------------------- ### Get Sublist from Nth Element Source: https://github.com/tsotchke/eshkol/blob/master/COMPLETE_LANGUAGE_SPECIFICATION.md Returns a new list containing the elements of `lst` starting from the zero-based index `n` to the end. ```Eshkol (list-tail lst n) ``` -------------------------------- ### Initialize Eshkol Project Source: https://github.com/tsotchke/eshkol/blob/master/docs/API_REFERENCE.md Use the `init` command to create a new `eshkol.toml` project file in the current directory. ```bash eshkol-pkg init ``` -------------------------------- ### REPL Session Example Source: https://github.com/tsotchke/eshkol/blob/master/docs/breakdown/COMPILATION_GUIDE.md Demonstrates defining functions, evaluating expressions, and using REPL-specific commands. ```scheme eshkol> (define (factorial n) (if (<= n 1) 1 (* n (factorial (- n 1))))) eshkol> (factorial 20) 2432902008176640000 eshkol> (gradient (lambda (x) (* x x)) 3.0) 6.0 eshkol> :type (+ 1 2) integer eshkol> :time (factorial 1000) [result] Elapsed: 0.002s eshkol> :quit ``` -------------------------------- ### Getting Started with Eshkol Random Functions Source: https://github.com/tsotchke/eshkol/blob/master/docs/breakdown/QUANTUM_RNG.md Demonstrates basic usage of both standard PRNG and quantum-inspired RNG functions in Eshkol. Ensure 'random' is required before use. ```scheme (require random) ;; Standard PRNG (display (random-float)) ; => 0.7234... (uniform [0,1)) (display (random-int 1 6)) ; => 4 (dice roll) ;; Quantum-inspired RNG (display (qrandom)) ; => 0.5128... (quantum uniform [0,1)) (display (qrandom-int 1 6)) ; => 2 (quantum dice roll) ``` -------------------------------- ### Scheme list queries Source: https://github.com/tsotchke/eshkol/blob/master/ESHKOL_V1_LANGUAGE_REFERENCE.md Functions to get information about lists: `length` for the number of elements, `list-ref` for the nth element (0-indexed), and `list-tail` for the sublist starting at the nth element. ```scheme (define lst '(10 20 30 40 50)) (length lst) ; => 5 (length '()) ; => 0 ; Get nth element (0-indexed) (list-ref lst 0) ; => 10 (list-ref lst 2) ; => 30 ; Get sublist from position n (list-tail lst 2) ; => (30 40 50) (list-tail lst 0) ; => (10 20 30 40 50) ``` -------------------------------- ### Debug and diagnostic examples Source: https://github.com/tsotchke/eshkol/blob/master/docs/breakdown/COMMAND_LINE_REFERENCE.md Commands for inspecting AST, IR, and using debuggers. ```bash # Dump AST for inspection eshkol-run program.esk -o program --dump-ast cat program.ast # Dump LLVM IR for codegen debugging eshkol-run program.esk -o program --dump-ir cat program.ll # Compile with debug info for lldb eshkol-run program.esk -o program -g lldb ./program # Verbose debug output eshkol-run -d program.esk -o program ``` -------------------------------- ### Hash Table Creation and Lookup Example Source: https://github.com/tsotchke/eshkol/blob/master/COMPLETE_LANGUAGE_SPECIFICATION.md Demonstrates creating a hash table with initial key-value pairs and then retrieving a value by its key. ```scheme (define h (hash 'a 1 'b 2)) (hash-ref h 'a) ``` -------------------------------- ### Build and Run Eshkol Programs Source: https://github.com/tsotchke/eshkol/blob/master/ESHKOL_LANGUAGE_GUIDE.md Instructions for cloning the Eshkol repository, building the project, running a program, compiling to a binary, and starting the interactive REPL. ```bash git clone https://github.com/tsotchke/eshkol.git cd eshkol mkdir build && cd build cmake .. && make -j8 ./eshkol-run examples/fibonacci.esk ./eshkol-run program.esk -o program ./program ./eshkol-repl ``` -------------------------------- ### Generate n Numbers from Start Source: https://github.com/tsotchke/eshkol/blob/master/COMPLETE_LANGUAGE_SPECIFICATION.md Generates a list of `n` consecutive integers starting from `start`. ```Eshkol (iota-from n start) ``` -------------------------------- ### Forward-Mode Automatic Differentiation in Eshkol Source: https://context7.com/tsotchke/eshkol/llms.txt Illustrates forward-mode automatic differentiation using dual number arithmetic in Eshkol. This mode is efficient for computing first derivatives of scalar functions. Examples show direct computation at a point, currying to get a derivative function, and automatic application of the chain rule, including second derivatives via nesting. ```scheme ;; Define function f(x) = x³ (define (f x) (* x x x)) ;; Compute derivative at point: f'(x) = 3x² (derivative f 2.0) ;; => 12.0 ;; Higher-order: returns derivative function (define df (derivative f)) (df 3.0) ;; => 27.0 ;; Chain rule applied automatically (define (g x) (sin (* x x))) (derivative g 1.0) ;; => 1.0806... (cos(1) * 2) ;; Second derivative via nesting (define (h x) (* x x x)) (define dh (derivative h)) (define ddh (derivative dh)) (ddh 2.0) ;; => 12.0 (h''(x) = 6x) ``` -------------------------------- ### Install LLVM on macOS Source: https://github.com/tsotchke/eshkol/blob/master/docs/breakdown/COMPILATION_GUIDE.md Install LLVM using Homebrew on macOS and set the LLVM_DIR environment variable to help CMake find the installation. ```bash brew install llvm@21 export LLVM_DIR=$(brew --prefix llvm@21)/lib/cmake/llvm ``` -------------------------------- ### Initialize New Eshkol Project Source: https://github.com/tsotchke/eshkol/blob/master/docs/breakdown/PACKAGE_MANAGER.md Commands to create a new project directory, initialize the Eshkol manifest file (`eshkol.toml`), and generate the entry point source file. ```bash mkdir vec-utils && cd vec-utils eshkol-pkg init # => Created eshkol.toml for project 'vec-utils' # => src/main.esk created ``` -------------------------------- ### Configure Build Options Source: https://github.com/tsotchke/eshkol/blob/master/docs/breakdown/COMPILATION_GUIDE.md Examples of enabling or disabling specific features like GPU, BLAS, XLA, and sanitizers. ```bash # Full build with GPU + BLAS (default) cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Release # Minimal build (no GPU, no BLAS) cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Release \ -DESHKOL_GPU_ENABLED=OFF -DESHKOL_BLAS_ENABLED=OFF # XLA build (requires MLIR + StableHLO) cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Release \ -DESHKOL_XLA_ENABLED=ON -DSTABLEHLO_ROOT=/path/to/stablehlo # Debug build with sanitizers cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Debug \ -DESHKOL_ENABLE_ASAN=ON -DESHKOL_ENABLE_UBSAN=ON ``` -------------------------------- ### Install Eshkol on macOS Source: https://github.com/tsotchke/eshkol/blob/master/docs/QUICKSTART.md Use Homebrew to install the Eshkol package. ```bash brew tap tsotchke/eshkol brew install eshkol ``` -------------------------------- ### Configure Extension Settings Source: https://github.com/tsotchke/eshkol/blob/master/docs/breakdown/VSCODE_EXTENSION.md Example configuration for settings.json to define paths for the LSP and compiler. ```json { "eshkol.lsp.enabled": true, "eshkol.lsp.path": "/usr/local/bin/eshkol-lsp", "eshkol.compiler.path": "/usr/local/bin/eshkol-run" } ``` -------------------------------- ### Install Eshkol on Linux Source: https://github.com/tsotchke/eshkol/blob/master/docs/QUICKSTART.md Install the package using the Debian/Ubuntu package manager. ```bash # Download .deb from https://github.com/tsotchke/eshkol/releases sudo dpkg -i eshkol_*.deb ``` -------------------------------- ### Interact with the REPL Source: https://github.com/tsotchke/eshkol/blob/master/docs/breakdown/GETTING_STARTED.md Example session demonstrating function definition, list processing, and gradient calculation. ```scheme eshkol> (define (square x) (* x x)) eshkol> (square 5) 25 eshkol> (define numbers (list 1 2 3 4 5)) eshkol> (map square numbers) (1 4 9 16 25) eshkol> (fold + 0 numbers) 15 eshkol> (gradient (lambda (x) (* x x)) 3.0) 6.0 ``` -------------------------------- ### Generate Range of Numbers Source: https://github.com/tsotchke/eshkol/blob/master/COMPLETE_LANGUAGE_SPECIFICATION.md Generates a list of integers starting from `start` up to (but not including) `end`. ```Eshkol (range start end) ``` -------------------------------- ### Install Eshkol on Ubuntu/Debian Source: https://github.com/tsotchke/eshkol/blob/master/docs/breakdown/GETTING_STARTED.md Commands to install dependencies and build Eshkol on Debian-based systems. ```bash # Install dependencies sudo apt-get update sudo apt-get install -y \ llvm-21 \ llvm-21-dev \ clang-21 \ cmake ninja-build \ build-essential # Build Eshkol cmake -B build -DCMAKE_BUILD_TYPE=Release cmake --build build -j$(nproc) ``` -------------------------------- ### Knowledge Base Creation and Querying in Scheme Source: https://github.com/tsotchke/eshkol/blob/master/ESHKOL_V1_LANGUAGE_REFERENCE.md Demonstrates creating a knowledge base, asserting facts, and performing pattern-based queries using `kb-query`. ```scheme (define kb (make-kb)) (display (kb? kb)) ; => #t ;; Assert facts (kb-assert! kb (make-fact 'parent 'alice 'bob)) (kb-assert! kb (make-fact 'parent 'bob 'charlie)) ;; Query (define results (kb-query kb 'parent 'alice ?who)) ;; results contains substitutions binding ?who to 'bob ``` -------------------------------- ### Install LLVM 21 on macOS Source: https://github.com/tsotchke/eshkol/blob/master/docs/FAQ.md Use Homebrew to install the required LLVM version. ```bash brew install llvm@21 ``` -------------------------------- ### Install Eshkol on macOS Source: https://github.com/tsotchke/eshkol/blob/master/docs/breakdown/GETTING_STARTED.md Commands to install dependencies via Homebrew and build Eshkol on macOS. ```bash # Install dependencies via Homebrew brew install llvm@21 cmake ninja # Build Eshkol cmake -B build -G Ninja \ -DCMAKE_BUILD_TYPE=Release \ -DLLVM_DIR=$(brew --prefix llvm@21)/lib/cmake/llvm cmake --build build -j$(sysctl -n hw.ncpu) ``` -------------------------------- ### Compile output control examples Source: https://github.com/tsotchke/eshkol/blob/master/docs/breakdown/COMMAND_LINE_REFERENCE.md Common commands for generating binaries, object files, libraries, and bytecode. ```bash # Compile to native binary eshkol-run hello.esk -o hello # Compile to object file only eshkol-run module.esk -c -o module.o # Compile as shared library eshkol-run mylib.esk -s -o mylib.o # Compile to WebAssembly eshkol-run app.esk -w -o app.wasm # Emit bytecode eshkol-run program.esk -B program.eskb ``` -------------------------------- ### Build Eshkol from Source Source: https://github.com/tsotchke/eshkol/blob/master/README.md Instructions for cloning the Eshkol repository, configuring the build with CMake, and compiling the project. Includes steps for building the REPL and setting the PATH. ```bash git clone https://github.com/tsotchke/eshkol.git cd eshkol # Configure build cmake -B build -DCMAKE_BUILD_TYPE=Release # Compile (parallel build recommended) cmake --build build -j$(nproc) # Optional: Build interactive REPL cmake --build build --target eshkol-repl # Add to path export PATH=$PATH:$(pwd)/build ``` -------------------------------- ### Create and Run Hello World Source: https://github.com/tsotchke/eshkol/blob/master/docs/breakdown/GETTING_STARTED.md A basic Hello World program in Eshkol and the commands to compile and execute it. ```scheme (display "Hello, Eshkol!") (newline) ``` ```bash # Compile (generates executable in current directory) build/eshkol-run hello.esk # Run ./hello # Output: Hello, Eshkol! ``` -------------------------------- ### Hello World in Eshkol Source: https://github.com/tsotchke/eshkol/blob/master/docs/future/external/eshkol_explained.md A basic entry point example demonstrating the standard main function structure in Eshkol, which returns an integer status code. ```scheme (define (main) (printf "Hello, Eshkol!\n") 0) ``` -------------------------------- ### Install OpenBLAS on Fedora/RHEL Source: https://github.com/tsotchke/eshkol/blob/master/docs/breakdown/COMPILATION_GUIDE.md Install the OpenBLAS development package on Fedora/RHEL systems to enable BLAS acceleration. ```bash sudo dnf install openblas-devel ``` -------------------------------- ### Serve Eshkol Website Locally Source: https://github.com/tsotchke/eshkol/blob/master/site/static/content/contributing.html Start a simple HTTP server in the site/static directory to serve the website locally. Access it via http://localhost:8888. ```bash cd site/static && python3 -m http.server 8888 ``` -------------------------------- ### Build Eshkol Website and REPL VM Source: https://github.com/tsotchke/eshkol/blob/master/CONTRIBUTING.md Compile the Eshkol website to WebAssembly and rebuild the browser REPL VM using emcc. Then, serve the static site locally. ```bash # Compile the website ./build/eshkol-run --wasm site/src/main.esk -o site/static/eshkol-site.wasm # Rebuild the browser REPL VM emcc -O2 -s WASM=1 -s MODULARIZE=1 -s EXPORT_NAME='EshkolVM' \ -DESHKOL_VM_WASM -DESHKOL_VM_NO_DISASM \ -I lib/backend lib/backend/vm_wasm_repl.c \ -o site/static/eshkol-vm.js -lm # Serve locally cd site/static && python3 -m http.server 8888 ``` -------------------------------- ### Quick Build Repository Source: https://github.com/tsotchke/eshkol/blob/master/docs/breakdown/COMPILATION_GUIDE.md Standard workflow to clone the repository and build the five core executables using Ninja. ```bash # Clone repository git clone https://github.com/tsotchke/eshkol.git cd eshkol # Configure with Ninja (recommended) cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Release # Build (produces 5 executables) cmake --build build -j$(nproc) # Executables in build/ ls build/eshkol-* # eshkol-run - AOT compiler / JIT runner # eshkol-repl - Interactive REPL # eshkol-pkg - Package manager # eshkol-lsp - LSP server # eshkol-server - Web server ``` -------------------------------- ### Install OpenBLAS on Ubuntu/Debian Source: https://github.com/tsotchke/eshkol/blob/master/docs/breakdown/COMPILATION_GUIDE.md Install the OpenBLAS development library on Ubuntu/Debian to enable BLAS acceleration for matrix operations. ```bash sudo apt-get install libopenblas-dev ``` -------------------------------- ### Matrix Multiplication Example Source: https://github.com/tsotchke/eshkol/blob/master/site/static/content/api_reference.html Example demonstrating matrix multiplication using the einsum function with predefined tensors A and B. ```lisp (define A #((1.0 2.0) (3.0 4.0))) (define B #((5.0 6.0) (7.0 8.0))) (einsum "ij,jk->ik" A B) ``` -------------------------------- ### Eshkol REPL Example Session Source: https://github.com/tsotchke/eshkol/blob/master/site/static/content/eshkol_language_guide.html A sample session demonstrating the interactive REPL, including defining functions, performing calculations, and using built-in utilities. ```eshkol (define (square x) (* x x)) ``` ```eshkol (square 5) ``` ```eshkol (map square (list 1 2 3 4 5)) ``` ```eshkol (expt 2 256) ``` ```eshkol (+ 1/3 1/6) ``` ```eshkol (parallel-map square (iota 8)) ``` ```eshkol (derivative (lambda (x) (* x x x)) 2.0) ``` -------------------------------- ### Library management examples Source: https://github.com/tsotchke/eshkol/blob/master/docs/breakdown/COMMAND_LINE_REFERENCE.md Commands for linking external libraries and managing standard library inclusion. ```bash # Link with a custom library eshkol-run program.esk -o program -l mylib -L /path/to/libs # Compile without standard library eshkol-run minimal.esk -o minimal -n # Use build directory as library path eshkol-run program.esk -o program -L build/ ``` -------------------------------- ### Eshkol TOML Manifest Example Source: https://github.com/tsotchke/eshkol/blob/master/docs/API_REFERENCE.md Example structure for an `eshkol.toml` manifest file, defining package metadata and dependencies. ```toml [package] name = "my-project" version = "0.1.0" description = "A scientific computing project" author = "Author Name" license = "MIT" entry = "src/main.esk" sources = ["src/*.esk"] [dependencies] math-utils = "1.0.0" ``` -------------------------------- ### Create an Interactive Counter Application Source: https://github.com/tsotchke/eshkol/blob/master/docs/breakdown/WEB_PLATFORM.md A complete example demonstrating state management, canvas rendering, DOM construction, and local storage persistence. ```scheme ;;; counter-app.esk — Interactive counter with canvas visualisation (require web) ;;; ─── State ──────────────────────────────────────────────────────────────── (define state (vector 0)) ; count (define (get-count) (vector-ref state 0)) (define (set-count! n) (vector-set! state 0 n)) ;;; ─── Canvas bar chart ───────────────────────────────────────────────────── (define canvas #f) (define ctx #f) (define (draw-chart) (let* ((count (get-count)) (bar-w 200.0) (bar-h (* (min count 20) 10.0)) (cx 50.0) (cy (- 200.0 bar-h))) ;; Background (web-canvas-fill-style ctx "#1E293B") (web-canvas-fill-rect ctx 0.0 0.0 400.0 220.0) ;; Bar (web-canvas-fill-style ctx "#3B82F6") (web-canvas-fill-rect ctx cx cy bar-w bar-h) ;; Label (web-canvas-fill-style ctx "#F8FAFC") (web-canvas-font ctx "16px monospace") (web-canvas-fill-text ctx (string-append "count=" (number->string count)) (+ cx 10.0) (- cy 8.0)))) ;;; ─── Persistence ────────────────────────────────────────────────────────── (define (save-state!) (web-storage-set "count" (number->string (get-count)))) ;;; ─── DOM construction ───────────────────────────────────────────────────── (define (build-ui) (let ((body (web-get-body))) ;; Outer container (define app (web-create-element "div")) (web-add-class app "app-container") (web-set-style app "fontFamily" "sans-serif") (web-set-style app "padding" "32px") ;; Title (define title (web-create-element "h1")) (web-set-text-content title "Eshkol Counter") (web-append-child app title) ;; Canvas (set! canvas (web-create-element "canvas")) (web-set-attribute canvas "width" "400") (web-set-attribute canvas "height" "220") (web-append-child app canvas) (set! ctx (web-get-context-2d canvas)) ;; Button row (define row (web-create-element "div")) (web-set-style row "marginTop" "16px") (define dec-btn (web-create-element "button")) (web-set-text-content dec-btn "- Decrement") (web-add-event-listener dec-btn "click" (lambda (_ev) (when (> (get-count) 0) (set-count! (- (get-count) 1)) (save-state!) (draw-chart)))) (web-append-child row dec-btn) (define inc-btn (web-create-element "button")) (web-set-text-content inc-btn "+ Increment") (web-set-style inc-btn "marginLeft" "8px") (web-add-event-listener inc-btn "click" (lambda (_ev) (set-count! (+ (get-count) 1)) (save-state!) (draw-chart))) (web-append-child row inc-btn) (define reset-btn (web-create-element "button")) (web-set-text-content reset-btn "Reset") (web-set-style reset-btn "marginLeft" "8px") (web-add-event-listener reset-btn "click" (lambda (_ev) (set-count! 0) (save-state!) (draw-chart))) (web-append-child row reset-btn) (web-append-child app row) (web-append-child body app) ;; Release temporary element handles (still live in DOM via JS ref) (web-release-handle title) (web-release-handle row) (web-release-handle dec-btn) (web-release-handle inc-btn) (web-release-handle reset-btn) (web-release-handle app))) ;;; ─── Startup ────────────────────────────────────────────────────────────── ;; Restore persisted count if present ;; (buffer read pattern omitted for brevity — see web-storage-get docs) (build-ui) (draw-chart) ``` -------------------------------- ### Generate List with Custom Step Source: https://github.com/tsotchke/eshkol/blob/master/COMPLETE_LANGUAGE_SPECIFICATION.md Generates a list of `n` numbers starting from `start` with a specified `step` between consecutive elements. ```Eshkol (iota-step n start step) ``` -------------------------------- ### Example Eshkol Configuration File Source: https://github.com/tsotchke/eshkol/blob/master/docs/breakdown/RUNTIME_CONFIGURATION.md This TOML file demonstrates how to configure runtime limits, logging, optimization, and debugging settings for the Eshkol compiler. ```toml # .eshkol.toml [runtime] max_heap = "2G" timeout_ms = 60000 max_stack_depth = 200000 [logging] level = "info" format = "text" [optimization] llvm_opt_level = 2 enable_simd = true enable_gpu = false [debug] dump_ast = false dump_ir = false [types] strict = false unsafe = false ``` -------------------------------- ### Neural Network Example Source: https://github.com/tsotchke/eshkol/blob/master/docs/API_REFERENCE.md A practical example demonstrating the implementation of a neural network, including forward pass and training with gradient descent. ```APIDOC ## Code Examples ### Neural Network Example ```scheme (import core.functional) (import core.list.higher_order) ; Sigmoid activation (define (sigmoid x) (/ 1.0 (+ 1.0 (exp (- x))))) ; Forward pass (2-layer network) (define (forward W1 W2 x) (let* ((h (tensor-apply (matmul W1 x) sigmoid)) (y (matmul W2 h))) y)) ; Training with gradient descent (define (train W1 W2 x target learning-rate) (let* ((loss-fn (lambda (w1 w2) (let ((pred (forward w1 w2 x))) (* 0.5 (norm (tensor-sub pred target))))))) (grad-w1 (gradient (lambda (w) (loss-fn w W2)) W1)) (grad-w2 (gradient (lambda (w) (loss-fn W1 w)) W2))) (values (tensor-sub W1 (tensor-mul learning-rate grad-w1)) (tensor-sub W2 (tensor-mul learning-rate grad-w2))))) ``` ``` -------------------------------- ### Standard Library Integration Source: https://github.com/tsotchke/eshkol/blob/master/docs/breakdown/REPL_JIT.md Demonstrates loading the standard library and using its functions within the REPL. ```scheme eshkol> (require stdlib) ;; loadStdlib(): ;; addObjectFile(main_dylib, stdlib.o) — instant, no recompile ;; registerStdlibSymbols(): ;; parseBitcodeFile("stdlib.bc") ;; discovers 237 functions, 305 globals ;; loaded_modules += {stdlib, core.io, core.list.*, ...} eshkol> (map (lambda (x) (* x x)) '(1 2 3 4 5)) ;; map resolved from stdlib.o, lambda compiled by JIT, list from stdlib ;; => (1 4 9 16 25) ``` -------------------------------- ### Thread Pool Introspection Examples Source: https://github.com/tsotchke/eshkol/blob/master/docs/breakdown/PARALLEL_COMPUTING.md Provides examples for querying thread pool information, including available parallelism and detailed statistics. ```scheme ;; Query available parallelism (display (thread-pool-info)) ; => 8 (on an 8-core machine) ;; Print detailed metrics (thread-pool-stats) ;; Output: ;; Mode: work-stealing ;; Threads: 8 ;; Tasks: submitted=1000, completed=1000, pending=0 ;; Local executions: 800 ;; Tasks stolen: 200 ;; Steal ratio: 20.0% ``` -------------------------------- ### Bytecode VM Initialization Source: https://github.com/tsotchke/eshkol/blob/master/site/static/index.html Configures the Eshkol VM for browser-based REPL execution, capturing standard output and error streams. ```javascript window._vmOutput = ''; window._vmStderr = ''; if (typeof EshkolVM !== 'undefined') { EshkolVM({ print: (text) => { window._vmOutput += text + '\n'; }, printErr: (text) => { window._vmStderr += text + '\n'; console.warn('[VM]', text); } }).then(vm => { runtime._eshkolVM = vm; vm.ccall('repl_init', null, [], []); console.log('Eshkol VM REPL ready (bytecode interpreter)'); window._eshkolVM = vm; }).catch(e => console.warn('VM load deferred:', e.message)); } ``` -------------------------------- ### Interactive REPL Usage Source: https://github.com/tsotchke/eshkol/blob/master/docs/breakdown/COMPILER_ARCHITECTURE.md Example session demonstrating function definition, execution, and automatic differentiation. ```bash eshkol-repl > (define (fib n) (if (< n 2) n (+ (fib (- n 1)) (fib (- n 2))))) > (fib 30) 832040 > (gradient (lambda (x) (* x x)) 3.0) 6.0 ``` -------------------------------- ### Install Eshkol on Windows Source: https://github.com/tsotchke/eshkol/blob/master/docs/QUICKSTART.md Build from source using Visual Studio 2022 and LLVM. ```powershell # In Developer PowerShell for VS 2022: git clone https://github.com/tsotchke/eshkol.git cd eshkol cmake -S . -B build -G "Visual Studio 17 2022" -A x64 -T ClangCL ` -DCMAKE_BUILD_TYPE=Release ` -DLLVM_DIR="C:/Program Files/LLVM/lib/cmake/llvm" cmake --build build --config Release --parallel ``` -------------------------------- ### Weight Initialization Examples Source: https://github.com/tsotchke/eshkol/blob/master/docs/breakdown/MACHINE_LEARNING.md Examples of applying Xavier and Kaiming initializers to tensors. Xavier is suitable for sigmoid/tanh, while Kaiming is for ReLU layers. ```scheme (define W (make-tensor (list 256 128) 0.0)) (xavier-uniform! W 256 128) ; sigmoid/tanh layers (kaiming-normal! W 256) ; ReLU layers ``` -------------------------------- ### ReLU Activation Function Example Source: https://github.com/tsotchke/eshkol/blob/master/docs/breakdown/MACHINE_LEARNING.md Example of applying the ReLU activation function to a tensor. ReLU computes `max(0, x)`. ```scheme (relu #(1.0 -2.0 3.0 -0.5)) ; => #(1.0 0.0 3.0 0.0) ``` -------------------------------- ### Query Knowledge Base with kb-query Source: https://github.com/tsotchke/eshkol/blob/master/docs/API_REFERENCE.md Demonstrates building a knowledge base and performing queries to retrieve substitutions based on fact patterns. ```scheme ;; Build a family knowledge base (define kb (make-kb)) (kb-assert! kb (make-fact 'parent 'alice 'bob)) (kb-assert! kb (make-fact 'parent 'bob 'charlie)) (kb-assert! kb (make-fact 'parent 'alice 'diana)) ;; Query: who are bob's parents? (define results (kb-query kb (make-fact 'parent ?who 'bob))) ;; results: list with one substitution where ?who = 'alice ;; Query: who are alice's children? (define children (kb-query kb (make-fact 'parent 'alice ?child))) ;; children: list of substitutions where ?child = 'bob and ?child = 'diana ;; Query with no matches (define empty (kb-query kb (make-fact 'sibling ?a ?b))) ;; empty: '() ``` -------------------------------- ### Complete Signal Processing Pipeline Example Source: https://github.com/tsotchke/eshkol/blob/master/docs/breakdown/SIGNAL_PROCESSING.md Demonstrates a full pipeline including signal synthesis, windowing, spectral analysis, bandpass filtering, frequency response checking, and spectral reconstruction. ```APIDOC ## Complete Pipeline Example ### Description This example demonstrates a full analysis and reconstruction pipeline: synthesizing a two-tone signal, applying a window, computing the spectrum, designing and applying a bandpass filter, and verifying the result via frequency response. ### Code Example ```scheme (require signal) ;;; --- Signal Generation --- ;;; 256-sample signal at normalized frequencies 0.1 and 0.4 (define N 256) (define signal (make-vector N 0.0)) (letrec ((gen (lambda (i) (if (< i N) (begin (vector-set! signal i (+ (* 1.0 (sin (* 2.0 3.14159 0.1 i))) ; 0.1 * Nyquist tone (* 0.5 (sin (* 2.0 3.14159 0.4 i))))) ; 0.4 * Nyquist tone (quieter) (gen (+ i 1))))))) (gen 0)) ;;; --- Windowing --- ;;; Apply Hann window to reduce spectral leakage before FFT (define window (hann-window N)) (define windowed-signal (apply-window signal window)) ;;; --- Spectral Analysis --- ;;; Compute FFT. Bins 0..N/2-1 cover DC to Nyquist. ;;; Bin k corresponds to frequency k/N * fs_normalized. (define spectrum (fft windowed-signal)) ;;; Bin 26 (≈ 0.1*256) should show the first tone. ;;; Bin 102 (≈ 0.4*256) should show the second tone. ;;; --- Bandpass Filtering --- ;;; Isolate the band 0.05–0.25 Nyquist to keep only the first tone. (define bp-filters (butterworth-bandpass 4 0.05 0.25)) (define lp-pair (car bp-filters)) (define hp-pair (cadr bp-filters)) (define after-lp (iir-filter (car lp-pair) (cdr lp-pair) signal)) (define filtered (iir-filter (car hp-pair) (cdr hp-pair) after-lp)) ;;; --- Frequency Response Check --- ;;; Verify the lowpass stage is well-behaved. (define resp (frequency-response (car lp-pair) (cdr lp-pair) 128)) (define mags (car resp)) ;;; (vref mags 0) should be ≈ 1.0 (DC passes) ;;; (vref mags 64) should be ≈ 0.0 (Nyquist is attenuated) ;;; --- Spectral Reconstruction (Synthesis) --- ;;; Inverse FFT to reconstruct time-domain signal from modified spectrum. (define reconstructed (ifft spectrum)) ;;; Take real parts for a pure real output: (define reconstructed-real (let ((result (make-vector N 0.0))) (letrec ((loop (lambda (i) (if (< i N) (begin (vector-set! result i (real-part (vref reconstructed i))) (loop (+ i 1))))))) (loop 0)) result)) ``` ``` -------------------------------- ### Example Hover Content for Gradient Source: https://github.com/tsotchke/eshkol/blob/master/docs/breakdown/DEVELOPER_TOOLS.md This example shows the expected markdown format for hover information, including the function signature and a brief explanation. ```markdown (gradient f) -> f' Compute gradient of f via autodiff. ``` -------------------------------- ### Apply Let Bindings Source: https://github.com/tsotchke/eshkol/blob/master/docs/breakdown/GETTING_STARTED.md Demonstration of parallel, sequential, and recursive variable bindings. ```scheme ;; let - parallel bindings (let ((x 1) (y 2)) (+ x y)) ; Returns 3 ;; let* - sequential bindings (let* ((x 1) (y (* x 2))) ; y can reference x (+ x y)) ; Returns 3 ;; letrec - recursive bindings (letrec ((even? (lambda (n) (if (= n 0) #t (odd? (- n 1))))) (odd? (lambda (n) (if (= n 0) #f (even? (- n 1)))))) (even? 10)) ; Returns #t ``` -------------------------------- ### Expression evaluation examples Source: https://github.com/tsotchke/eshkol/blob/master/ESHKOL_V1_LANGUAGE_REFERENCE.md All constructs in Eshkol are expressions that return a value. Examples include literals, function calls, conditional expressions, and begin blocks. ```scheme 42 ; => 42 (+ 1 2) ; => 3 (if #t 1 2) ; => 1 (begin (display "hi") 5) ; Prints "hi", returns 5 ``` -------------------------------- ### Import Standard Library Modules Source: https://github.com/tsotchke/eshkol/blob/master/docs/QUICKSTART.md Demonstrates how to import specific modules or the entire standard library in Eshkol. ```scheme ; Import modules (require core.list.higher_order) ; fold, filter, any, every (require core.list.sort) ; sort, merge (require core.functional) ; compose, curry, flip (require core.strings) ; String utilities (require core.json) ; JSON parsing ; Or import everything at once (require stdlib) ```