### Quick Start Logging Examples Source: https://kit-lang.org/docs/2026.5.3/stdlib/logging.html Use global convenience functions for simple logging at different levels with optional structured fields. ```kit import IO.Logging as Log # Log messages at different levels Log.debug "Debugging info" {} Log.info "Application started" {version: "1.0.0"} Log.warn "Resource running low" {memory: 85} Log.error "Connection failed" {host: "db.example.com"} ``` -------------------------------- ### Run Kit Examples Source: https://kit-lang.org/docs/2026.5.3/packages/kit-yahoo-finance.html Execute Kit examples using the interpreter. Ensure the example file path is correct. ```shell kit run examples/basic-quote.kit ``` -------------------------------- ### Build and Run a Kit Example Source: https://kit-lang.org/docs/2026.5.3/packages/kit-metal.html Compile a Kit Metal example into a binary and then execute it. This is useful for testing individual examples. ```bash kit build examples/device-info.kit ./device-info ``` -------------------------------- ### Compile and Run Kit Examples Source: https://kit-lang.org/docs/2026.5.3/packages/kit-curl.html Compiles a Kit example file and then executes the resulting binary. ```bash kit build examples/basic.kit -o basic && ./basic ``` -------------------------------- ### Run Example Counter Locally Source: https://kit-lang.org/docs/2026.5.3/packages/kit-tea-web.html Navigate to the example directory and run a simple HTTP server to view the counter example locally. ```bash cd examples/counter python3 -m http.server 8000 # Open http://localhost:8000 ``` -------------------------------- ### Build Basic Usage Example Source: https://kit-lang.org/docs/2026.5.3/packages/kit-toon.html Compile the basic usage example into a native binary. ```bash kit build examples/basic-usage.kit && ./basic-usage ``` -------------------------------- ### Build and Run GitHub Example Source: https://kit-lang.org/docs/2026.5.3/packages/kit-oauth.html Compile the GitHub OAuth example to a native binary and then execute it. ```bash kit build examples/github.kit && ./github ``` -------------------------------- ### Client Initialization and Request Example Source: https://kit-lang.org/docs/2026.5.3/packages/kit-gcp-core.html Demonstrates how to initialize a GCP client from environment variables or metadata server and make a basic authenticated GET request. ```APIDOC ## Usage Example This example shows how to authenticate with GCP using `client-from-env` and then make an authenticated GET request to the Google Cloud Storage API. ### Initialize Client ```kit import Kit.GcpCore as GCP main = fn => match GCP.client-from-env | Err e -> println "Authentication failed: ${e}" | Ok client -> println "Project ID: ${client.project-id}" // ... proceed with requests ``` `client-from-env` attempts to authenticate using the GCP metadata server first, then falls back to environment variables. For service accounts, set `GOOGLE_APPLICATION_CREDENTIALS` to the path of your service account JSON file. ### Make Authenticated Request ```kit url = "https://storage.googleapis.com/storage/v1/b?project=${client.project-id}" match GCP.get client url | Ok response -> if response.status == 200 then println response.body else println "HTTP ${Int.to-string response.status}: ${response.body}" | Err e -> println "Request failed: ${e}" ``` This part of the example makes a GET request to list buckets in the authenticated project. It checks the response status and prints either the body or an error message. ``` -------------------------------- ### Discover OpenCL Platforms and Display Info Source: https://kit-lang.org/docs/2026.5.3/packages/kit-opencl.html This example demonstrates how to get a list of available OpenCL platforms and print their basic information such as name, vendor, and version. It handles potential errors during platform enumeration. ```kit import Opencl as CL main = fn => match CL.get-platforms 0 | Err e -> println "Failed to enumerate OpenCL platforms: ${show e}" | Ok platforms -> println "Found ${length platforms} OpenCL platform(s)" show-platforms platforms 1 show-platforms = fn(platforms, idx) => match platforms | [] -> no-op | [platform | rest] -> match CL.platform-info platform | Ok info -> println "Platform ${idx}: ${info.name}" println " Vendor: ${info.vendor}" println " Version: ${info.version}" | Err e -> println "Platform ${idx}: ${show e}" show-platforms rest (idx + 1) main ``` -------------------------------- ### Compile and Run Crypto Example Source: https://kit-lang.org/docs/2026.5.3/packages/kit-crypto.html Build the crypto example into a native binary and then execute it. ```bash kit build examples/crypto.kit --allow=ffi && ./crypto ``` -------------------------------- ### Run Kit Examples Source: https://kit-lang.org/docs/2026.5.3/packages/kit-finnhub.html Execute Kit examples using the interpreter. Ensure network access is allowed for examples that require it. ```bash kit run --allow=net examples/basic-quote.kit ``` -------------------------------- ### Run Basic Example Source: https://kit-lang.org/docs/2026.5.3/packages/kit-cassandra.html Execute the basic parity-safe example using the Kit interpreter. ```bash kit run examples/basic.kit ``` -------------------------------- ### Basic Kit VIPS Usage Example Source: https://kit-lang.org/docs/2026.5.3/packages/kit-vips.html Demonstrates initializing libvips, loading an image, getting its dimensions, resizing it, and saving the result. Remember to free image handles with `vips.free` after use. ```kit import Kit.VIPS as vips main = fn => match vips.init | Err e -> println ("Failed to init libvips: " ++ e) | Ok _ -> println ("libvips version: " ++ vips.version) match vips.load "photo.png" | Err e -> println ("Load error: " ++ e) | Ok img -> println ("Size: " ++ (show (vips.get-width img)) ++ "x" ++ (show (vips.get-height img))) println ("Bands: " ++ (show (vips.get-bands img))) # Resize to 50% match vips.resize img 0.5 | Err e -> println ("Resize error: " ++ e) | Ok resized -> match vips.save resized "photo-half.png" | Ok _ -> println "Saved resized image" | Err e -> println ("Save error: " ++ e) vips.free resized # Generate a thumbnail from the original file match vips.thumbnail "photo.png" 100 | Err e -> println ("Thumbnail error: " ++ e) | Ok thumb -> match vips.save thumb "photo-thumb.png" | Ok _ -> println "Saved thumbnail" | Err e -> println ("Save error: " ++ e) vips.free thumb vips.free img vips.shutdown main ``` -------------------------------- ### Basic Redis Usage Example Source: https://kit-lang.org/docs/2026.5.3/packages/kit-redis.html Demonstrates connecting to Redis, performing PING, SET, GET, and INCR operations, and handling potential errors. Ensure a Redis server is running and accessible. ```kit import Kit.Redis as Redis main = fn => match Redis.connect "127.0.0.1" 6379 | Err err -> println "Failed to connect: ${err}" | Ok conn -> defer Redis.close conn match Redis.ping conn | Ok pong -> println "PING: ${pong}" | Err err -> println "PING failed: ${err}" match Redis.set conn "greeting" "Hello from kit-redis!" | Ok _ -> println "SET greeting succeeded" | Err err -> println "SET failed: ${err}" match Redis.get conn "greeting" | Ok (Some value) -> println "GET greeting: ${value}" | Ok None -> println "GET greeting: (nil)" | Err err -> println "GET failed: ${err}" Redis.del conn "counter" |> Result.unwrap match Redis.incr conn "counter" | Ok n -> println "INCR counter: ${n}" | Err err -> println "INCR failed: ${err}" Redis.del conn "greeting" |> Result.unwrap Redis.del conn "counter" |> Result.unwrap main ``` -------------------------------- ### Compile Example to Native Binary Source: https://kit-lang.org/docs/2026.5.3/packages/kit-aws-core.html Compiles the basic example to a native binary and then executes it. ```bash kit build examples/basic.kit && ./basic ``` -------------------------------- ### Compile and Run WebSocket Example Source: https://kit-lang.org/docs/2026.5.3/packages/kit-websocket.html Compile the example to a native binary and then run the executable. ```bash kit build examples/websocket.kit -o websocket-example ./websocket-example ``` -------------------------------- ### Install Kit with Install Script Source: https://kit-lang.org/docs/2026.5.3/guide/installation.html Use this command to quickly install Kit on macOS or Linux. It installs to `~/.kit/` and adds it to your PATH. ```bash curl -fsSL https://kit-lang.org/install.sh | bash ``` -------------------------------- ### Recommended Local Verification Flow Source: https://kit-lang.org/docs/2026.5.3/packages/kit-mgclient.html A comprehensive local verification flow that includes starting Memgraph, installing the package, running tests, and executing examples. ```kit kit task memgraph-up kit install kit test tests/ kit task test-live kit run examples/basic.kit --allow=ffi,file kit build examples/basic.kit -o /tmp/kit-mgclient-basic --allow=ffi,file --no-spinner /tmp/kit-mgclient-basic ``` -------------------------------- ### Compile Basic Example to Native Binary Source: https://kit-lang.org/docs/2026.5.3/packages/kit-dapr.html Compiles the basic example into a native binary and then executes it. ```bash kit build examples/basic.kit -o basic --allow=net && ./basic ``` -------------------------------- ### Create an Interval Source: https://kit-lang.org/docs/2026.5.3/stdlib/interval.html Create a new interval using start and end timestamps in milliseconds. This example also shows how to get the number of days within the interval. ```kit start = Time.parse "2024-01-01" "%Y-%m-%d" end = Time.parse "2024-01-31" "%Y-%m-%d" january = Interval.new start end println (Interval.days january) # => 30 ``` -------------------------------- ### Basic Kit MQTT Usage Example Source: https://kit-lang.org/docs/2026.5.3/packages/kit-mqtt.html Demonstrates initializing the MQTT library, connecting to a broker, subscribing to a topic, publishing a message, and handling received messages. Requires the `ffi` capability. ```kit import Kit.MQTT as Mqtt main = fn => # Initialize the Mosquitto library before creating clients match Mqtt.lib-init | Err e -> println ("Init error: " ++ e) | Ok _ -> println "MQTT library initialized" # Show the linked Mosquitto version and QoS constants println ("Mosquitto version: " ++ Mqtt.version) println ("QoS 0: " ++ (show Mqtt.qos-0)) println ("QoS 1: " ++ (show Mqtt.qos-1)) println ("QoS 2: " ++ (show Mqtt.qos-2)) match Mqtt.new "kit-client" | Err e -> println ("Client error: " ++ e) | Ok client -> match Mqtt.connect client "localhost" 1883 60 | Err e -> println ("Connect error: " ++ e) | Ok _ -> match Mqtt.subscribe client "kit/test" (Mqtt.qos-1) | Ok _ -> println "Subscribed to kit/test" | Err e -> println ("Subscribe error: " ++ e) match Mqtt.publish client "kit/test" "Hello from Kit!" (Mqtt.qos-1) false | Ok _ -> println "Published message" | Err e -> println ("Publish error: " ++ e) match Mqtt.loop client 1000 | Err e -> println ("Loop error: " ++ e) | Ok _ -> if Mqtt.has-message? then println ("Topic: " ++ Mqtt.get-last-topic) println ("Payload: " ++ Mqtt.get-last-payload) Mqtt.clear-message else println "No message received" match Mqtt.disconnect client | Ok _ -> println "Disconnected" | Err e -> println ("Disconnect error: " ++ e) Mqtt.destroy client Mqtt.lib-cleanup main ``` -------------------------------- ### Build PostgreSQL Example Binary Source: https://kit-lang.org/docs/2026.5.3/packages/kit-query.html Compile the PostgreSQL example to a native binary and then execute it. ```bash kit build examples/postgres-basic.kit -o postgres-basic && ./postgres-basic ``` -------------------------------- ### Run Upload/Download Example Source: https://kit-lang.org/docs/2026.5.3/packages/kit-azure-storage.html Execute the upload and download example, ensuring the AZURE_CONTAINER environment variable is set. ```bash export AZURE_CONTAINER=mycontainer kit run examples/upload-download.kit ``` -------------------------------- ### Making Authenticated GET Requests Source: https://kit-lang.org/docs/2026.5.3/packages/kit-oauth.html Provides an example of how to make an authenticated GET request to an API using an access token. ```APIDOC ## Authenticated GET Request ### Description This snippet shows how to make a GET request to a protected API endpoint using an obtained access token. It handles the response, including status and body. ### Usage ```kit match OAuth.get "https://api.example.com/user" tokens.access-token | Ok response -> println "Status: ${Int.to-string response.status}" println response.body | Error err -> println "API error: ${err}" ``` ``` -------------------------------- ### Run Examples with Interpreter Source: https://kit-lang.org/docs/2026.5.3/packages/kit-vulkan.html Execute Kit examples using the interpreter, allowing FFI access. ```bash kit run examples/basic-usage.kit --allow=ffi ``` -------------------------------- ### Compile and Run Kit Examples Source: https://kit-lang.org/docs/2026.5.3/packages/kit-finance.html Compile Kit examples to a native binary and then execute it. This allows for performance testing and running examples outside the interpreter. ```kit kit build examples/capabilities.kit && ./capabilities ``` -------------------------------- ### Basic SDL Initialization and Window Creation Source: https://kit-lang.org/docs/2026.5.3/packages/kit-sdl.html Demonstrates the basic initialization of SDL, window creation, renderer setup, drawing a rectangle, and presenting it. Ensure to pair resource creation with `defer` for cleanup. ```kit import Kit.Sdl as SDL main = fn => match SDL.init | Err err -> print "SDL init failed: ${err}" | Ok _ -> defer SDL.quit match SDL.create-window "Kit SDL Demo" 800 600 | Err err -> print "Window error: ${err}" | Ok window -> defer SDL.destroy-window window match SDL.create-renderer window | Err err -> print "Renderer error: ${err}" | Ok renderer -> defer SDL.destroy-renderer renderer SDL.set-draw-color renderer 30 30 40 255 SDL.clear renderer SDL.set-draw-color renderer 100 200 100 255 SDL.fill-rect renderer 100 100 240 160 SDL.present renderer SDL.delay 1000 main ``` -------------------------------- ### Install libxml2 Dependency Source: https://kit-lang.org/docs/2026.5.3/packages/kit-xml.html Install the native libxml2 development library required by the Kit XML package. This is a prerequisite for building or running examples. ```shell # macOS brew install libxml2 # Ubuntu/Debian sudo apt install libxml2-dev # Fedora sudo dnf install libxml2-devel ``` -------------------------------- ### Run Kit Examples Source: https://kit-lang.org/docs/2026.5.3/packages/kit-metal.html Execute various Kit Metal examples using the `kit run` command. Ensure examples are located in the specified directory. ```bash kit run examples/device-info.kit kit run examples/shader-compile.kit kit run examples/compute.kit kit run examples/vector-add.kit ``` -------------------------------- ### Usage Example Source: https://kit-lang.org/docs/2026.5.3/packages/kit-sndfile.html A comprehensive example demonstrating how to use the Kit.SndFile module to get library version, read audio file metadata, and create a new WAV file. ```APIDOC ## Usage ```kit import Kit.SndFile as Sndfile main = fn => println ("libsndfile version: " ++ Sndfile.version) # Read audio file metadata match Sndfile.open-read "audio.wav" | Err e -> println ("Open error: " ++ e) | Ok handle -> println ("Format: " ++ (Sndfile.format-name handle)) println ("Sample rate: " ++ (show (Sndfile.get-samplerate handle)) ++ " Hz") println ("Channels: " ++ (show (Sndfile.get-channels handle))) println ("Frames: " ++ (show (Sndfile.get-frames handle))) println ("Duration: " ++ (show (Sndfile.get-duration handle)) ++ " seconds") match Sndfile.close handle | Ok _ -> println "File closed" | Err e -> println ("Close error: " ++ e) # Create a WAV file handle wav-format = Sndfile.format-wav + Sndfile.format-pcm16 match Sndfile.open-write "output.wav" wav-format 1 44100 | Err e -> println ("Create error: " ++ e) | Ok handle -> println "Created WAV (1 channel, 44100 Hz, PCM 16-bit)" match Sndfile.close handle | Ok _ -> println "File closed" | Err e -> println ("Close error: " ++ e) main ``` When writing files, combine one container format with one encoding format. The public constants currently cover `format-wav`, `format-flac`, `format-ogg`, `format-aiff`, `format-pcm16`, `format-pcm24`, `format-float`, and `format-vorbis`. ``` -------------------------------- ### Run Basic Usage Example Source: https://kit-lang.org/docs/2026.5.3/packages/kit-toon.html Execute the basic usage example using the Kit interpreter. ```bash kit run examples/basic-usage.kit ``` -------------------------------- ### Run ZGPUI Examples Source: https://kit-lang.org/docs/2026.5.3/packages/kit-zgpui.html Execute example Kit files using the kit run command. This is useful for testing specific examples or features. ```bash kit run examples/hello.kit ``` ```bash kit run examples/counter.kit ``` ```bash kit run examples/flexbox.kit ``` -------------------------------- ### Complete Supervisor Example Source: https://kit-lang.org/docs/2026.5.3/stdlib/supervisor.html A comprehensive example demonstrating the creation of child specifications, starting a supervisor with the ':isolate' strategy, sending messages to children, and checking supervisor status before cleanup. ```kit # Define a worker handler worker-handler = fn(msg, state) => match msg | :work -> state + 1 | :reset -> 0 | _ -> state # Create child specifications children = [ {handler: worker-handler, state: 0, name: "worker-1"}, {handler: worker-handler, state: 0, name: "worker-2"}, {handler: worker-handler, state: 0, name: "worker-3"} ] # Start supervisor with isolate strategy sup = Supervisor.start :isolate children # Get child actors and send them work workers = Supervisor.children sup workers |> List.each (fn(w) => w <- :work) # Check status println "Supervisor running: ${Supervisor.is-running? sup}" println "Child count: ${Supervisor.child-count sup}" # Cleanup Supervisor.stop sup ``` -------------------------------- ### Run Basic Example with Capabilities Source: https://kit-lang.org/docs/2026.5.3/packages/kit-azure-core.html Execute the basic Azure example using the kit interpreter, allowing FFI and process capabilities. This is useful for testing and development. ```bash kit run examples/basic.kit --allow=ffi,process ``` -------------------------------- ### Basic SDL Initialization and Window Creation Source: https://kit-lang.org/docs/2026.5.3/packages/kit-sdl.html Demonstrates the fundamental steps of initializing SDL, creating a window, setting up a renderer, drawing a rectangle, and presenting it. It also shows proper resource cleanup using `defer`. ```APIDOC ## Usage Example This example demonstrates basic SDL initialization, window creation, renderer setup, drawing a rectangle, and resource cleanup. ```kit import Kit.Sdl as SDL main = fn => match SDL.init | Err err -> print "SDL init failed: ${err}" | Ok _ -> defer SDL.quit match SDL.create-window "Kit SDL Demo" 800 600 | Err err -> print "Window error: ${err}" | Ok window -> defer SDL.destroy-window window match SDL.create-renderer window | Err err -> print "Renderer error: ${err}" | Ok renderer -> defer SDL.destroy-renderer renderer SDL.set-draw-color renderer 30 30 40 255 SDL.clear renderer SDL.set-draw-color renderer 100 200 100 255 SDL.fill-rect renderer 100 100 240 160 SDL.present renderer SDL.delay 1000 main ``` ``` -------------------------------- ### Extract Substring with String.substring Source: https://kit-lang.org/docs/2026.5.3/stdlib/string.html Get a portion of a string between a start and end index (exclusive). Indices are 0-based. ```kit println (String.substring "Hello, World!" 0 5) # => "Hello" ``` -------------------------------- ### Build SQLite Example Binary Source: https://kit-lang.org/docs/2026.5.3/packages/kit-query.html Compile the SQLite example to a native binary and then execute it. ```bash kit build examples/sqlite-basic.kit -o sqlite-basic && ./sqlite-basic ``` -------------------------------- ### Show ValidationError Example Source: https://kit-lang.org/docs/2026.5.3/stdlib/validation-error.html Demonstrates how to use the 'show' trait to get human-readable descriptions of ValidationError instances. ```kit err = InvalidValue{field: "age", value: "-5", reason: "must be positive"} println (show err) # => InvalidValue: age='-5' (must be positive) err = MissingField{field: "email"} println (show err) # => MissingField: email ``` -------------------------------- ### Write Your First Kit Program Source: https://kit-lang.org/docs/2026.5.3/guide/hello-world.html Create a simple Kit file to print 'Hello, World!'. Kit programs execute top-to-bottom without requiring a main function or boilerplate. ```kit println "Hello, World!" ``` -------------------------------- ### Get Start of Month - Calendar Source: https://kit-lang.org/docs/2026.5.3/stdlib/calendar.html Returns the timestamp for the first day of the month (00:00:00) for a given timestamp. ```kit ts = Time.parse "2024-12-19" "%Y-%m-%d" start = Calendar.start-of-month ts println (Time.format start "%Y-%m-%d") # => "2024-12-01" ``` -------------------------------- ### Get Start of Day - Calendar Source: https://kit-lang.org/docs/2026.5.3/stdlib/calendar.html Returns the timestamp representing the beginning of the day (00:00:00.000) for a given timestamp. ```kit now = Time.now start = Calendar.start-of-day now println (Time.format start "%Y-%m-%d %H:%M:%S") # => "2024-12-19 00:00:00" ``` -------------------------------- ### Get Start of Year - Calendar Source: https://kit-lang.org/docs/2026.5.3/stdlib/calendar.html Returns the timestamp for the beginning of the year (January 1st 00:00:00) for a given timestamp. ```kit ts = Time.parse "2024-06-15" "%Y-%m-%d" start = Calendar.start-of-year ts println (Time.format start "%Y-%m-%d") # => "2024-01-01" ``` -------------------------------- ### Run Kit Examples Source: https://kit-lang.org/docs/2026.5.3/packages/kit-otel.html Execute Kit examples using the kit run command or compile them to a native binary. ```bash kit run examples/basic-metrics.kit ``` ```bash kit build examples/basic-metrics.kit && ./basic-metrics ``` -------------------------------- ### Get Start of Week - Calendar Source: https://kit-lang.org/docs/2026.5.3/stdlib/calendar.html Returns the timestamp for the beginning of the week (Monday 00:00:00) relative to a given timestamp. ```kit ts = Time.parse "2024-12-19" "%Y-%m-%d" # Thursday start = Calendar.start-of-week ts println (Time.format start "%Y-%m-%d") # => "2024-12-16" (Monday) ``` -------------------------------- ### Run Kit Examples Source: https://kit-lang.org/docs/2026.5.3/packages/kit-mcp.html Execute Kit example files using the Kit interpreter. The `--allow=net` flag is required for examples that utilize network functionalities. ```bash kit run examples/hello-server.kit ``` ```bash kit run --allow=net examples/hello-sse-server.kit ``` -------------------------------- ### Get TA-Lib Version Source: https://kit-lang.org/docs/2026.5.3/packages/kit-ta-lib.html Retrieves the installed TA-Lib version string. This is useful for checking compatibility or reporting issues. ```Groovy version = TALib.version() println "TA-Lib version: ${version}" ``` -------------------------------- ### Basic Usage Example Source: https://kit-lang.org/docs/2026.5.3/packages/kit-redis.html Demonstrates basic Redis operations: connecting, pinging, setting, getting, and incrementing a counter. ```APIDOC ## Usage ``` import Kit.Redis as Redis main = fn => match Redis.connect "127.0.0.1" 6379 | Err err -> println "Failed to connect: ${err}" | Ok conn -> defer Redis.close conn match Redis.ping conn | Ok pong -> println "PING: ${pong}" | Err err -> println "PING failed: ${err}" match Redis.set conn "greeting" "Hello from kit-redis!" | Ok _ -> println "SET greeting succeeded" | Err err -> println "SET failed: ${err}" match Redis.get conn "greeting" | Ok (Some value) -> println "GET greeting: ${value}" | Ok None -> println "GET greeting: (nil)" | Err err -> println "GET failed: ${err}" Redis.del conn "counter" |> Result.unwrap match Redis.incr conn "counter" | Ok n -> println "INCR counter: ${n}" | Err err -> println "INCR failed: ${err}" Redis.del conn "greeting" |> Result.unwrap Redis.del conn "counter" |> Result.unwrap main ``` ``` -------------------------------- ### Compile Kit Examples to Native Binary Source: https://kit-lang.org/docs/2026.5.3/packages/kit-pg-parser.html Build the demo.kit script into an executable binary. ```bash kit build examples/demo.kit && ./demo ``` -------------------------------- ### Find All Substring Indices with String.indices-of Source: https://kit-lang.org/docs/2026.5.3/stdlib/string.html Get a list of all starting indices where a substring occurs within a string. Matches are non-overlapping. ```kit println (String.indices-of "abcabcabc" "abc") # => [0, 3, 6] ``` ```kit println (String.indices-of "hello" "xyz") # => [] ``` -------------------------------- ### Compile Examples to Native Binary Source: https://kit-lang.org/docs/2026.5.3/packages/kit-libuv.html Commands to compile a Kit example file into a native executable and then run it. ```bash kit build examples/timer-example.kit && ./timer-example ``` -------------------------------- ### Compile and Run Examples Source: https://kit-lang.org/docs/2026.5.3/packages/kit-fix.html Compile Kit examples into native binaries and then execute them. This helps in testing the compiled output. ```bash kit build examples/simple-client.kit && ./simple-client ``` -------------------------------- ### Market Sector Data Source: https://kit-lang.org/docs/2026.5.3/packages/kit-yahoo-finance.html Retrieves sector performance data. This example shows how to get the performance of the 'technology' sector for the last day. ```APIDOC ## Market.get-sector ### Description Retrieves sector performance data. ### Method `Market.get-sector` ### Parameters - **sectorName** (String) - Required - The name of the sector to retrieve data for. ### Request Example ``` import Kit.YahooFinance as YahooFinance match YahooFinance.Market.get-sector "technology" | Ok sector -> println "Tech sector: ${Float.to-string sector.performance-1d}%" | Err e -> println "Error: ${show e}" ``` ### Response #### Success Response - **performance-1d** (Float) - The 1-day performance percentage of the sector. ``` -------------------------------- ### Start Server with Configuration Source: https://kit-lang.org/docs/2026.5.3/packages/kit-crooner.html Starts an HTTP server with a specific router and configuration. The on-start callback is executed after the server is successfully created. ```kit config = {host: "127.0.0.1", port: 8080} start router config fn => println "Server started!" ``` -------------------------------- ### Build Kit Examples Source: https://kit-lang.org/docs/2026.5.3/packages/kit-plot.html Compile a Kit example to verify native code generation. The output path and file permissions are specified. ```bash kit build examples/vega-lite/bar-chart.kit -o /tmp/kit-plot-bar-chart --allow=file,file-write ``` -------------------------------- ### Period Boundaries Source: https://kit-lang.org/docs/2026.5.3/stdlib/calendar.html Functions to get the timestamp for the start or end of a day, week, month, quarter, or year relative to a given timestamp. ```APIDOC ## Calendar.start-of-day ### Description Returns the timestamp for the start of the day (00:00:00.000). ### Signature `Int -> Int` ### Example ``` now = Time.now start = Calendar.start-of-day now println (Time.format start "%Y-%m-%d %H:%M:%S") # => "2024-12-19 00:00:00" ``` ## Calendar.end-of-day ### Description Returns the timestamp for the end of the day (23:59:59.999). ### Signature `Int -> Int` ## Calendar.start-of-week ### Description Returns the timestamp for the start of the week (Monday 00:00:00). ### Signature `Int -> Int` ### Example ``` ts = Time.parse "2024-12-19" "%Y-%m-%d" # Thursday start = Calendar.start-of-week ts println (Time.format start "%Y-%m-%d") # => "2024-12-16" (Monday) ``` ## Calendar.end-of-week ### Description Returns the timestamp for the end of the week (Sunday 23:59:59.999). ### Signature `Int -> Int` ## Calendar.start-of-month ### Description Returns the timestamp for the start of the month. ### Signature `Int -> Int` ### Example ``` ts = Time.parse "2024-12-19" "%Y-%m-%d" start = Calendar.start-of-month ts println (Time.format start "%Y-%m-%d") # => "2024-12-01" ``` ## Calendar.end-of-month ### Description Returns the timestamp for the end of the month. ### Signature `Int -> Int` ### Example ``` ts = Time.parse "2024-02-15" "%Y-%m-%d" end = Calendar.end-of-month ts println (Time.format end "%Y-%m-%d") # => "2024-02-29" (leap year) ``` ## Calendar.start-of-quarter ### Description Returns the timestamp for the start of the quarter. ### Signature `Int -> Int` ### Example ``` ts = Time.parse "2024-05-15" "%Y-%m-%d" # Q2 start = Calendar.start-of-quarter ts println (Time.format start "%Y-%m-%d") # => "2024-04-01" ``` ## Calendar.end-of-quarter ### Description Returns the timestamp for the end of the quarter. ### Signature `Int -> Int` ## Calendar.start-of-year ### Description Returns the timestamp for the start of the year (January 1st 00:00:00). ### Signature `Int -> Int` ### Example ``` ts = Time.parse "2024-06-15" "%Y-%m-%d" start = Calendar.start-of-year ts println (Time.format start "%Y-%m-%d") # => "2024-01-01" ``` ## Calendar.end-of-year ### Description Returns the timestamp for the end of the year (December 31st 23:59:59.999). ### Signature `Int -> Int` ``` -------------------------------- ### Run Examples with Interpreter Source: https://kit-lang.org/docs/2026.5.3/packages/kit-aws-core.html Commands to run the provided examples using the Kit interpreter. ```bash kit run examples/basic.kit ``` ```bash kit run examples/regions.kit ``` ```bash kit run examples/sign-request.kit ``` -------------------------------- ### Get Start of Quarter - Calendar Source: https://kit-lang.org/docs/2026.5.3/stdlib/calendar.html Returns the timestamp for the beginning of the quarter (e.g., April 1st 00:00:00 for Q2) relative to a given timestamp. ```kit ts = Time.parse "2024-05-15" "%Y-%m-%d" # Q2 start = Calendar.start-of-quarter ts println (Time.format start "%Y-%m-%d") # => "2024-04-01" ``` -------------------------------- ### Run Full Kit UI Application Source: https://kit-lang.org/docs/2026.5.3/packages/kit-ui.html Use Kit.UI for the full package entry point, including the SDL/WGPU window runner. This example demonstrates setting up a simple scene and handling user interaction. ```kit import Kit.UI as UI render-scene = fn(model) => { background-top: UI.color 0.06 0.08 0.11 1.0, background-bottom: UI.color 0.11 0.14 0.19 1.0, root: UI.button "save-button" "save" UI.default-panel-style } update-model = fn(model, clicked-id) => if clicked-id == "save" then {status: "saved"} else model main = fn => initial-model = {status: "idle"} UI.run-app-window "Kit UI Demo" 800 480 initial-model render-scene update-model main ``` -------------------------------- ### Create Default Logger Source: https://kit-lang.org/docs/2026.5.3/packages/kit-logging.html Creates a logger using the default configuration. This is a convenient way to get a functional logger without explicit setup. ```kit log = default log.debug "Debugging info" {} ``` -------------------------------- ### Get UTC Offset Source: https://kit-lang.org/docs/2026.5.3/stdlib/time.html Returns the UTC offset in minutes for a given timezone at a specific timestamp. For example, EST (UTC-5) would return -300. ```kit now = Time.now offset = Time.utc-offset "America/New_York" now println offset # => -300 (EST is UTC-5, which is -300 minutes) ``` -------------------------------- ### Compile and Run Kit UI Layout Example Source: https://kit-lang.org/docs/2026.5.3/packages/kit-ui.html Compile a smoke example using 'kit build' and then execute the compiled binary. ```bash kit build examples/layout-smoke.kit -o /tmp/kit-ui-layout-smoke && /tmp/kit-ui-layout-smoke ``` -------------------------------- ### Kit PDF Usage Example Source: https://kit-lang.org/docs/2026.5.3/packages/kit-pdf.html Demonstrates creating a PDF file with a title, author, and text, and then reading its properties. Ensure the pdfio library is installed and accessible. ```kit import Kit.PDF as Pdf main = fn => # Create a PDF match Pdf.create "/tmp/report.pdf" "Monthly Report" "Kit User" | Ok pdf -> match Pdf.add-page pdf Pdf.letter-width Pdf.letter-height | Ok page -> Pdf.add-text pdf page "Monthly Report" 72 720 24 Pdf.add-text pdf page "Generated with kit-pdf" 72 690 12 | Err e -> println ("Page error: " ++ e) Pdf.finalize pdf println "PDF created" | Err e -> println ("Error: " ++ e) # Read a PDF match Pdf.open "/tmp/report.pdf" | Ok pdf -> println ("Pages: " ++ (show (Pdf.page-count pdf))) match Pdf.get-title pdf | Some title -> println ("Title: " ++ title) | None -> println "No title" match Pdf.get-author pdf | Some author -> println ("Author: " ++ author) | None -> println "No author" Pdf.close pdf | Err e -> println ("Error: " ++ e) main ``` -------------------------------- ### Get Relative Path Source: https://kit-lang.org/docs/2026.5.3/stdlib/path.html Path.relative calculates the relative path from a starting directory to a target path. This is useful for creating links or references within a project structure. ```kit println (Path.relative "/home/user" "/home/user/docs/file.txt") # => "docs/file.txt" ``` -------------------------------- ### Run Kit Examples Source: https://kit-lang.org/docs/2026.5.3/packages/kit-mgclient.html Execute Kit examples using the interpreter. Ensure to specify allowed capabilities like ffi and file. ```kit kit run examples/basic.kit --allow=ffi,file kit run examples/auth.kit --allow=ffi,file kit run examples/transactions.kit --allow=ffi,file ``` -------------------------------- ### Run PostgreSQL Example Source: https://kit-lang.org/docs/2026.5.3/packages/kit-query.html Execute the basic PostgreSQL example using the kit run command. ```bash kit run examples/postgres-basic.kit ``` -------------------------------- ### Run WebSocket Example with Interpreter Source: https://kit-lang.org/docs/2026.5.3/packages/kit-websocket.html Execute the example WebSocket client using the Kit interpreter. ```bash kit run examples/websocket.kit ``` -------------------------------- ### Run Kit Examples Source: https://kit-lang.org/docs/2026.5.3/packages/kit-pg-parser.html Execute the demo.kit script using the Kit interpreter. ```bash kit run examples/demo.kit ``` -------------------------------- ### Basic Crooner Web Server Setup Source: https://kit-lang.org/docs/2026.5.3/packages/kit-crooner.html Set up a basic web server using Crooner, defining handlers for different routes and starting the server on a specified port. ```kit import Map import Kit.Crooner as Crooner index-handler = fn(-req) => Crooner.text-response 200 "Hello, World!" hello-handler = fn(req) => name = Map.get req.params "name" |> Option.unwrap-or "stranger" Crooner.text-response 200 "Hello, ${name}!" json-handler = fn(-req) => Crooner.json-response 200 "{\"message\":\"Hello, JSON!\"}" app = Crooner.app |> Crooner.get "/" index-handler |> Crooner.get "/hello/:name" hello-handler |> Crooner.get "/json" json-handler Crooner.listen app 4000 fn => println "Crooner running at http://localhost:4000" ``` -------------------------------- ### Implement Measurable Trait Source: https://kit-lang.org/docs/2026.5.3/packages/kit-tea.html Types implementing Measurable can report their dimensions, which is useful for layout calculations and hit testing. This example shows a basic implementation to get width and height. ```tea extend MyWidget with Measurable measure = fn(widget) => {w: widget.width, h: widget.height} ``` -------------------------------- ### Run Basic Example with Custom Memcached Port Source: https://kit-lang.org/docs/2026.5.3/packages/kit-memcached.html Execute the basic memcached example, directing it to a custom memcached server host and port. ```bash KIT_MEMCACHED_HOST=127.0.0.1 KIT_MEMCACHED_PORT=11222 kit run --allow=ffi,tcp examples/basic.kit ``` -------------------------------- ### Initialize OpenCL Resources for Kernel Execution Source: https://kit-lang.org/docs/2026.5.3/packages/kit-opencl.html This snippet shows the setup required before running OpenCL kernels. It includes creating a context, a command queue, compiling an OpenCL C program, and creating a kernel. Resources are deferred for release. ```kit # Given a selected device: ctx = CL.create-context [device] |> Result.unwrap defer CL.release-context ctx queue = CL.create-queue ctx device |> Result.unwrap defer CL.release-queue queue source = "__kernel void scale(__global float* data) { int i = get_global_id(0); data[i] = data[i] * 2.0f; }" program = CL.create-program ctx source |> Result.unwrap defer CL.release-program program CL.build-program program [device] "" |> Result.unwrap kernel = CL.create-kernel program "scale" |> Result.unwrap defer CL.release-kernel kernel ``` -------------------------------- ### Basic Factgraph Usage Example Source: https://kit-lang.org/docs/2026.5.3/packages/kit-factgraph.html Demonstrates creating a dictionary with types and facts, initializing an empty graph, setting and getting facts, and inspecting the graph's paths and data. ```kit import Kit.Factgraph as FactGraph main = fn => # Create a dictionary with metadata, type definitions, and fact definitions dict = FactGraph.empty-dictionary {name: "Person Schema", version: "1.0"} |> FactGraph.add-type "PositiveInt" (FactGraph.make-type "PositiveInt" "Int") |> FactGraph.add-fact "/person/name" (FactGraph.make-fact "String") |> FactGraph.add-fact "/person/age" (FactGraph.make-fact "PositiveInt") |> FactGraph.add-fact "/person/email" (FactGraph.make-optional-fact "String") # Create an empty fact graph from the dictionary graph = FactGraph.empty dict |> FactGraph.set "/person/name" "Alice" |> FactGraph.set "/person/age" 30 # Read facts by path name = FactGraph.get graph "/person/name" age = FactGraph.get graph "/person/age" println "Name: ${name}" println "Age: ${age}" # Inspect paths and serialize the graph data println "All paths: ${FactGraph.paths graph}" println "Data: ${FactGraph.to-map graph}" main ``` -------------------------------- ### REPL Preloaders for Sample Databases Source: https://kit-lang.org/docs/2026.5.3/packages/kit-sqlite.html Launch the Kit REPL with pre-loaded sample databases for interactive exploration. Each preloader sets up an in-memory database with helper functions. ```bash kit repl --preload dev/repl.kit # Generic in-memory database (users, posts) ``` ```bash kit repl --preload dev/chinook.kit # Chinook music store (artists, albums, tracks) ``` ```bash kit repl --preload dev/northwind.kit # Northwind traders (products, orders, customers) ``` -------------------------------- ### Basic Azure Storage Usage Example Source: https://kit-lang.org/docs/2026.5.3/packages/kit-azure-storage.html This example demonstrates how to create an Azure Storage client from environment variables, list containers, and perform upload, download, and delete operations on a blob. ```kit import Kit.Azure-Storage as Storage main = fn => match Storage.client-from-env | Err err -> println "Unable to create Azure Storage client: ${err}" | Ok storage -> # List containers in the storage account. match Storage.list-containers storage | Err err -> println "List containers failed: ${err}" | Ok result -> println "Containers: ${Int.to-string (List.length result.containers)}" # Upload, read, and delete a blob. container = "my-container" blob-name = "kit/hello.txt" content = "Hello from Kit" match Storage.put-blob-with-type storage container blob-name content "text/plain" | Err err -> println "Upload failed: ${err}" | Ok _ -> match Storage.get-blob storage container blob-name | Ok downloaded -> println downloaded | Err err -> println "Download failed: ${err}" match Storage.delete-blob storage container blob-name | Ok _ -> println "Deleted ${blob-name}" | Err err -> println "Delete failed: ${err}" main ``` -------------------------------- ### Basic Audio Playback Example Source: https://kit-lang.org/docs/2026.5.3/packages/kit-audio.html Demonstrates basic audio playback. Initializes the audio engine, loads a sound file, plays it, and then shuts down the engine. Requires 'sound.wav' to be present. ```kit import Kit.Audio as Audio main = fn(env: Env) => match Audio.init | Ok engine -> match Audio.load engine "sound.wav" | Ok sound -> defer Audio.free sound Audio.play sound Process.sleep 2000 # Wait for playback | Err err -> println "Failed to load: ${err}" Audio.shutdown engine | Err err -> println "Failed to initialize: ${err}" main ``` -------------------------------- ### Basic Policy and Scope Example Source: https://kit-lang.org/docs/2026.5.3/packages/kit-policy.html Demonstrates defining a post policy, a post scope, and using them with authorization checks and data filtering. Includes setup for user context and post data. ```kit import Kit.Policy.Core as PolicyCore import Kit.Policy.Error as PolicyError import Kit.Policy.Scope as PolicyScope type Post = {id: Int, author-id: Int, published?: Bool, title: String} type User = {id: Int, admin?: Bool} type AuthContext = {user: User} post-policy = fn(post, ctx, action) => if ctx.user.admin? then PolicyCore.allow else match PolicyCore.resolve-alias action | :show -> PolicyCore.allow-if post.published? | :update -> PolicyCore.allow-if (ctx.user.id == post.author-id) | :destroy -> PolicyCore.allow-if (ctx.user.id == post.author-id) | _ -> PolicyCore.no-rule action post-scope = fn(posts, ctx) => if ctx.user.admin? then posts else posts |> List.filter (fn(post) => post.published?) main = fn => user = {id: 1, admin?: false} ctx = {user: user} post = {id: 1, author-id: 1, published?: true, title: "Hello"} posts = [post] if PolicyCore.can-with? post-policy post ctx :update then println "Can update post" else println "Cannot update post" visible-posts = PolicyScope.scope-with post-scope posts ctx page = PolicyScope.paginate 1 10 visible-posts info = PolicyScope.pagination-info 1 10 visible-posts println "Visible posts: ${page}" println "Pages: ${info.pages}" err = PolicyError.not-authorized "Post" :update "not the author" println (PolicyError.message err) main ``` -------------------------------- ### start Source: https://kit-lang.org/docs/2026.5.3/packages/kit-crooner.html Starts the server with the given configuration, creating an HTTP server and accepting client connections. It calls the on-start callback after the server is created successfully. ```APIDOC ## start ### Description Start the server with the given configuration. Creates an HTTP server and starts accepting client connections. Calls the on-start callback after the server is created successfully. ### Parameters * `router` - Router record with routes and handlers * `config` - Configuration record with host and port fields * `on-start` - Callback function to run after server starts ### Returns Never returns (enters accept loop) `Router -> Config -> (() -> ()) -> Unit` ### Example ``` config = {host: "127.0.0.1", port: 8080} start router config fn => println "Server started!" ``` ``` -------------------------------- ### Basic LMDB Usage Example Source: https://kit-lang.org/docs/2026.5.3/packages/kit-lmdb.html Demonstrates basic operations like opening a database, storing, reading, checking for keys, counting entries, and deleting values. Ensure LMDB is installed on your system. ```kit import Kit.LMDB as Lmdb main = fn => println ("LMDB version: " ++ Lmdb.version) match Lmdb.open "/tmp/my-database" | Err e -> println ("Error: " ++ e) | Ok db -> defer Lmdb.close db # Store values match Lmdb.put db "name" "Kit" | Err e -> println ("put failed: " ++ e) | Ok _ -> no-op Lmdb.put db "version" "0.1.0" Lmdb.put db "language" "functional" # Read values match Lmdb.get db "name" | Some val -> println ("name: " ++ val) | None -> println "name: not found" match Lmdb.get db "missing" | Some val -> println ("missing: " ++ val) | None -> println "missing: not found" # Check key existence if Lmdb.has-key? db "name" then println "'name' exists" # Count and list entries println ("Entries: " ++ (show (Lmdb.count db))) keys = Lmdb.list-keys db println ("Keys: " ++ (show keys)) # Update and delete values Lmdb.put db "version" "0.2.0" Lmdb.delete db "language" main ```