### Install Numbat on Void Linux Source: https://github.com/sharkdp/numbat/blob/main/book/src/cli/installation.md Installs the Numbat package on Void Linux using the xbps-install command. ```bash sudo xbps-install -S numbat ``` -------------------------------- ### Install Dependencies and Start Local Preview Server (Bash) Source: https://github.com/sharkdp/numbat/blob/main/book/README.md Installs project dependencies using uv and starts a local development server with live reload. This command is essential for previewing documentation changes in real-time during development. ```bash uv run zensical serve ``` -------------------------------- ### Install Numbat using Nix Source: https://github.com/sharkdp/numbat/blob/main/book/src/cli/installation.md Installs Numbat on NixOS or any distribution with Nix installed, either to the user profile or by adding it to the NixOS configuration. ```bash nix-env -iA nixpkgs.numbat ``` -------------------------------- ### Install Numbat on Windows using Scoop Source: https://github.com/sharkdp/numbat/blob/main/book/src/cli/installation.md Installs the Numbat package on Windows using the Scoop package manager. ```bash scoop install main/numbat ``` -------------------------------- ### Install latest Numbat release using Cargo Source: https://github.com/sharkdp/numbat/blob/main/book/src/cli/installation.md Installs the latest release of the numbat-cli binary directly from crates.io using Cargo. ```bash cargo install numbat-cli ``` -------------------------------- ### Install Numbat from source using Cargo Source: https://github.com/sharkdp/numbat/blob/main/book/src/cli/installation.md Clones the Numbat Git repository and builds the numbat-cli binary using Cargo. This method allows for building from the latest source code. ```bash git clone https://github.com/sharkdp/numbat cd numbat/ cargo install -f --path numbat-cli ``` -------------------------------- ### Install Numbat on Ubuntu using PPA Source: https://github.com/sharkdp/numbat/blob/main/book/src/cli/installation.md Adds the Numbat PPA to the system and installs Numbat using apt, enabling automatic updates. This method is for amd64/x86_64 architectures on Ubuntu. ```bash sudo add-apt-repository ppa:apandada1/numbat sudo apt update sudo apt install numbat ``` -------------------------------- ### Numbat CLI Usage Examples Source: https://context7.com/sharkdp/numbat/llms.txt Demonstrates different ways to use the Numbat command-line interface (CLI), including starting the interactive REPL, running script files, and evaluating single expressions. ```bash # Start interactive REPL session numbat # Run a Numbat script file numbat script.nbt # Evaluate a single expression numbat -e '30 km/h -> mi/h' # In REPL, use special commands help # Show introduction info # Get info about functions, units, dimensions list # Show all defined items list functions # Show all functions list units # Show all units save history.nbt # Save session to file ``` -------------------------------- ### Install Numbat on macOS using Homebrew Source: https://github.com/sharkdp/numbat/blob/main/book/src/cli/installation.md Installs Numbat on macOS using the Homebrew package manager. ```bash brew install numbat ``` -------------------------------- ### Install Numbat on Arch Linux from AUR Source: https://github.com/sharkdp/numbat/blob/main/book/src/cli/installation.md Installs Numbat on Arch Linux and derivatives using the AUR helper 'yay'. It provides options to install a prebuilt package or compile from source. ```bash yay -S numbat-bin yay -S numbat ``` -------------------------------- ### Install Numbat on Ubuntu using dpkg Source: https://github.com/sharkdp/numbat/blob/main/book/src/cli/installation.md Downloads the latest .deb package from the Numbat releases page and installs it using dpkg. This method is suitable for Ubuntu and other Debian-based distributions. ```bash curl -LO https://github.com/sharkdp/numbat/releases/download/v1.23.0/numbat_1.23.0_amd64.deb sudo dpkg -i numbat_1.23.0_amd64.deb ``` -------------------------------- ### Install Numbat on Chimera Linux Source: https://github.com/sharkdp/numbat/blob/main/book/src/cli/installation.md Installs Numbat on Chimera Linux using the apk add command after enabling the 'contrib' repository. ```bash doas apk add numbat ``` -------------------------------- ### Add Numbat to NixOS Configuration Source: https://github.com/sharkdp/numbat/blob/main/book/src/cli/installation.md Adds Numbat to the system packages in a NixOS configuration file. ```nix environment.systemPackages = [ pkgs.numbat ]; ``` -------------------------------- ### Install Numbat CLI Source: https://github.com/sharkdp/numbat/blob/main/README.md Installs the Numbat CLI version using Cargo. The '-f' flag forces reinstallation, and '--path' specifies the directory containing the CLI. ```bash cargo install -f --path numbat-cli ``` -------------------------------- ### Numbat Interactive Session Example Source: https://github.com/sharkdp/numbat/blob/main/book/src/cli/usage.md Demonstrates a typical interaction within the Numbat REPL, showing calculations and referencing the previous answer. ```numbat >>> 60 kW h / 150 kW = 0.4 h >>> ans -> minutes = 24 min ``` -------------------------------- ### Build Documentation with Auto-Generated Content (Bash) Source: https://github.com/sharkdp/numbat/blob/main/book/README.md Builds the complete Numbat documentation, including generating example files, function reference documentation, and the units list. The output is placed in the 'site/' directory. ```bash uv run build ``` -------------------------------- ### Scale Recipe Ingredients with Numbat Source: https://github.com/sharkdp/numbat/blob/main/book/src/examples/example-recipe.md Scales ingredient quantities for a recipe based on a change in the number of servings. It defines original and desired servings, then uses a function to calculate the new quantities. This example demonstrates Numbat's ability to handle units and perform calculations. ```numbat # Scale ingredient quantities based on desired servings. @aliases(servings) unit serving let original_recipe_servings = 2 servings let desired_servings = 3 servings fn scale(quantity) = quantity × desired_servings / original_recipe_servings print("Milk: {scale(500 ml)}") print("Flour: {scale(250 g)}") print("Sugar: {scale(2 cups)}") print("Baking powder: {scale(4 tablespoons)}") ``` -------------------------------- ### Run Numbat Interactive Session Source: https://github.com/sharkdp/numbat/blob/main/book/src/cli/usage.md Starts an interactive Numbat session (REPL) for performing calculations and sequences of operations. Uses 'ans' or '_' to refer to the last result. ```bash numbat ``` -------------------------------- ### Numbat Date and Time Examples Source: https://github.com/sharkdp/numbat/blob/main/book/src/basics/date-and-time.md Demonstrates various operations for date and time handling in Numbat, including calculating time differences, converting timezones, and performing date arithmetic. ```numbat # How many days have passed since the beginning of the millennium? today() - date("2000-01-01") -> days # What time is it in Nepal right now? now() -> tz("Asia/Kathmandu") # use tab completion to find time zone names # What is the local time when it is 2024-11-01 12:30:00 in Australia? datetime("2024-11-01 12:30:00 Australia/Sydney") -> local # Which date was 1 million seconds ago? now() - 1 million seconds # Which date is 40 days from now? calendar_add(now(), 40 days) # Which weekday was the 1st day of this century? date("2000-01-01") -> weekday # What is the current UNIX timestamp? now() -> unixtime_s # What is the date corresponding to a given UNIX timestamp? from_unixtime_s(1707568901) # How long are one million seconds in years, months, days, hours, minutes, seconds? 1 million seconds -> human ``` -------------------------------- ### Numbat Parsing and Pretty-Printing Example Source: https://github.com/sharkdp/numbat/blob/main/book/src/basics/operations.md Demonstrates how Numbat parses an expression involving unit conversion and division, showing the intermediate parsed structure and the final pretty-printed result with unit simplification. ```numbat >>> 1 / meter per second 1 / (meter / second) = 1 s/m ``` -------------------------------- ### Take First N Elements Source: https://github.com/sharkdp/numbat/blob/main/book/src/prelude/functions/lists.md Get the first `n` elements of a list using the `take` function. ```APIDOC ## GET /list/take ### Description Get the first `n` elements of a list. ### Method GET ### Endpoint /list/take ### Parameters #### Query Parameters - **n** (Scalar) - Required - The number of elements to take from the beginning of the list. - **xs** (List) - Required - The list from which to take elements. ### Response #### Success Response (200) - **result** (List) - A new list containing the first `n` elements. #### Response Example ```json { "result": [ 3, 2 ] } ``` ``` -------------------------------- ### Implement and Test Factorial in Numbat Source: https://github.com/sharkdp/numbat/blob/main/book/src/examples/example-factorial.md This Numbat code defines a recursive function to calculate the factorial of a number. It uses conditional logic to handle the base case (n < 1) and the recursive step. The example also includes an assertion to compare the custom implementation with Numbat's built-in factorial operator. ```numbat # Naive factorial implementation to showcase recursive # functions and conditionals. fn factorial(n) = if n < 1 then 1 else n × factorial(n - 1) # Compare result with the builtin factorial operator assert_eq(factorial(10), 10!) ``` -------------------------------- ### Generate Numbat Configuration Source: https://github.com/sharkdp/numbat/blob/main/book/src/cli/customization.md Command to generate a default Numbat configuration file. This is useful for users who want to start customizing Numbat without manually creating the configuration file. ```bash numbat --generate-config ``` -------------------------------- ### Create and Use Numbat Lists Source: https://github.com/sharkdp/numbat/blob/main/book/src/basics/lists.md Demonstrates the creation of Numbat lists with various element types and showcases common list operations like getting length, summing elements, calculating the mean, filtering, mapping, generating ranges, and creating evenly spaced lists. ```nbt [ 30 cm, 110 cm, 2 m ] ["a", "b", "c"] [[1, 2], [3, 4]] # Get the length of a list len([1, 2, 3]) # returns 3 # Sum all elements of a list: sum([30 cm, 130 cm, 2 m]) # returns 360 cm # Get the average of a list: mean([30 cm, 130 cm, 2 m]) # returns 120 cm # Filter a list: filter(is_finite, [20 cm, inf, 1 m]) # returns [20 cm, 1 m] # Map a function over a list: map(sqr, [10 cm, 2 m]) # returns [100 cm², 4 m²] # Generate a range of numbers: range(1, 5) # returns [1, 2, 3, 4, 5] # Generate a list of evenly spaced quantities: linspace(0 m, 1 m, 5) # returns [0 m, 0.25 m, 0.5 m, 0.75 m, 1 m] ``` -------------------------------- ### Get First Element Source: https://github.com/sharkdp/numbat/blob/main/book/src/prelude/functions/lists.md Retrieve the first element of a list using the `head` function. This will result in a runtime error if the list is empty. ```APIDOC ## GET /list/head ### Description Get the first element of a list. Yields a runtime error if the list is empty. ### Method GET ### Endpoint /list/head ### Parameters #### Query Parameters - **xs** (List) - Required - The list from which to get the first element. ### Response #### Success Response (200) - **result** (A) - The first element of the list. #### Response Example ```json { "result": 3 } ``` ``` -------------------------------- ### String Find Source: https://github.com/sharkdp/numbat/blob/main/book/src/prelude/functions/strings.md Finds the starting index of the first occurrence of a substring within a larger string. ```APIDOC ## str_find ### Description Find the first occurrence of a substring in a string. ### Method N/A (Function Call) ### Endpoint N/A (Function Call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```nbt str_find("typed", "Numbat is a statically typed programming language.") = 23 ``` ### Response #### Success Response (200) - **result** (Scalar) - The starting index of the first occurrence, or -1 if not found. #### Response Example ```json { "result": 23 } ``` ``` -------------------------------- ### Basic Arithmetic Computations in Numbat Source: https://github.com/sharkdp/numbat/blob/main/book/src/index.md Demonstrates simple mathematical operations in Numbat, including division, exponentiation, and square roots combined with trigonometric functions. These examples show Numbat's ability to perform standard arithmetic. ```numbat >>> 1920 / 16 * 9 = 1080 >>> 2^32 = 4_294_967_296 >>> sqrt(1.4^2 + 1.5^2) * cos(pi / 3)^2 = 0.512957 ``` -------------------------------- ### Numbat Compile-Time Evaluated Exponent Example Source: https://github.com/sharkdp/numbat/blob/main/book/src/advanced/type-system.md Demonstrates an exponentiation expression where the exponent is a compile-time evaluable constant. Numbat allows this for dimensionfull bases, ensuring type safety by evaluating the exponent to a rational number. ```numbat meter^(2 * (2 + 1) / 3) ``` -------------------------------- ### Dimensional Analysis Example in Numbat Source: https://github.com/sharkdp/numbat/blob/main/book/src/examples/example-xkcd_687.md This Numbat code snippet performs dimensional analysis to calculate a dimensionless quantity. It defines variables for core pressure, Prius mileage, and minimum channel width, then computes a ratio involving Planck energy. The output checks if the result is approximately pi. ```numbat # Dimensional analysis # # https://xkcd.com/687/ let core_pressure = 3.5 million atmospheres let prius_milage = 50 miles per gallon let min_width_channel = 21 miles # Make sure that the result is dimensionless: let r: Scalar = planck_energy / core_pressure × prius_milage / min_width_channel print("{r} ≈ π ?") ``` -------------------------------- ### Random Number Generation in Numbat Source: https://context7.com/sharkdp/numbat/llms.txt Provides examples of various random number generation functions in Numbat, including uniform, normal, Bernoulli, binomial, Poisson, exponential, and geometric distributions. ```numbat # Uniform random number in [0, 1) >>> random() # Uniform distribution over interval [a, b) >>> rand_uniform(0 m, 10 m) # Random integer from [a, b] >>> rand_int(1, 6) # Normal distribution with mean μ and standard deviation σ >>> rand_norm(170 cm, 10 cm) # Bernoulli distribution (returns 1 with probability p) >>> rand_bernoulli(0.5) # Binomial distribution (n trials with probability p) >>> rand_binom(10, 0.5) # Poisson distribution with rate λ >>> rand_poisson(5) # Exponential distribution with rate λ >>> rand_expon(1 / second) # Geometric distribution >>> rand_geom(0.3) ``` -------------------------------- ### Numbat Configuration Options (TOML) Source: https://github.com/sharkdp/numbat/blob/main/book/src/cli/customization.md Example TOML configuration for Numbat, illustrating various settings such as intro banner, prompt character, pretty-printing, edit mode, color output, and formatting options for numbers and dates. It also includes settings for exchange rate fetching. ```toml # Controls the welcome message. Can be "long", "short", or "off". intro-banner = "long" # Controls the prompt character(s) in the interactive terminal. prompt = ">>> " # Whether or not to pretty-print expressions before showing the result. # Can be "always", "never" or "auto". The latter uses pretty-printing # only in interactive mode. pretty-print = "auto" # Controls the edit mode. Can be "emacs", or "vi". edit-mode = "emacs" # Whether or not to use colors in the output. # Can be "always", "never" or "auto". color = "auto" [formatting] # Digit separator for large integers. # Common options: "_", ",", " ", "'", or "" to disable. digit-separator = "_" # Minimum number of digits before adding separators. # e.g., 6 means 12345 has no separator, but 123456 becomes 123_456. digit-grouping-threshold = 6 # Maximum significant digits for floating-point display. significant-digits = 6 # Controls the format used to display DateTime values. Uses strftime-style # format specifiers. Use "%.f" to include fractional seconds. datetime = "%Y-%m-%d %H:%M:%S" [exchange-rates] # When and if to load exchange rates from the European Central Bank for # currency conversions. Can be "on-startup" to always fetch exchange rates # in the background when the application is started. With "on-first-use", # Numbat only fetches exchange rates when they are needed. Exchange rate # fetching can also be disabled using "never". The latter will lead to # "unknown identifier" errors when a currency unit is being used. fetching-policy = "on-startup" ``` -------------------------------- ### Basic List Operations in Numbat Source: https://context7.com/sharkdp/numbat/llms.txt Numbat provides basic operations for lists, including getting the length, the first element (head), and the rest of the list (tail). ```numbat # Basic list operations >>> len([1, 2, 3]) = 3 >>> head([3, 2, 1]) = 3 >>> tail([3, 2, 1]) = [2, 1] [List] ``` -------------------------------- ### Generic Function for Square Root Source: https://github.com/sharkdp/numbat/blob/main/book/src/advanced/type-system.md Provides an example of a generic function 'sqrt' that operates on types with squared dimensions. It shows two equivalent ways to specify the type signature for the square root function. ```numbat fn sqrt(x: D^2) -> D // Alternatively: // fn sqrt(x: D) -> D^(1/2) ``` -------------------------------- ### Numbat Custom Unit and Dimension Example for IV Drip Rate Source: https://github.com/sharkdp/numbat/blob/main/assets/articles/intro.html This Numbat code snippet demonstrates defining custom units and dimensions. It introduces a 'drops' unit, defines a 'DripRate' dimension, and calculates the IV drip rate in 'drops per minute' for a given saline volume and infusion time. ```numbat unit drops # Implicitly creates a new base dimension 'Drops' dimension DripRate = Drops / Time let saline_volume = 1200 mL let drop_factor = 15 drops / mL let total_time = 6 hours let iv_drip_rate = saline_volume * drop_factor / total_time iv_drip_rate -> drops / min ``` -------------------------------- ### Get Command-Line Arguments (Numbat) Source: https://github.com/sharkdp/numbat/blob/main/book/src/prelude/functions/math.md Retrieves the command-line arguments passed to the script. The first element in the returned list is the script name. This function is useful for dynamic script behavior based on user input. ```nbt fn args() -> List ``` -------------------------------- ### Numbat Date, Time, and Duration Functions Source: https://github.com/sharkdp/numbat/blob/main/book/src/basics/date-and-time.md Lists and describes the available functions in Numbat for date, time, and duration handling, such as getting current time, parsing strings, formatting, timezone conversions, and timestamp conversions. ```numbat now() -> DateTime today() -> DateTime datetime(input: String) -> DateTime date(input: String) -> DateTime time(input: String) -> DateTime format_datetime(format: String, dt: DateTime) -> String tz(tz: String) -> Fn[(DateTime) -> DateTime] local(dt: DateTime) -> DateTime get_local_timezone() -> String unixtime_s(dt: DateTime) -> Scalar unixtime_ms(dt: DateTime) -> Scalar unixtime_µs(dt: DateTime) -> Scalar from_unixtime_s(ut: Scalar) -> DateTime from_unixtime_ms(ut: Scalar) -> DateTime from_unixtime_µs(ut: Scalar) -> DateTime calendar_add(dt: DateTime, span: Time) -> DateTime calendar_sub(dt: DateTime, span: Time) -> DateTime weekday(dt: DateTime) -> String human(duration: Time) -> String julian_date(dt: DateTime) -> Scalar ``` -------------------------------- ### Calculate Photons Received Per Bit from Voyager Source: https://github.com/sharkdp/numbat/blob/main/book/src/examples/example-voyager.md This Numbat script calculates the number of photons received per bit transmitted from Voyager 1. It defines variables for data rate, transmission frequency and power, and then calculates the energy per photon, photon rate, received power, and finally, photons per bit. It uses custom units and aliases for clarity. ```numbat # How many photons are received per bit transmitted from Voyager 1? # # This calculation is adapted from a Physics Stack Exchange answer [1]. # # [1] https://physics.stackexchange.com/a/816710 # Voyager radio transmission: let datarate = 160 bps let f = 8.3 GHz let P_transmit = 23 W let ω = 2π f let λ = c / f @aliases(photon) unit photons let energy_per_photon = ℏ ω / photon let photon_rate = P_transmit / energy_per_photon -> photons/s print("Voyager sends data at a rate of {datarate} with {P_transmit}.") print("At a frequency of {f}, this amounts to {photon_rate:.0e}.") # Voyager dish antenna: let d_voyager = 3.7 m # Voyagers distance to Earth: let R = 23.5 billion kilometers # as of 2024 # Diameter of receiver dish: let d_receiver = 70 m let irradiance = P_transmit / (4π R²) let P_received: Power = irradiance × (π d_voyager / λ)² × (π d_receiver² / 4) print("A {d_receiver} dish on Earth will receive {P_received -> aW:.1f} of power.") let photon_rate_receiver = P_received / energy_per_photon -> photons/s let photons_per_bit = photon_rate_receiver / datarate -> photons/bit print() print("This corresponds to {photon_rate_receiver}.") print("Which means {photons_per_bit:.0}.") ``` -------------------------------- ### Physical Unit Calculations in Numbat Source: https://github.com/sharkdp/numbat/blob/main/book/src/index.md Illustrates Numbat's core strength: performing calculations with physical dimensions and units. Examples include velocity, currency conversion, angle calculations, and energy calculations using physical constants. ```numbat >>> 110 km / (1 day + 3 hours) = 4.07407 km/h [Velocity] >>> 140 € -> GBP = 120.768 £ [Money] >>> atan2(30 cm, 1 m) -> deg = 16.6992° >>> let ω = 2π c / 660 nm >>> ℏ ω -> eV = 1.87855 eV [Energy] ``` -------------------------------- ### Inferring Acceleration with Typed Holes Source: https://github.com/sharkdp/numbat/blob/main/book/src/advanced/typed-holes.md Demonstrates using a typed hole to infer the expected type for an unknown expression in a physics formula. This example shows how Numbat can determine that 'Acceleration' is the missing type when calculating force using Newton's second law. ```numbat let mass = 1 kg let f: Force = mass * ? ``` -------------------------------- ### Unit Conversion and Rounding Example in Numbat Source: https://github.com/sharkdp/numbat/blob/main/book/src/examples/example-xkcd_2585.md This Numbat code snippet defines a speed in miles per hour and then converts and rounds it to multiple different units. It demonstrates the flexibility of Numbat for handling various units and performing chained operations. ```numbat # Rounding # # https://xkcd.com/2585/ let speed = 17 mph |> round_in(meters/sec) |> round_in(knots) |> round_in(fathoms/sec) |> round_in(furlongs/min) |> round_in(fathoms/sec) |> round_in(kph) |> round_in(knots) |> round_in(kph) |> round_in(furlongs/hour) |> round_in(mi/h) |> round_in(m/s) |> round_in(furlongs/min) |> round_in(yards/sec) |> round_in(fathoms/sec) |> round_in(m/s) |> round_in(mph) |> round_in(furlongs/min) |> round_in(knots) |> round_in(yards/sec) |> round_in(fathoms/sec) |> round_in(knots) |> round_in(furlongs/min) |> round_in(mph) print("I can ride my bike at {speed}.") print("If you round.") ``` -------------------------------- ### Get Current Date at Midnight in Numbat Source: https://github.com/sharkdp/numbat/blob/main/book/src/prelude/functions/datetime.md The `today` function returns the current date at midnight in the local time. It provides a DateTime object representing the start of the current day. ```nbt fn today() -> DateTime ``` -------------------------------- ### Serve Numbat Project Web Content with Python Source: https://github.com/sharkdp/numbat/blob/main/numbat-wasm/README.md Serves the `www` directory of the Numbat project using Python's built-in HTTP server. This allows for local testing of the web interface. It requires navigating to the `www` directory and then running the Python module. Access is typically via `http://0.0.0.0:8000/`. ```bash cd www python -m http.server ``` -------------------------------- ### Set Numbat System Module Path via Environment Variable Source: https://github.com/sharkdp/numbat/blob/main/book/src/cli/installation.md This snippet demonstrates how to set the NUMBAT_SYSTEM_MODULE_PATH environment variable. This variable is used during Numbat compilation to specify the final location of the Numbat modules folder. If this variable is set, the specified path will be compiled into the Numbat binary, allowing users to access the standard library source code. ```shell export NUMBAT_SYSTEM_MODULE_PATH="/path/to/numbat/modules" ``` -------------------------------- ### Build Numbat Project with Bash Source: https://github.com/sharkdp/numbat/blob/main/numbat-wasm/README.md Executes the build script for the Numbat project. This is a standard bash script that compiles or prepares the project for distribution. No specific inputs or outputs are detailed, but it's assumed to modify the project's build artifacts. ```bash bash build.sh ``` -------------------------------- ### Get Element at Index Source: https://github.com/sharkdp/numbat/blob/main/book/src/prelude/functions/lists.md Get the element at a specific index in a list using the `element_at` function. ```APIDOC ## GET /list/element_at ### Description Get the element at index `i` in a list. ### Method GET ### Endpoint /list/element_at ### Parameters #### Query Parameters - **i** (Scalar) - Required - The index of the element to retrieve (0-based). - **xs** (List) - Required - The list from which to get the element. ### Response #### Success Response (200) - **result** (A) - The element at the specified index. #### Response Example ```json { "result": 1 } ``` ``` -------------------------------- ### Instantiate Numbat Struct Source: https://github.com/sharkdp/numbat/blob/main/book/src/basics/structs.md Demonstrates how to create an instance of a previously defined Numbat struct ('Element') by providing values for each of its fields. This allows for the creation of specific data points. ```nbt let tungsten = Element { name: "Tungsten", atomic_number: 74, density: 19.25 g/cm³, } ``` -------------------------------- ### Get Tail of List Source: https://github.com/sharkdp/numbat/blob/main/book/src/prelude/functions/lists.md Get all elements of a list except the first one using the `tail` function. This will result in a runtime error if the list is empty. ```APIDOC ## GET /list/tail ### Description Get everything but the first element of a list. Yields a runtime error if the list is empty. ### Method GET ### Endpoint /list/tail ### Parameters #### Query Parameters - **xs** (List) - Required - The list from which to get the tail. ### Response #### Success Response (200) - **result** (List) - A new list containing all elements except the first. #### Response Example ```json { "result": [ 2, 1 ] } ``` ``` -------------------------------- ### Slice String in Numbat Source: https://github.com/sharkdp/numbat/blob/main/book/src/prelude/functions/strings.md Extracts a portion of a string based on start and end indices. It requires scalar values for start and end, and the string to slice, returning the resulting substring. ```numbat fn str_slice(start: Scalar, end: Scalar, s: String) -> String ``` -------------------------------- ### Root Finding Methods in Numbat Source: https://context7.com/sharkdp/numbat/llms.txt Illustrates various root-finding algorithms available in Numbat's `numerics` module, including the bisection method, Newton's method, and fixed-point iteration. ```numbat use numerics::solve fn f(x) = x² + x - 2 >>> root_bisect(f, 0, 100, 0.01, 0.01) = 1.00098 fn f(x) = x² - 3x + 2 fn f_prime(x) = 2x - 3 >>> root_newton(f, f_prime, 0, 0.01) = 0.996078 use numerics::fixed_point fn function(x) = x/2 - 1 >>> fixed_point(function, 0, 0.01) = -1.99219 ``` -------------------------------- ### Run Numbat Project Tests with Bash Source: https://github.com/sharkdp/numbat/blob/main/numbat-wasm/README.md Executes the test suite for the Numbat project using a bash script. This command is used to verify the functionality and integrity of the project. It's a straightforward execution of the `test.sh` script. ```bash bash test.sh ``` -------------------------------- ### Grandpa Simpson's Car Mileage Conversion Example Source: https://github.com/sharkdp/numbat/blob/main/book/src/basics/conversions.md A practical example demonstrating unit conversions for Grandpa Simpson's car mileage, converting rods per hogshead to miles per gallon, feet per gallon, and liters per 100 km. ```numbat >>> 40 rods / hogshead -> mpg = 0.00198413 mpg [Length⁻²] >>> 40 rods / hogshead -> ft / gallon = 10.4762 ft/gal [Length⁻²] >>> 1 / (40 rods / hogshead) -> L / (100 km) = 118548 × 0.01 l/km [Area] ``` -------------------------------- ### Generate a list of evenly spaced numbers in Numbat Source: https://github.com/sharkdp/numbat/blob/main/book/src/prelude/functions/lists.md The `linspace` function creates a list containing a specified number of evenly spaced values between a start and end point, inclusive. It takes the start value, end value, and the number of steps as input. This is useful for creating ranges for plotting or numerical analysis. ```nbt fn linspace(start: D, end: D, n_steps: Scalar) -> List linspace(-5 m, 5 m, 11) = [-5 m, -4 m, -3 m, -2 m, -1 m, 0 m, 1 m, 2 m, 3 m, 4 m, 5 m] [List] ``` -------------------------------- ### List Length Source: https://github.com/sharkdp/numbat/blob/main/book/src/prelude/functions/lists.md Get the length of a list using the `len` function. ```APIDOC ## GET /list/len ### Description Get the length of a list. ### Method GET ### Endpoint /list/len ### Parameters #### Query Parameters - **xs** (List) - Required - The list to get the length of. ### Response #### Success Response (200) - **result** (Scalar) - The length of the list. #### Response Example ```json { "result": 3 } ``` ``` -------------------------------- ### String Slice Source: https://github.com/sharkdp/numbat/blob/main/book/src/prelude/functions/strings.md Extracts a subslice of a string given start and end indices. ```APIDOC ## str_slice ### Description Subslice of a string. ### Method N/A (Function Call) ### Endpoint N/A (Function Call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```nbt str_slice(3, 6, "Numbat") = "bat" [String] ``` ### Response #### Success Response (200) - **result** (String) - The extracted subslice of the string. #### Response Example ```json { "result": "bat" } ``` ``` -------------------------------- ### Numbat Syntax: Constants Source: https://github.com/sharkdp/numbat/blob/main/book/src/examples/example-numbat_syntax.md Demonstrates how to declare constants in Numbat using the `let` keyword. It shows simple numerical constants, constants with unit annotations, and constants with more complex type annotations. ```numbat let n = 4 # Simple numerical constant let q1 = 2 m/s # Right hand side can be any expression let q2: Velocity = 2 m/s # With optional type annotation let q3: Length / Time = 2 m/s # more complex type annotation ``` -------------------------------- ### Get Day of Week in Numbat Source: https://context7.com/sharkdp/numbat/llms.txt Numbat can determine the day of the week for a given date. ```numbat # Get day of week >>> date("2000-01-01") -> weekday = "Saturday" [String] ``` -------------------------------- ### Build Documentation Without Regenerating Content (Bash) Source: https://github.com/sharkdp/numbat/blob/main/book/README.md Builds the Numbat documentation without regenerating auto-generated content. This is useful for faster builds when only static content has changed. ```bash uv run zensical build ``` -------------------------------- ### Print Expressions and Booleans in Numbat Source: https://github.com/sharkdp/numbat/blob/main/book/src/basics/printing-strings.md Demonstrates the basic usage of the `print` procedure in Numbat to display the results of expressions, including unit conversions and boolean comparisons. ```numbat print(2 km/h) print(3 ft < 1 m) ``` -------------------------------- ### Numbat: Type Inference for Arithmetic Source: https://github.com/sharkdp/numbat/blob/main/assets/articles/intro.html Illustrates how Numbat infers the type of an expression based on the types of its operands and the arithmetic operations involved. Multiplication and division combine types, while addition requires matching types. ```Numbat type(a * b) = type(a) * type(b) type(a / b) = type(a) / type(b) type(a + b) = if type(a) == type(b) { type(a) } else { error("incompatible dimensions in addition …") } ``` -------------------------------- ### Drop First N Elements Source: https://github.com/sharkdp/numbat/blob/main/book/src/prelude/functions/lists.md Get all elements of a list except the first `n` using the `drop` function. ```APIDOC ## GET /list/drop ### Description Get everything but the first `n` elements of a list. ### Method GET ### Endpoint /list/drop ### Parameters #### Query Parameters - **n** (Scalar) - Required - The number of elements to drop from the beginning of the list. - **xs** (List) - Required - The list from which to drop elements. ### Response #### Success Response (200) - **result** (List) - A new list with the first `n` elements removed. #### Response Example ```json { "result": [ 1, 0 ] } ``` ``` -------------------------------- ### Unit Definitions in Numbat Source: https://context7.com/sharkdp/numbat/llms.txt Demonstrates how to define new units in Numbat, including base units, derived units, and units with metric and binary prefixes. It also shows how to define custom units for counting and how to use them in calculations. ```numbat # Define a base unit with its physical dimension unit second: Time # Define a derived unit unit minute: Time = 60 second # Unit with metric prefixes enabled @metric_prefixes @aliases(meters, metre, metres, m: short) unit meter: Length # Unit with both metric and binary prefixes @binary_prefixes @metric_prefixes unit byte = 8 bit # Allows: mebibyte (1024² byte), megabyte (1000² byte) # Ad-hoc units for counting things unit book @aliases(pages) unit page @aliases(words) unit word let words_per_book = 500 words/page × 300 pages/book # Custom unit for screen resolution @aliases(dots) unit dot unit dpi = dots / inch fn inter_dot_spacing(resolution: Dot / Length) -> Length = 1 dot / resolution >>> inter_dot_spacing(72 dpi) -> µm = 353 µm [Length] ``` -------------------------------- ### Numbat: Basic Unit Computation Source: https://github.com/sharkdp/numbat/blob/main/assets/articles/intro.html Demonstrates a simple Numbat expression for calculating the oscillation period of a pendulum. It shows how units can be mixed and how type annotations can be inferred. ```Numbat let pendulum_length: Length = 30 cm let t_oscillation: Time = 2 * pi * sqrt(pendulum_length / g0) t_oscillation ``` -------------------------------- ### Current Date and Time Functions in Numbat Source: https://context7.com/sharkdp/numbat/llms.txt Numbat provides functions to get the current date and time, as well as the current date only. ```numbat # Current date and time >>> now() >>> today() ``` -------------------------------- ### Get Moon Phase Name Source: https://github.com/sharkdp/numbat/blob/main/book/src/prelude/functions/other.md Converts a moon phase value (LunarCycle) into its corresponding name and Unicode symbol (e.g., '🌔 Waxing Gibbous'). ```numbat use extra::celestial datetime("2026-01-30 12:00:00 UTC") -> moon_phase -> moon_phase_name = "🌔 Waxing Gibbous" [String] ``` -------------------------------- ### Command-line Arguments Source: https://github.com/sharkdp/numbat/blob/main/book/src/prelude/functions/math.md Retrieves the command-line arguments passed to the script. The first argument is the script name. ```APIDOC ## `args` (Command-line arguments) ### Description Returns the command-line arguments passed to the script. The first argument is the name of the script itself. ### Method N/A (Built-in function) ### Endpoint N/A ### Parameters None ### Request Example ```nbt let xs = tail(args()) ``` ### Response #### Success Response (200) - **List** - A list of strings representing the command-line arguments. #### Response Example ```json ["script_name.nbt", "arg1", "arg2"] ``` ``` -------------------------------- ### Get Chemical Element Properties in Numbat Source: https://github.com/sharkdp/numbat/blob/main/book/src/prelude/functions/other.md The `element` function retrieves properties of a chemical element using its symbol or name (case-insensitive). It returns a `ChemicalElement` struct. ```nbt fn element(pattern: String) -> ChemicalElement ``` -------------------------------- ### Run All Numbat Tests Source: https://github.com/sharkdp/numbat/blob/main/README.md Executes all tests defined within the Numbat project using Cargo. This command is essential for verifying the integrity of the codebase after changes. ```bash cargo test ``` -------------------------------- ### Get Unit Name as String in Numbat Source: https://github.com/sharkdp/numbat/blob/main/book/src/prelude/functions/other.md The `unit_name` function returns the string representation of a quantity's unit. If the quantity is dimensionless, it returns an empty string. ```nbt fn unit_name(quantity: T) -> String ``` -------------------------------- ### Numbat Syntax: Structs Source: https://github.com/sharkdp/numbat/blob/main/book/src/examples/example-numbat_syntax.md Illustrates the definition and instantiation of structs in Numbat, including structs with typed fields, generic structs, and accessing struct fields. ```numbat struct Element { name: String, atomic_number: Scalar, density: MassDensity, } let hydrogen = Element { name: "Hydrogen", atomic_number: 1, density: 0.08988 g/L, } hydrogen.density # Access the field of a struct struct Vec2 { x: D, y: D, } ``` -------------------------------- ### Calculate Power per Banana with Type Annotation in Numbat Source: https://github.com/sharkdp/numbat/blob/main/book/src/tutorial.md This code calculates the power contribution per banana, using the radioactivity per banana and the energy per decay. It includes a type annotation `: Power / Banana`, demonstrating type combination via mathematical operators. ```numbat let power_per_banana: Power / Banana = radioactivity_banana * energy_per_decay ``` -------------------------------- ### Get Current Date and Time in Numbat Source: https://github.com/sharkdp/numbat/blob/main/book/src/prelude/functions/datetime.md The `now` function returns the current date and time as a DateTime object. It does not require any arguments or external dependencies. ```nbt fn now() -> DateTime ``` -------------------------------- ### Get String Length in Numbat Source: https://github.com/sharkdp/numbat/blob/main/book/src/prelude/functions/strings.md Calculates the length of a given string. It takes a string as input and returns a scalar value representing the number of characters. ```numbat fn str_length(s: String) -> Scalar ``` -------------------------------- ### Variables and Type Annotations in Numbat Source: https://context7.com/sharkdp/numbat/llms.txt Illustrates how to define and use variables in Numbat, including immutable variables introduced with `let`. It shows the use of optional type annotations to enforce dimensional correctness at compile time and how the system catches dimensional errors. ```numbat # Basic variable definitions let pipe_radius = 1 cm let pipe_length = 10 m let Δp = 0.1 bar # Variables with type annotations for safety let μ_water: DynamicViscosity = 1 mPa·s let Q: FlowRate = π × pipe_radius^4 × Δp / (8 μ_water × pipe_length) # Type annotations catch dimensional errors let energy_per_decay: Energy = 11% × 1.5 MeV + 89% × 1.3 MeV # Using the result of previous calculations (in REPL) >>> 60 kW h / 150 kW = 0.4 h >>> ans -> minutes = 24 min ``` -------------------------------- ### Get Minimum Element of a List Source: https://github.com/sharkdp/numbat/blob/main/book/src/prelude/functions/math.md Returns the smallest element from a list of quantities. It requires a list of quantities of the same dimension as input and returns a single quantity of that dimension. ```nbt fn minimum(xs: List) -> D ``` -------------------------------- ### Get Weekday from DateTime Source: https://github.com/sharkdp/numbat/blob/main/book/src/prelude/functions/datetime.md The `weekday` function takes a `DateTime` object and returns the corresponding day of the week as a string. It is a straightforward utility for date analysis. ```nbt fn weekday(dt: DateTime) -> String ``` -------------------------------- ### Find Substring in Numbat Source: https://github.com/sharkdp/numbat/blob/main/book/src/prelude/functions/strings.md Locates the starting index of the first occurrence of a substring within a larger string. It returns a scalar representing the index or indicates absence. ```numbat fn str_find(needle: String, haystack: String) -> Scalar ``` -------------------------------- ### Run Numbat Script Source: https://github.com/sharkdp/numbat/blob/main/book/src/cli/usage.md Executes a Numbat program from a specified script file. The file should have a '.nbt' extension. ```bash numbat script.nbt ``` -------------------------------- ### Get List Length in Numbat Source: https://github.com/sharkdp/numbat/blob/main/book/src/prelude/functions/lists.md The `len` function returns the number of elements in a given list. It takes a list of any type `A` as input and returns a scalar representing the length. ```numbat fn len(xs: List) -> Scalar ``` -------------------------------- ### Calculate nth Fibonacci Number Source: https://github.com/sharkdp/numbat/blob/main/book/src/prelude/functions/math.md Returns the nth Fibonacci number, where n is a non-negative integer. The sequence starts with F0=0 and F1=1. It takes a scalar and returns a scalar. ```nbt fn fibonacci(n: Scalar) -> Scalar ``` -------------------------------- ### Run Numbat CLI Command Source: https://github.com/sharkdp/numbat/blob/main/README.md Executes the Numbat Command Line Interface with specified arguments. This command is used to interact with the Numbat compiler and tools. ```bash cargo run -- ``` -------------------------------- ### Entering Units in Numbat Source: https://github.com/sharkdp/numbat/blob/main/book/src/basics/unit-notation.md Demonstrates various styles for entering units in Numbat, showcasing different forms like long, plural, short, and those with prefixes. ```nbt 2 min + 1 s 150 cm sin(30°) 50 mph 6 MiB 25 °C 2 minutes + 1 second 150 centimeters sin(30 degrees) 50 miles per hour 6 mebibyte 25 degree_celsius ``` -------------------------------- ### Define Basic Variables in Numbat Source: https://github.com/sharkdp/numbat/blob/main/book/src/basics/variables.md Introduces variables using the 'let' keyword with simple values like length and pressure. No external dependencies are required for these basic definitions. ```nbt let pipe_radius = 1 cm let pipe_length = 10 m let Δp = 0.1 bar ``` -------------------------------- ### Apply Both Metric and Binary Prefixes in Numbat Source: https://github.com/sharkdp/numbat/blob/main/book/src/advanced/unit-definitions.md Applies both '@metric_prefixes' and '@binary_prefixes' decorators to a unit, allowing it to be used with both metric and binary prefixes. Example shows 'byte' definition. ```numbat @binary_prefixes @metric_prefixes unit byte = 8 bit ``` -------------------------------- ### Get Element at Index in Numbat Source: https://github.com/sharkdp/numbat/blob/main/book/src/prelude/functions/lists.md The `element_at` function retrieves an element from a list based on its index. It takes a scalar index `i` and a list of type `A`, returning the element of type `A` at that index. ```numbat fn element_at(i: Scalar, xs: List) -> A ``` -------------------------------- ### Convert Numbers to Other Bases using base() and |> Source: https://github.com/sharkdp/numbat/blob/main/book/src/basics/number-notation.md Shows how to convert numbers to a specified base using the `base(b, n)` function combined with the reverse function application operator `|>`. This allows for flexible base conversions. ```nbt 273 |> base(3) 144 |> base(12) ``` -------------------------------- ### Get Unicode Code Point of Character in Numbat Source: https://github.com/sharkdp/numbat/blob/main/book/src/prelude/functions/strings.md Retrieves the Unicode code point of the first character in a given string. It takes a string as input and returns a scalar value. ```numbat fn ord(s: String) -> Scalar ``` -------------------------------- ### Numbat Syntax: Function Definitions Source: https://github.com/sharkdp/numbat/blob/main/book/src/examples/example-numbat_syntax.md Illustrates various ways to define functions in Numbat, including simple functions, functions with multiple parameters, generic functions, functions returning booleans, and functions with local variables using `where` and `and`. ```numbat fn foo(z: Scalar) -> Scalar = 2 * z + 3 # A simple function fn speed(len: Length, dur: Time) -> Velocity = len / dur # Two parameters fn my_sqrt(q: T^2) -> T = q^(1/2) # A generic function fn is_non_negative(x: Scalar) -> Bool = x ≥ 0 # Returns a bool fn power_4(x: Scalar) = z # A function with local variables where y = x * x and z = y * y ``` -------------------------------- ### Define Base Unit in Numbat Source: https://github.com/sharkdp/numbat/blob/main/book/src/advanced/unit-definitions.md Introduces a new base unit by specifying its physical dimension. For example, 'second' is defined as the base unit for 'Time'. This assumes dimensions are pre-defined. ```numbat unit second: Time ``` -------------------------------- ### Timezone Conversions in Numbat Source: https://context7.com/sharkdp/numbat/llms.txt Numbat supports converting date and time values to different timezones. It also provides functions to get the current time and parse date/time strings. ```numbat # Timezone conversions >>> now() -> tz("Asia/Kathmandu") >>> datetime("2024-11-01 12:30:00 Australia/Sydney") -> local ```