# Frankie - The Programming Language — full documentation > Concatenated from 58 pages. Index: https://atejada.github.io/frankielanguage/site/llms.txt --- # Welcome to Frankie - The Programming Language Docs ![Frankie Logo](img/The Frankie Programming Language.png)

Latest version: Frankie v1.22.4

A procedural programming language lovingly stitched together from Ruby, Python, R, and Fortran. Zero dependencies. Proudly monstrous.

No install? Try Frankie in your browser — see The Playground

For Frankie's website visit The Frankie Language

## Hello, Frankie ```ruby name = "world" puts "Hello, #{name}!" for i in 1..3 puts "#{i} squared is #{i ** 2}" end ``` ## Install in 30 seconds ```bash brew install atejada/frankie/frankie frankiec run hello.fk ``` No Homebrew? Clone the repo and run `python3 install.py`, or [try it in your browser](getting_started/playground.md) with nothing to install. See [Installation](getting_started/installation.md). ## Where to go next - **[Installation](getting_started/installation.md)** and **[CLI Commands](getting_started/cli_commands.md)** — `frankiec run`, `test`, `check`, `fmt`, `repl`, `new`, `watch`. - **[Language](language/variables_and_types.md)** — variables, operators, conditionals, loops (including labeled loops), functions, error handling, modules. - **[Data Types](data_types/index.md)** — Integer, Float, String, Vector, Hash, Lambda, Record. - **[Standard Library](standard_library/math_statistics.md)** — math and matrices, files, JSON/CSV, HTTP, SQLite, a built-in web server, testing, regex and more. - **[Stitches](stitches/index.md)** — reusable library modules loaded with `stitch "name"`. - **[Examples](examples/index.md)** and **[Showcase](examples/showcase.md)** — runnable programs, from FizzBuzz to games. - **[Changelog](reference/changelog.md)** and **[Full Stdlib Index](reference/full_index.md)** — every release and every function. ## For AI agents and tools Plain-markdown access to these docs: [`llms.txt`](https://atejada.github.io/frankielanguage/site/llms.txt) (index) and [`llms-full.txt`](https://atejada.github.io/frankielanguage/site/llms-full.txt) (everything in one file). Every page also has a `.md` twin, e.g. `getting_started/playground.md`. --- # About ## What is Frankie? The Frankie Programming Language - A procedural language stitched from Ruby, Python, R and Fortran — with a built-in web server, SQLite, and zero dependencies. ## Who created Frankie? Frankie has been designed, coded, vibe-coded, build, whatever by Anthropic's Claude and I (Blag aka. Alvaro Tejada Galindo) ## Why Frankie? Because I wanted the power of Python with the syntax of Ruby, the elegance of Fortran and the statistics power of R. --- # Getting Started with Frankie ## Requirements * Python 3.10 or higher * No external dependencies — pure Python standard library ## Installation ### Homebrew (macOS/Linux) The easiest path if you're on a Mac or Linux box with Homebrew. Frankie ships as a third-party tap: ```bash brew tap atejada/frankie brew trust atejada/frankie # Homebrew 6.0+: third-party taps need explicit trust brew install frankie frankiec version # Frankie v1.22.4 ``` One-liner alternative (auto-taps and trusts just this formula): ```bash brew install atejada/frankie/frankie ``` Homebrew installs are pure Python stdlib too — the only dependency is `python@3.12`. Standard stitches resolve from the installed tree automatically, alongside project-local `./stitches` and `~/.frankie/stitches` (which still take precedence). To upgrade later: `brew upgrade frankie`. To remove: `brew uninstall frankie`. ### Git clone + installer ```bash git clone https://github.com/atejada/Frankie.git cd Frankie python3 install.py # Add frankie/bin to your PATH (add to ~/.bashrc or ~/.zshrc) export PATH="/path/to/frankie/bin:$PATH" ``` To uninstall: ```bash python3 install.py --uninstall ``` ### Without installing ```bash python3 frankiec.py run examples/hello.fk ``` --- ## Where the Examples Live Every install method ships the same bundle of examples and showcase projects (Hello World, Fizzbuzz, the full showcase, and playable projects like Snake and Zombie Chat). `frankiec` always knows where its own install lives, so you don't need to hunt for the source tree: ```bash frankiec examples # list everything bundled with this install frankiec examples snake # copy a project into the current directory cd snake && frankiec run main.fk ``` This works identically whether you installed via Homebrew, `git clone` + `install.py`, or an unpacked zip. * **Homebrew:** examples live at `$(brew --prefix frankie)/libexec/examples/` — typically `/opt/homebrew/opt/frankie/libexec/examples/` on Apple Silicon, or `/usr/local/opt/frankie/libexec/examples/` on Intel Macs. `frankiec examples` (no arguments) also prints this path directly, so you never have to work it out by hand. * **Git clone / zip:** examples are just `examples/` in the repo root. Single-file examples (like `fizzbuzz.fk`) copy as one `.fk` file; full projects (like `snake` or `frankie_ledger`) copy as a whole directory, including their pinned `stitches/` and `stitch.lock`. --- ## Quick Start ```bash frankiec repl # interactive REPL frankiec new myapp # scaffold a new project frankiec new --game mygame # scaffold a playable starter game frankiec run examples/hello.fk # run a program ``` --- # CLI Commands * `frankiec` - launch the REPL * `frankiec new [--game] ` - scaffold a new project (`--game`: playable starter, v1.20) * `frankiec run [--debug] ` - run a program (`--debug`: break at line 1, v1.19) * `frankiec build ` - compile to Python source * `frankiec bundle [-o out.py]` - compile to ONE self-contained .py (v1.18) * `frankiec check [--strict] ` - syntax check + static analysis (v1.17); directories recurse (v1.18) * `frankiec test [file.fk] [--filter ] [--tag ] [--coverage]` - run test suite (default: test.fk); `--coverage` since v1.19 * `frankiec fmt [--write] [--check] ` - auto-format; directories recurse (v1.18) * `frankiec docs [--html] [--output out.md] ` - generate docs; `--html` since v1.19 * `frankiec lsp` - start the Language Server (v1.18) * `frankiec stitch install [--global]` - install a stitch from the registry or any URL (v1.17; URLs v1.19) * `frankiec stitch list` - list installed + registry stitches (v1.17) * `frankiec stitch verify` - check installed stitches against stitch.lock (v1.18) * `frankiec stitch update [name]` - re-fetch + re-pin stitches (v1.18) * `frankiec examples [name]` - list bundled examples, or copy one here (v1.20.1) * `frankiec repl [--no-banner]` - interactive REPL * `frankiec watch [--test]` - re-run on save * `frankiec version` - show version * `frankiec --help` - full usage * `frankiec --help` - per-command help --- ## `frankiec lsp` — Language Server (v1.18) Frankie speaks the Language Server Protocol over stdio, built directly on the static analyzer: * **Live diagnostics** — undefined names, wrong argument counts, unused variables, lex/parse errors — as you type. * **Completion** — stdlib functions (with signatures + docs), your own functions, records, enums, and keywords. * **Hover** — signatures and documentation; `##` doc-comments above your `def`s show up in hover cards. The VS Code extension in the compiler repo (`editors/vscode/`) launches the server automatically. For Neovim (0.10+): ```lua vim.filetype.add({ extension = { fk = "frankie" } }) vim.api.nvim_create_autocmd("FileType", { pattern = "frankie", callback = function() vim.lsp.start({ name = "frankie", cmd = { "frankiec", "lsp" } }) end, }) ``` For Helix (`languages.toml`): ```toml [language-server.frankie] command = "frankiec" args = ["lsp"] [[language]] name = "frankie" scope = "source.frankie" file-types = ["fk"] language-servers = ["frankie"] ``` --- ## `frankiec examples` — Browse Bundled Examples (v1.20.1) ```bash frankiec examples # list everything bundled with this install frankiec examples snake # copy a project into the current directory cd snake && frankiec run main.fk ``` * With no argument, lists every project (in `examples/projects/`) and single-file example bundled with the install, plus the source directory. * With a name, copies that project directory — or single `.fk` file — into the current directory, ready to run. * Works identically for Homebrew, git-clone, and `install.py` installs — `frankiec` always knows where its own install lives. * Won't overwrite an existing file or directory of the same name. See [Where the Examples Live](installation.md#where-the-examples-live) for details on install-specific paths. --- ## `frankiec new --game` — Playable Starter (v1.20) ```bash frankiec new --game mygame cd mygame && frankiec run main.fk ``` Scaffolds a playable starter (a zombie you steer with the arrows) with the `frankiegame` stitch pre-installed and lockfile-pinned. See the [frankiegame](../stitches/frankiegame.md) and [frankiecanvas](../stitches/frankiecanvas.md) stitch pages for the full game engine API. --- ## `frankiec run --debug` — Stepping Debugger (v1.19) ```bash frankiec run --debug app.fk ``` Breaks at the very first line of the program, dropping you into the `(fkdb)` debug REPL before anything executes — useful for stepping through a program you've never read. See [Debugging & Benchmarking](../standard_library/debugging.md) for the full command reference (`s`, `n`, `stack`, `vars`, `c`). --- ## `frankiec docs --html` (v1.19) ```bash frankiec docs --html mystitch.fk --output mystitch.html ``` Renders `##` doc-comments (with `@param` / `@return` / `@example`) into a styled single-page HTML document matching the Frankie website's theme, instead of the default Markdown output. --- ## `frankiec bundle` — One-File Distribution (v1.18) ```bash frankiec bundle app.fk -o app.py python3 app.py # anywhere Python 3.8+ exists — no Frankie needed ``` The bundle inlines the entire Frankie stdlib and **pre-compiles every statically referenced file** — `require`, `import` and `stitch` targets, recursively. At runtime they resolve from an embedded registry instead of the filesystem. Dynamic paths (computed at runtime) can't be bundled and produce a warning. Write a tool, hand someone a single file. That's the whole story. --- ## `frankiec check` — Static Analysis (v1.17) `check` used to be syntax-only. It now finds real bugs before the program runs: ``` $ frankiec check app.fk ✗ app.fk:11 — Undefined function: 'greeet' ✗ app.fk:9 — greet() expects 1..2 argument(s), got 3 ⚠ app.fk:3 — Unused variable 'unused_thing' in function 'greet' [Frankie] app.fk — 2 error(s), 1 warning(s) ``` * Undefined variables/functions and wrong argument counts are **errors** (exit 1); unused locals are **warnings**. * `require`, `stitch` and `import` targets are resolved and analyzed, so multi-file programs check cleanly. * Names inside string interpolation (`"#{typo}"`) are checked too. * `--strict` makes warnings fail the build (CI mode). * If a required file can't be resolved (dynamic path), undefined-name errors downgrade to warnings instead of guessing. * Since v1.18, `check` and `fmt` accept directories and recurse into `.fk` files: ```bash frankiec check . # analyze the whole project frankiec check --strict src # CI mode — warnings fail too frankiec fmt --check . # formatting gate frankiec fmt --write . # fix everything in place ``` * Since v1.22.3, `fmt` preserves comments (full-line and trailing) and keeps parentheses that affect precedence. --- ## `frankiec test` — Filtering (v1.17) ```bash frankiec test # run everything frankiec test --filter math # only test groups whose name contains "math" frankiec test --tag slow # only test groups tagged "slow" frankiec test --coverage # v1.19 — report line coverage after the run ``` Works with `test "name", tags: [...] do ... end` groups — skipped groups are reported in the summary. `--coverage` writes `.frankie_coverage.json`, which the LSP reads to show uncovered lines as editor hints. See the [Testing](../standard_library/testing.md) page. --- ## `frankiec stitch` — Stitch Installer (v1.17) ```bash frankiec stitch install frankiecolor # → ./stitches/ frankiec stitch install frankiecache --global # → ~/.frankie/stitches/ frankiec stitch install https://example.com/stitches/foo.fk # v1.19 — any URL frankiec stitch list # installed + registry frankiec stitch verify # v1.18 — ✓ pinned · ⚠ modified · ✗ missing frankiec stitch update [name] # v1.18 — re-fetch + re-pin ``` Stitches are fetched straight from the Frankie GitHub repository using the Python stdlib HTTP client — a package manager with no packaging. Since v1.19, `install` also accepts arbitrary URLs, not just registry names. Since v1.18, installs are pinned in `stitch.lock` (sha256, source, size, date). Commit the lockfile for reproducible builds; `verify` exits 1 on problems, so it drops straight into CI. Global installs (`--global`) don't touch the lockfile. --- ## REPL (v1.17 upgrades) ``` fk> 2 + 3 => 5 fk> _ * 10 => 50 fk> help parallel_map parallel_map(vec, fn, workers=4) parallel_map(vec, workers: 4) do |x| ... end Runs the block across a thread pool... ``` * Bare expressions echo their value (`=>`), like Ruby's irb. * `_` always holds the last echoed result. * `help ` shows the signature and documentation of any stdlib or user-defined function. --- # The Frankie Playground Run Frankie in the browser, with nothing to install: **[Open the Playground](https://atejada.github.io/frankielanguage/#playground)**. It is **not a re-implementation**. The page runs the real compiler, standard library, formatter, test runner and bundled stitches — the same files that ship with `frankiec` — inside [Pyodide](https://pyodide.org) (CPython compiled to WebAssembly). Error messages, line mapping and test output match a local install. Nothing is sent to a server: your code runs in a Web Worker in your own tab. ## Buttons | Button | What it does | |--------|--------------| | **Run** (`Ctrl/Cmd + Enter`) | Compile and run `main.fk`; output streams into the Output pane | | **Test** | Run the `test "…" do … end` blocks with the built-in harness | | **Format** | `frankiec fmt` — comments and parentheses are preserved (v1.22.3) | | **Stop** | Kill the worker (programs running longer than 20 s are stopped automatically) | | **Share link** | Copy a URL whose `#pg=…` fragment contains your compressed code | | **Input (stdin)** | Lines fed to `input()`, `input_int()` and `input_float()` | An example picker offers short programs covering hello world, FizzBuzz, hashes, error handling, records, FORTRAN-style features, labeled loops, pipes, tests, stitches and input. Shared links never auto-run: opening one loads the code and waits for you to press Run. ## What does not work in a browser Pyodide has no sockets, threads or real terminal, so these only work in a real install: `web_app()` / `app.run`, `tcp_*` / `udp_*` / `ws_connect`, `http_*` requests, `spawn` and `parallel_map`, the terminal engine `frankiegame` (use `frankiecanvas` locally), `shell()`, and files that must outlive the tab (the in-browser filesystem resets on reload). A server program runs until the 20-second timeout and is then stopped with an explanatory message. ## First load The first use downloads Pyodide (about 7 MB, cached afterwards) and the Frankie bundle (about 120 KB gzipped). Later runs start instantly. --- # Variables & Types ## Variables Variables are created on first assignment. There is no declaration step — no `var`, `let`, or type annotation. Frankie figures out the type from the value. ```ruby name = "Alice" age = 30 score = 97.5 active = true nothing = nil ``` Variable names are lowercase with underscores. A variable referenced before assignment raises a runtime error. ```ruby puts mystery # Runtime error: Undefined variable: mystery ``` ### `Reassignment` A variable can be reassigned to any type at any time: ```ruby x = 42 x = "hello" # now a String — valid x = [1, 2, 3] # now a Vector — still valid ``` ### `Multiple Assignment (Destructuring)` Assign several variables at once from a vector: ```ruby a, b, c = [10, 20, 30] puts a # 10 puts b # 20 puts c # 30 # Extra variables are set to nil x, y, z = [1, 2] puts z # nil # Common use: functions that return multiple values def min_max(v) [min(v), max(v)] end lo, hi = min_max([3, 1, 4, 1, 5, 9]) puts "#{lo}..#{hi}" # 1..9 ``` ### `Hash Destructuring` Assign several variables at once from a hash: ```ruby user = {name: "Alice", age: 30, role: "admin"} {name, age} = user puts "name=#{name} age=#{age}" rows = [{city: "Lima", country: "Peru"}, {city: "Tokyo", country: "Japan"}] rows.each do |row| {city, country} = row puts "#{city}, #{country}" end ``` --- ## Reserved Names `p` is the debug-print shortcut (`p 5` prints `(Integer) 5`), so don't use it as a variable or parameter name — `p = 5` and `def f(p)` are parse errors. `stitch` and `require` are also fully reserved. Pick a different name (`pos`, `prev`, `item`) instead. --- ## `Constants` Names written in `UPPER_SNAKE_CASE` are treated as constants. Reassignment prints a warning and the original value is preserved. ```ruby MAX_RETRIES = 3 PI = 3.14159 APP_NAME = "Frankie" puts MAX_RETRIES # 3 MAX_RETRIES = 10 # Warning: MAX_RETRIES is a constant puts MAX_RETRIES # 3 — unchanged ``` --- ## `Enums` (v1.18) `enum` declares a named set of symbolic values. Members are their own names as strings — no hidden integers: ```ruby enum Status(pending, active, done) puts Status.pending # pending puts Status.values # [pending, active, done] puts Status.include?("done") # true case order_state when Status.active ship_it() end ``` Because members are plain strings, enums round-trip cleanly through JSON, CSV, and databases. `enum` is a contextual keyword — a variable named `enum` keeps working. --- ## `Types` Frankie is **dynamically typed** — every value has a type, but variables do not. The type is determined by the value at the time it is used. | Type | Example | Description | |---|---|---| | `Integer` | `42`, `-7` | Whole numbers, no size limit | | `Float` | `3.14`, `-0.5` | Decimal numbers | | `String` | `"hello"` | UTF-8 text | | `Boolean` | `true`, `false` | Logical values | | `Nil` | `nil` | Absence of a value | | `Vector` | `[1, 2, 3]` | Ordered list | | `Hash` | `{name: "Alice"}` | Key-value map | | `Lambda` | `->(x) { x * 2 }` | Storable function | | `Record` | `Point(x: 3, y: 4)` | Named data object | --- ## `Type Checking` ```ruby puts is_integer(42) # true puts is_float(3.14) # true puts is_string("hello") # true puts is_vector([1,2,3]) # true puts is_nil(nil) # true puts is_bool(true) # true ``` --- ## `Type Conversion` Frankie does not coerce types silently. Convert explicitly: ```ruby puts 42.to_s # "42" — Integer to String puts 42.to_f # 42.0 — Integer to Float puts "42".to_i # 42 — String to Integer puts "3.14".to_f # 3.14 — String to Float puts 3.9.to_i # 3 — Float to Integer (truncates) # Standalone function forms puts to_int("42") # 42 puts to_float("3.14") # 3.14 puts to_str(42) # "42" ``` Inside `#{}` interpolation, any value is converted to a string automatically — no `.to_s` needed: ```ruby n = 42 puts "The answer is #{n}" # The answer is 42 puts "Double is #{n * 2}" # Double is 84 puts "Type check: #{is_integer(n)}" # Type check: true ``` --- ## `Truthiness` `if`, `while`, `until`, and the inline-`if` expression follow Python-style truthiness: `false`, `nil`, `0`, `0.0`, `""`, `[]`, and `{}` are all falsy. Everything else is truthy. ```ruby puts(if 0 then "truthy" else "falsy" end) # falsy puts(if "" then "truthy" else "falsy" end) # falsy puts(if [] then "truthy" else "falsy" end) # falsy puts(if false then "truthy" else "falsy" end) # falsy puts(if nil then "truthy" else "falsy" end) # falsy ``` The exception is `||=` (nil-coalescing assignment), which uses Ruby's model instead — only `nil` and `false` trigger the fallback: ```ruby a = 0 a ||= 99 puts a # 0 — kept, not nil/false ``` See [Conditionals](conditionals.md#truthiness) for the full picture, including why `then` only works in this inline-`if` *expression* form. --- ## `Nil Safety` Calling a method on `nil` raises a runtime error. The `&.` operator returns `nil` instead of crashing: ```ruby name = nil puts name.upcase # Runtime error puts name&.upcase # nil — safe # Chains short-circuit at the first nil puts name&.upcase&.reverse # nil ``` --- ## `Scope` Frankie has simple lexical scope. Variables defined in the outer scope are readable inside functions and blocks. Variables assigned inside a function are local to that function. ```ruby x = 10 def show puts x # readable — outer scope is accessible end show() # 10 def modify x = 99 # local to modify — does not affect outer x end modify() puts x # 10 — unchanged ``` Unlike Ruby, Frankie always requires parentheses to call a function, even with zero arguments — a bare `show` (no `()`) is just a reference to the function object and does nothing as a statement. --- # Operators ## Arithmetic | Operator | Meaning | Example | Result | |---|---|---|---| | `+` | Addition | `10 + 3` | `13` | | `-` | Subtraction | `10 - 3` | `7` | | `*` | Multiplication | `10 * 3` | `30` | | `/` | Float division | `10 / 3` | `3.333...` | | `//` | Integer division | `10 // 3` | `3` | | `%` | Modulo | `10 % 3` | `1` | | `**` | Exponentiation | `2 ** 8` | `256` | `/` always returns a Float. Use `//` (borrowed from Fortran) when you want a whole-number result. ```ruby puts 10 / 3 # 3.3333333333333335 puts 10 // 3 # 3 puts 10 % 3 # 1 puts 2 ** 10 # 1024 ``` `*` and `**` also work on strings and vectors: ```ruby puts "ha" * 3 # hahaha puts [0] * 4 # [0, 0, 0, 0] puts [1, 2] * 3 # [1, 2, 1, 2, 1, 2] ``` --- ## Compound Assignment Shorthand for `x = x op value`: ```ruby x = 10 x += 3 # 13 x -= 2 # 11 x *= 4 # 44 x /= 2 # 22.0 (float division) x //= 5 # 4 (integer division) x **= 2 # 16 x %= 5 # 1 ``` Works on vector elements too: ```ruby v = [10, 20, 30] v[0] += 5 puts v # [15, 20, 30] ``` --- ## Comparison Comparison operators return `true` or `false`. | Operator | Meaning | |---|---| | `==` | Equal | | `!=` | Not equal | | `<` | Less than | | `<=` | Less than or equal | | `>` | Greater than | | `>=` | Greater than or equal | ```ruby puts 5 == 5 # true puts 5 != 3 # true puts 5 > 3 # true puts 5 < 3 # false puts 5 >= 5 # true puts 5 <= 4 # false # Integers and Floats compare naturally puts 3 == 3.0 # true puts 3 < 3.14 # true # Strings compare lexicographically puts "apple" < "banana" # true puts "z" > "a" # true ``` --- ## Logical | Operator | Meaning | Example | |---|---|---| | `and` | Both must be true | `x > 0 and x < 10` | | `or` | At least one must be true | `x < 0 or x > 100` | | `not` | Negate | `not active` | ```ruby age = 25 active = true if age >= 18 and active puts "eligible" end if age < 0 or age > 120 puts "invalid age" end if not active puts "inactive" end ``` Short-circuit evaluation applies — `and` stops at the first false, `or` stops at the first true. --- ## Match Operator `=~` Returns the **position** of the first regex match, or `nil` if there is no match. ```ruby puts "frank123" =~ "\\d+" # 5 puts "no digits" =~ "\\d+" # nil pos = "hello world" =~ "world" if pos != nil puts "found at position #{pos}" # found at position 6 end ``` --- ## String Concatenation `+` ```ruby puts "Hello, " + "Frankie!" # Hello, Frankie! first = "Frank" last = "ie" puts first + last # Frankie ``` --- ## Hash Merge `|` Merges two hashes. Right-hand keys win on conflict. ```ruby defaults = {color: "blue", size: "md", weight: "normal"} custom = {color: "red", size: "lg"} result = defaults | custom puts result # {color: red, size: lg, weight: normal} # Chains naturally base = {a: 1, b: 2} mid = {b: 3, c: 4} top = {c: 5, d: 6} puts base | mid | top # {a: 1, b: 3, c: 5, d: 6} ``` --- ## Pipe Operator `|>` Passes the result of the left side as the argument to the right side. Borrowed from R. ```ruby [1, 2, 3, 4, 5] |> sum # 15 [1, 2, 3, 4, 5] |> mean # 3.0 [1, 2, 3, 4, 5] |> sum |> puts # 15 def double(x) x * 2 end 10 |> double |> puts # 20 # Clean data pipelines data = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3] data |> sum |> puts # 39 data |> mean |> puts # 3.9 data |> stdev |> puts # 2.375... ``` --- ## Nil-Safe Navigation `&.` Calls a method only if the receiver is not nil. Returns nil otherwise — no crash. ```ruby name = nil puts name&.upcase # nil puts name&.upcase&.length # nil — chain short-circuits user = {name: "Alice"} puts user["name"]&.upcase # ALICE puts user["missing_key"]&.upcase # nil ``` --- ## Range Operators | Operator | Meaning | Example | |---|---|---| | `..` | Inclusive range | `1..5` → 1, 2, 3, 4, 5 | | `...` | Exclusive range | `1...5` → 1, 2, 3, 4 | Used in loops, slices, and `vec()`: ```ruby for i in 1..5 puts i end puts "hello"[1..3] # ell puts vec(1..10) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] puts vec(0...5) # [0, 1, 2, 3, 4] ``` ### First-Class Ranges (v1.17) Ranges are proper values — assign them, print them, and call methods on them: ```ruby r = 1..10 puts r # 1..10 puts r.to_vec # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] puts r.include?(7) # true puts (1..10).step(3) # [1, 4, 7, 10] puts (1..4).sum # 10 puts (1..10).first # 1 puts (1..10).last # 10 puts (1...4).to_vec # [1, 2, 3] (exclusive) ``` `.to_a` is an alias for `.to_vec`. In `case/when`, a range value tests membership: `when 90..100`. --- ## Operator Precedence From highest to lowest: | Level | Operators | |---|---| | Highest | `**` | | | `*` `/` `//` `%` | | | `+` `-` | | | `<` `<=` `>` `>=` | | | `==` `!=` `=~` | | | `and` | | | `or` | | | `\|>` | | Lowest | `\|` (hash merge) | Use parentheses to make intent explicit: ```ruby puts 2 + 3 * 4 # 14 — * before + puts (2 + 3) * 4 # 20 — parentheses first ``` --- # Conditionals ## `if / elsif / else` The basic conditional. The first branch whose condition is truthy runs; the rest are skipped. ```ruby score = 85 if score >= 90 puts "A" elsif score >= 80 puts "B" elsif score >= 70 puts "C" else puts "F" end ``` `elsif` and `else` are optional: ```ruby if logged_in puts "Welcome back!" end ``` --- ## `unless` `unless` is `if not` — runs the block when the condition is **false**. Use it when the negative reads more naturally. ```ruby unless logged_in puts "Please log in." end # Equivalent to: if not logged_in puts "Please log in." end ``` `unless` supports `else` but not `elsif`: ```ruby unless admin puts "Access denied." else puts "Welcome, admin." end ``` --- ## Postfix `if` and `unless` For single-statement conditionals, put the condition at the end. Reads like natural English. ```ruby puts "Adult!" if age >= 18 puts "Minor!" unless age >= 18 x = 0 unless x > 0 log(event) if debug_mode ``` --- ## Inline `if` Expression `if` can produce a value. Assign it, return it, or use it inline. ```ruby grade = if score >= 90 then "A" elsif score >= 80 then "B" else "C" end puts grade # Without 'then' — newline works too label = if x > 0 "positive" elsif x < 0 "negative" else "zero" end puts label # Assign to a variable before using in an expression status = if active then "on" else "off" end puts "System is #{status}" ``` A missing `else` clause evaluates to `nil`: ```ruby title = if admin then "Admin" end puts title # nil if admin is false ``` --- ## `case / when` Match a value against a series of alternatives. Cleaner than a long `if/elsif` chain when testing one variable. ```ruby day = "Monday" case day when "Saturday", "Sunday" puts "Weekend!" when "Monday" puts "Start of the week." when "Friday" puts "Almost there." else puts "Midweek." end ``` Multiple values in a single `when` are separated by commas — any of them triggers the branch. ### Bare `case` — condition-based `case` without a subject works like `if/elsif` but reads more cleanly when all branches test different conditions: ```ruby case when x < 0 puts "negative" when x == 0 puts "zero" when x < 100 puts "small positive" else puts "large positive" end ``` ### `case` with ranges ```ruby case score when 90..100 puts "A" when 80..89 puts "B" when 70..79 puts "C" else puts "F" end ``` Since v1.17, `case/when` tests **membership** for range literals — `when 90..100` matches any value inside the range, not just the range itself. Note that this applies to range *literals* written in the `when` clause; a range stored in a variable is compared with `==` instead. --- ## Ternary-style with Inline `if` Frankie does not have a `? :` ternary operator. Use inline `if` instead: ```ruby # Instead of: label = x > 0 ? "positive" : "non-positive" label = if x > 0 then "positive" else "non-positive" end # Or assign first, then use status = if active then "on" else "off" end puts "System: #{status}" ``` --- ## Truthiness `if`, `while`, `until`, and the inline-`if` expression all follow Python-style truthiness: `false`, `nil`, `0`, `0.0`, `""`, `[]`, and `{}` are all falsy. Everything else is truthy. ```ruby puts(if 0 then "truthy" else "falsy" end) # falsy puts(if "" then "truthy" else "falsy" end) # falsy puts(if [] then "truthy" else "falsy" end) # falsy puts(if nil then "truthy" else "falsy" end) # falsy puts(if false then "truthy" else "falsy" end) # falsy puts(if 5 then "truthy" else "falsy" end) # truthy ``` Note: `then` is only valid in this inline-`if` *expression* form (used where a value is expected, like inside `puts(...)` or an assignment). In statement position, drop `then` and put the body on its own line(s): ```ruby if 0 puts "truthy" else puts "falsy" end # falsy ``` The one exception to this rule is `||=` (nil-coalescing assignment), which follows Ruby-style truthiness instead — only `nil` and `false` trigger the fallback: ```ruby a = 0 a ||= 99 puts a # 0 — kept, because 0 is not nil/false b = nil b ||= 99 puts b # 99 — nil triggers the fallback ``` This means nil checks should always be explicit: ```ruby result = find_user(id) # Wrong — empty vector or 0 would also be treated as "missing" if not result puts "not found" end # Right — test for nil specifically if result == nil puts "not found" end # Or use .nil? if result.nil? puts "not found" end ``` --- ## `Shape pattern matching` ```ruby user = {name: "Alice", role: "admin", active: true} case user when {role: "admin"} puts "Admin: #{user["name"]}" when {role: "moderator"} puts "Moderator: #{user["name"]}" when {active: false} puts "Suspended user" else puts "Regular user: #{user["name"]}" end → Admin: Alice ``` --- ## `Combining Conditions` ```ruby if age >= 18 and active puts "eligible" end if role == "admin" or role == "moderator" puts "elevated access" end if not banned puts "allowed" end # Parentheses for clarity if (score > 50 and attempts < 3) or override puts "access granted" end ``` --- # Loops Frankie has four loop constructs and a rich set of iterator methods. The loop constructs handle index-based and condition-based repetition; the iterators handle collection traversal. --- ## `while` Runs as long as the condition is truthy. ```ruby x = 0 while x < 5 puts x x += 1 end # 0 1 2 3 4 ``` --- ## `until` Runs as long as the condition is **falsy** — the inverse of `while`. ```ruby x = 0 until x == 5 puts x x += 1 end # 0 1 2 3 4 ``` --- ## `do...while` Runs the body **at least once**, then checks the condition. Borrowed from Fortran. ```ruby x = 10 do puts x x += 1 while x < 5 # prints 10 — body ran once even though condition was already false ``` Useful when you need to guarantee at least one execution — user input loops, retry logic: ```ruby do name = input("Enter a positive number: ") n = name.to_i while n <= 0 puts "You entered: #{n}" ``` --- ## `for...in` Iterates over a range or a vector. ```ruby # Over a range for i in 1..5 puts i end # 1 2 3 4 5 # Exclusive range for i in 0...4 puts i end # 0 1 2 3 # Over a vector for item in ["apple", "banana", "cherry"] puts item end # Over a hash — gives [key, value] pairs config = {host: "localhost", port: 5432} config.each do |k, v| puts "#{k}: #{v}" end ``` --- ## `n.times` Repeat a block exactly `n` times. The loop variable counts from `0` to `n-1`. ```ruby 3.times do |i| puts "iteration #{i}" end # iteration 0 # iteration 1 # iteration 2 # Without the variable 5.times do print "* " end # * * * * * ``` The standalone `times(n)` form is identical: ```ruby times(3) do |i| puts i end ``` --- ## Loop Control ### `next` Skip to next iteration Equivalent to `continue` in other languages. ```ruby [1, 2, 3, 4, 5, 6].each do |n| next if n % 2 == 0 puts n end # 1 3 5 ``` ### `break` Exit the loop early ```ruby [1, 2, 3, 4, 5].each do |n| break if n > 3 puts n end # 1 2 3 ``` ### `break` with a value A `break` can carry a value out of the loop: ```ruby result = [1, 2, 3, 4, 5].each do |n| break n * 10 if n == 3 end puts result # 30 ``` ### Postfix forms ```ruby next if condition break if condition ``` --- ## Iterator Methods For collection traversal, iterator methods with blocks are more idiomatic than `for` loops. They compose, chain, and express intent more clearly. ### `.each` — iterate for side effects ```ruby [1, 2, 3].each do |x| puts x * 2 end {name: "Alice", age: 30}.each do |k, v| puts "#{k}: #{v}" end ``` ### `.each_with_index` — iterate with position ```ruby ["a", "b", "c"].each_with_index do |val, i| puts "#{i}: #{val}" end # 0: a # 1: b # 2: c ``` ### `.each_with_object` — iterate with accumulator ```ruby result = [1, 2, 3, 4, 5].each_with_object({}) do |x, h| h[x] = x * x end puts result # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} ``` ### `.each_slice` — iterate in fixed-size chunks ```ruby [1, 2, 3, 4, 5, 6].each_slice(2) do |slice| puts slice end # [1, 2] # [3, 4] # [5, 6] ``` ### `.each_cons` — iterate with sliding window ```ruby [1, 2, 3, 4, 5].each_cons(3) do |window| puts window end # [1, 2, 3] # [2, 3, 4] # [3, 4, 5] ``` ### `.times` — iterate n times (method form) ```ruby 5.times do |i| puts i end ``` --- ## `for` vs Iterators Both work. Iterators are generally preferred for collection traversal because they compose and chain cleanly: ```ruby # for loop for n in [1, 2, 3, 4, 5] puts n if n > 3 end # Iterator — composes with select [1, 2, 3, 4, 5].select do |n| n > 3 end.each do |n| puts n end ``` Use `for` when iterating over a range by index. Use iterators when transforming or filtering a collection. --- ## Infinite Loops A `while true` loop runs forever until `break`: ```ruby count = 0 while true count += 1 break if count >= 5 end puts count # 5 ``` --- ## Nested Loops ```ruby [1, 2, 3].each do |x| [10, 20].each do |y| puts "#{x} × #{y} = #{x * y}" end end # 1 × 10 = 10 # 1 × 20 = 20 # 2 × 10 = 20 # ... # Or use .product for cartesian iteration [1, 2, 3].product([10, 20]).each do |pair| puts "#{pair[0]} × #{pair[1]} = #{pair[0] * pair[1]}" end ``` --- ## Labeled Loops (v1.22) A bare `break` or `next` only ever affects the loop it's directly inside — for a deeply nested search, that usually means booleans and extra checks to unwind more than one level. `while`, `until`, `for`, and `loop` can carry a `:name` label right after the keyword, and `break :name` / `next :name` target that exact loop from anywhere nested inside it, even through other unlabeled loops in between. ```ruby loop :outer do i = 0 loop do i += 1 break :outer if i > 2 puts "inner i=#{i}" end puts "never reached — the labeled break already exited :outer" end puts "after outer loop" # inner i=1 # inner i=2 # after outer loop ``` `next :name` works the same way, jumping straight to the next iteration of the labeled loop instead of just the innermost one: ```ruby i = 0 while :outer i < 3 i += 1 j = 0 while j < 3 j += 1 next :outer if j == 2 puts "i=#{i} j=#{j}" end end # i=1 j=1 # i=2 j=1 # i=3 j=1 ``` `for` takes its label right after `for`, before the loop variable: ```ruby for :outer x in [1, 2, 3] for y in [1, 2, 3] break :outer if x == 2 and y == 2 puts "x=#{x} y=#{y}" end end ``` An unlabeled `break`/`next` between the label and the target loop is transparent — it isn't required to also carry the label, and it doesn't accidentally get caught early. Only a loop can be labeled; plain `break`/`next` inside iterator blocks (`.each`, `.map`, ...) are unaffected. --- # Functions ## Defining a Function Use `def` to define a named function. The last expression is implicitly returned — `return` is optional at the end. ```ruby def add(a, b) a + b end puts add(3, 4) # 7 ``` `return` is still useful for early exits: ```ruby def divide(a, b) return nil if b == 0 a / b end puts divide(10, 2) # 5.0 puts divide(10, 0) # nil ``` --- ## Default Parameters Parameters can have default values. Required parameters must come before optional ones. ```ruby def greet(name, msg = "Hello", punct = "!") puts "#{msg}, #{name}#{punct}" end greet("Alice") # Hello, Alice! greet("Bob", "Hi") # Hi, Bob! greet("Carol", "Hey", ".") # Hey, Carol. ``` --- ## Gradual Type Annotations (v1.19) Annotate parameters and return values with `name: Type` and `-> Type`. Annotations are entirely optional and cost nothing at runtime — they're checked statically, by `frankiec check`, in CI, and live in your editor via the LSP. ```ruby def area(r: Float) -> Float 3.14159 * r * r end def clamp(x: Int, lo: Int, hi: Int) -> Int return lo if x < lo return hi if x > hi x end puts area(3) # fine — Int flows into Float puts area("five") # ✗ area() argument 1 expects Float, got String ``` Un-annotated functions and un-annotated parameters within a partially-annotated function are completely untouched — add types only where they're useful. ### Type names | Canonical | Aliases | |---|---| | `Int` | `Integer` | | `Float` | `Number` | | `String` | `Str` | | `Bool` | `Boolean` | | `Vector` | | | `Hash` | | | `Lambda` | | | `Range` | | | `Nil` | | | `Any` | matches anything | Return annotations are checked against every `return` and the implicit final expression. Simple local inference follows literals, arithmetic, and calls to other annotated functions. ### Coexists with keyword defaults A bare reserved type name in parameter position is an annotation; anything else is still a keyword default — no existing code changes meaning: ```ruby def connect(host: String, port: 5432, ssl: true) # host is annotated String; port and ssl are keyword defaults end ``` Where to catch violations: `frankiec check file.fk` (or a whole project since v1.18: `frankiec check .`), CI via `--strict`, or live as you type via `frankiec lsp`. --- ## Named Arguments Some built-in functions accept named arguments with `key: value` syntax: ```ruby puts paste("2025", "03", "14", sep: "-") # 2025-03-14 puts sprintf("%-10s %d", "Frankie", 1) ``` --- ## Multiple Return Values Return a vector and destructure it at the call site: ```ruby def min_max(v) [min(v), max(v)] end lo, hi = min_max([3, 1, 4, 1, 5, 9]) puts "#{lo}..#{hi}" # 1..9 def stats(v) [mean(v), median(v), stdev(v)] end avg, med, sd = stats([10, 20, 30, 40, 50]) puts avg # 30.0 puts med # 30 ``` --- ## Recursion Functions can call themselves. Frankie supports full recursion. ```ruby def factorial(n) return 1 if n <= 1 n * factorial(n - 1) end puts factorial(10) # 3628800 def fib(n) return n if n <= 1 fib(n - 1) + fib(n - 2) end puts fib(10) # 55 ``` --- ## Lambdas — Functions as Values Use `->` to create an anonymous function that can be stored, passed, and called later. ```ruby double = ->(x) { x * 2 } puts double.call(5) # 10 add = ->(a, b) { a + b } puts add.call(3, 4) # 7 ``` Multi-statement bodies use `do...end`: ```ruby clamp = ->(n, lo, hi) do return lo if n < lo return hi if n > hi n end puts clamp.call(150, 0, 100) # 100 puts clamp.call(-5, 0, 100) # 0 puts clamp.call(42, 0, 100) # 42 ``` Lambdas accept default parameters: ```ruby greet = ->(name, prefix = "Hello") { "#{prefix}, #{name}!" } puts greet.call("Alice") # Hello, Alice! puts greet.call("Bob", "Hi") # Hi, Bob! ``` ### Lambdas as Arguments Pass lambdas to functions for higher-order patterns: ```ruby def apply(fn, val) fn.call(val) end square = ->(x) { x * x } puts apply(square, 6) # 36 # Store in a vector and call each transforms = [ ->(x) { x + 1 }, ->(x) { x * 2 }, ->(x) { x ** 2 } ] transforms.each do |fn| puts fn.call(5) end # 6 # 10 # 25 ``` --- ## Blocks Blocks are anonymous chunks of code passed directly to a method call with `do...end` or `{ }`. They are not stored — they run once as part of the method. ```ruby [1, 2, 3].each do |x| puts x * 2 end result = [1, 2, 3].map do |x| x * x end puts result # [1, 4, 9] ``` Single-line blocks can use braces: ```ruby [1, 2, 3].each do |x| puts x end ``` Blocks are the foundation of Frankie's iterator system — `.map`, `.select`, `.reduce`, `.each_with_object`, and all other iterators take blocks. --- ## The Pipe Operator Chain function calls without nesting: ```ruby data = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3] data |> sum |> puts # 39 data |> mean |> puts # 3.9 def double(x) x * 2 end 10 |> double |> puts # 20 ``` --- ## Scope Variables defined outside a function are readable inside it. Variables assigned inside a function are local to it — they do not affect the outer scope. ```ruby x = 10 def read_outer puts x # 10 — outer x is readable end read_outer() def set_local x = 99 # local to set_local puts x # 99 end set_local() puts x # 10 — outer x unchanged ``` Unlike Ruby, Frankie always requires parentheses to call a function, even with zero arguments. A bare name like `read_outer` (no `()`) is just a reference to the function object, not a call — it silently does nothing as a statement. --- ## Multi-file Programs Split code across files with `require`. Each file is loaded at most once. ```ruby # lib/math_utils.fk def circle_area(r) PI * r * r end # main.fk require "lib/math_utils" puts circle_area(5) # 78.539... ``` `require` resolves paths relative to the current working directory. The `.fk` extension is optional. --- # Error Handling ## `begin / rescue / ensure` Wrap risky code in a `begin` block. If an error is raised, execution jumps to the matching `rescue` clause. `ensure` always runs — whether an error occurred or not. ```ruby begin result = 10 // 0 rescue e puts "Something went wrong: #{e}" ensure puts "This always runs." end ``` `rescue e` without a type catches any error. `ensure` is optional. --- ## Typed Rescue Catch specific error types with typed rescue clauses. Clauses are matched in order — the first matching type wins. ```ruby begin content = file_read("config.json") rescue FileNotFoundError e puts "Config file missing: #{e}" rescue RuntimeError e puts "Runtime error: #{e}" rescue e puts "Unexpected error: #{e}" ensure puts "Done." end ``` Multiple `rescue` clauses let you respond differently to different failure modes — re-raise, recover, log, or substitute a default. Since v1.17 you can also use the Ruby-style `=>` binding — both forms are equivalent: ```ruby rescue FileNotFoundError => e puts "Config file missing: #{e}" ``` --- ## Supported Error Types | Type | When it occurs | |---|---| | `ZeroDivisionError` | Division or modulo by zero | | `FileNotFoundError` | `file_read`, `file_lines`, `file_copy`, `file_rename` on a missing file | | `TypeError` | Wrong type for an operation — e.g. adding Integer and String | | `IndexError` | Vector index out of bounds | | `KeyError` | Hash key not found (when using strict access) | | `ValueError` | Invalid value — e.g. `to_i` on a non-numeric string | | `NameError` | Undefined variable or function | | `AttributeError` | Method or property doesn't exist on the receiver | | `RecursionError` | Stack overflow from too-deep recursion | | `TimeoutError` | Operation timed out (e.g. socket timeouts) — v1.17 | | `RuntimeError` | General runtime error | | `Exception` / `Error` | Catch-all — matches any error | --- ## `raise` Raise an error manually with a message. ```ruby def divide(a, b) raise "Cannot divide by zero" if b == 0 a / b end begin puts divide(10, 0) rescue RuntimeError e puts "Caught: #{e}" # Caught: Cannot divide by zero end ``` `raise` without a type raises a `RuntimeError`. Use it to signal invalid inputs, failed preconditions, or unexpected states. --- ## User-Defined Error Types (v1.17) Declare your own error types with `error`, raise them with `raise TypeName, "message"`, and catch them with Ruby-style binding: ```ruby error TimeoutError error ValidationError def save_user(u) raise ValidationError, "email is required" unless u.has_key?("email") end begin save_user({name: "Blag"}) rescue ValidationError => e puts "Invalid: #{e}" rescue TimeoutError => e puts "Too slow: #{e}" rescue e puts "Something else: #{e}" end ``` Notes: - `raise TypeName("message")` also works. - A typed `raise` auto-declares its type, so simple scripts can skip `error`. - Generic `rescue e` still catches typed errors. - User-defined types take precedence over Python builtins of the same name. - `assert_raises_typed(fn, "ValidationError")` understands user types. - `error` is a contextual keyword — a variable named `error` keeps working. --- ## Rescuing File I/O File operations raise `FileNotFoundError` when the source is missing — making `rescue` the natural pattern for optional files. ```ruby begin config = file_read("config.json") rescue FileNotFoundError e puts "No config found — using defaults." config = "{}" end # file_lines works the same way begin rows = file_lines("data.csv") rescue FileNotFoundError e rows = [] end ``` `file_delete` and `file_exists` do not raise on missing files — they return `false` instead, since those operations are naturally idempotent. --- ## Nested `begin` Blocks `begin` blocks can be nested. Each has its own `rescue` and `ensure`. ```ruby begin begin x = risky_parse(input) rescue ValueError e puts "Parse failed: #{e}" x = default_value end result = process(x) rescue RuntimeError e puts "Processing failed: #{e}" ensure cleanup() end ``` --- ## `ensure` for Cleanup `ensure` is the right place for cleanup that must always happen — closing files, releasing resources, resetting state. ```ruby f = file_open("/tmp/output.txt", "w") begin f.write("result: #{compute()}") rescue e puts "Write failed: #{e}" ensure f.close # always closes, even if an error occurred end ``` --- ## Error Handling in Tests Use `assert_raises` and `assert_raises_typed` in test suites to verify that errors are raised correctly: ```ruby # Assert that any error is raised assert_raises(->() { file_read("/no/such/file.txt") }, "missing file raises an error") # Assert that a specific type is raised assert_raises_typed(->() { x = 1 // 0 }, "ZeroDivisionError", "division by zero raises ZeroDivisionError") assert_raises_typed(->() { file_read("/no/such/file.txt") }, "FileNotFoundError", "missing file raises FileNotFoundError") ``` --- ## Common Patterns ### Provide a default on failure ```ruby def safe_read(path, default = "") begin file_read(path) rescue FileNotFoundError e default end end content = safe_read("config.json", "{}") ``` ### Retry on transient errors Frankie has no `retry` keyword — `begin`/`rescue` cannot re-run its own body. To retry, wrap the `begin`/`rescue` in a loop and use `next` to try again or `break` to stop: ```ruby attempts = 0 retry_limit = 3 result = nil loop do attempts += 1 begin result = http_get("https://api.example.com/data") break rescue RuntimeError e if attempts < retry_limit puts "Attempt #{attempts} failed — retrying..." sleep(1) next else puts "All #{retry_limit} attempts failed: #{e}" break end end end ``` ### Log and continue ```ruby results = [] items.each do |item| begin results.push(process(item)) rescue e puts "Warning: failed to process #{item}: #{e}" end end ``` --- # Modules ## Splitting Code Across Files As programs grow, splitting them across multiple `.fk` files keeps things manageable. Use `require` to load another file. ```ruby require "utils" # loads utils.fk require "lib/helpers" # loads lib/helpers.fk require "lib/math" # loads lib/math.fk ``` The `.fk` extension is optional. Paths are resolved relative to the current working directory. --- ## How `require` Works When you `require` a file, Frankie loads and executes it in the current scope. Everything defined in that file — functions, constants, records — becomes available to the file that required it. ```ruby # lib/math_utils.fk PI = 3.14159265358979 def circle_area(r) PI * r * r end def circle_perimeter(r) 2 * PI * r end ``` ```ruby # main.fk require "lib/math_utils" puts circle_area(5) # 78.539... puts circle_perimeter(5) # 31.415... puts PI # 3.14159265358979 ``` Each file is loaded **at most once** — calling `require` on the same file multiple times has no effect after the first load. --- ## Recommended Project Structure For anything beyond a single script, use `frankiec new` to scaffold a standard layout: ```bash frankiec new myapp ``` This creates: ``` myapp/ ├── main.fk ← entry point ├── test.fk ← test suite ├── lib/ │ └── utils.fk ← reusable functions ├── data/ ← JSON, CSV, SQLite files ├── .env.example ← environment variable template ├── .gitignore └── README.md ``` A typical `main.fk` requiring several modules: ```ruby require "lib/config" require "lib/database" require "lib/routes" require "lib/helpers" db = db_open(env("DB_PATH", ":memory:")) app = web_app() setup_routes(app, db) app.run(3000) ``` --- ## Conventions **One concern per file.** A file should do one thing — math utilities, database helpers, route definitions. Keep files focused and short. **Put reusable code in `lib/`**. Anything that could be used by both `main.fk` and `test.fk` belongs in a lib file. **Load order matters.** If `lib/routes.fk` uses functions from `lib/helpers.fk`, require helpers first: ```ruby require "lib/helpers" # must come first require "lib/routes" # can now use helpers ``` **Constants and records defined in any required file are global.** `require` has no namespaces — keep names descriptive enough to avoid collisions, or use `import` (below) when names start colliding. --- ## Namespaced Imports — `import` (v1.17) `require` merges everything into your scope. For larger programs, `import` loads a file into its **own namespace** instead: ```ruby import "lib/math_utils" as math puts math.circle_area(5) # 78.539... puts math.PI # 3.14159265358979 ``` The alias is optional — `import "lib/math_utils"` defines a module named `math_utils`: ```ruby import "lib/math_utils" puts math_utils.circle_area(5) ``` Notes: - Modules are cached — importing the same file twice returns the same module. - `require` is unchanged and fully supported. Use `require` for quick scripts, `import` when names start colliding. - `import` is a contextual keyword — a variable named `import` keeps working. --- ## Testing Across Files `frankiec test` runs your test suite. A typical `test.fk` requires the same lib files as `main.fk`: ```ruby # test.fk require "lib/math_utils" require "lib/helpers" test "circle_area" do assert_eq(round(circle_area(1), 4), 3.1416, "unit circle area") assert_eq(round(circle_area(0), 2), 0.0, "zero radius") end test "helpers" do assert_eq(clamp(150, 0, 100), 100, "clamp above max") assert_eq(clamp(-5, 0, 100), 0, "clamp below min") end ``` Run it with: ```bash frankiec test test.fk ``` Or just `frankiec test` if your test file is named `test.fk` in the current directory. --- ## Environment Variables `.env` files in the project root are loaded automatically at startup. Use them to keep secrets and configuration out of source code. ```bash # .env DB_PATH=data/app.db API_KEY=your_key_here DEBUG=false ``` ```ruby # main.fk — .env is already loaded db_path = env("DB_PATH", ":memory:") api_key = env("API_KEY") debug = env("DEBUG", "false") puts "Connecting to #{db_path}" ``` `env(key, default)` returns the default if the variable is not set. `env(key)` with no default returns `nil` if missing. --- # Data Types ## `What is a Data Type?` Every value in Frankie has a type. The type determines what the value can do — what methods it responds to, how it behaves in arithmetic, and how it prints. You never declare types explicitly; Frankie figures them out from the values you assign. ```ruby x = 42 # Integer y = 3.14 # Float name = "Alice" # String flag = true # Boolean items = [1,2,3] # Vector empty = nil # Nil ``` --- ## `Primitive vs Composite Types` Frankie types fall into two groups. **Primitive types** hold a single value. They are the atoms of the language — everything else is built from them. | Type | Example | Description | |---|---|---| | `Integer` | `42`, `-7`, `0` | Whole numbers | | `Float` | `3.14`, `-0.5`, `1.0` | Decimal numbers | | `String` | `"hello"` | Text — UTF-8, double-quoted | | `Boolean` | `true`, `false` | Logical values | | `Nil` | `nil` | Absence of a value | **Composite types** hold multiple values or represent a complex object. They are built from primitives and other composites. | Type | Example | Description | |---|---|---| | `Vector` | `[1, "two", 3.0]` | Ordered list of any values | | `Hash` | `{name: "Alice", age: 30}` | Key-value map | | `Lambda` | `->( x) { x * 2 }` | A storable, callable function | | `Record` | `Point(x: 3, y: 4)` | A named data object built on a Hash | There are also **stdlib object types** — `DB`, `DateTime`, `WebApp`, `HTTPResponse`, `File` — returned by specific stdlib functions. They behave like composite types but are not part of the core language. --- ## `How Variables Store Values` Frankie is **dynamically typed** — a variable has no fixed type. It holds whatever value was last assigned to it, and that value's type can change between assignments. ```ruby x = 42 # x is an Integer x = "hello" # x is now a String — perfectly valid x = [1, 2, 3] # x is now a Vector ``` Variables are created on first assignment. There is no declaration step — no `var`, `let`, or `int x`. If you reference a variable before assigning it, you get a runtime error. ```ruby puts mystery # Runtime error: Undefined variable: mystery ``` --- ## `Type Conversion` Frankie does not coerce types silently. Adding an Integer to a String is an error, not a guess. Convert explicitly when you need to cross type boundaries. ```ruby # Explicit conversion puts 42.to_s # "42" — Integer to String puts "42".to_i # 42 — String to Integer puts "3.14".to_f # 3.14 — String to Float puts 3.14.to_i # 3 — Float to Integer (truncates) puts 42.to_f # 42.0 — Integer to Float # Type checking puts is_integer(42) # true puts is_float(3.14) # true puts is_string("hello") # true puts is_vector([1, 2]) # true puts is_nil(nil) # true puts is_bool(false) # true ``` String interpolation converts any value automatically inside `#{}`: ```ruby n = 42 puts "The answer is #{n}" # "42" — no .to_s needed here ``` --- ## `Truthiness and Nil` Frankie has **strict boolean semantics**. Only `false` and `nil` are falsy. Everything else — including `0`, `""`, and `[]` — is truthy. This matches Ruby's model and avoids the silent bugs common in languages that treat `0` as false. ```ruby if 0 puts "0 is truthy in Frankie" # this prints end if "" puts "empty string is truthy" # this prints too end if nil puts "nil is falsy" # this does NOT print end if false puts "false is falsy" # this does NOT print end ``` Check for nil explicitly with `.nil?` or `== nil`: ```ruby x = nil if x == nil puts "x has no value" end if x.nil? puts "same thing, method form" end ``` --- ## `Mutability` In Frankie, **composite types are mutable** — you can change their contents after creation. **Primitive types are effectively immutable** — string methods like `.upcase` return new strings rather than modifying the original. ```ruby # Strings — immutable style (methods return new values) s = "hello" puts s.upcase # "HELLO" puts s # "hello" — unchanged # Vectors — mutable v = [1, 2, 3] v.push(4) puts v # [1, 2, 3, 4] — modified in place v[0] = 99 puts v # [99, 2, 3, 4] — index assignment modifies in place # Hashes — mutable h = {a: 1, b: 2} h["c"] = 3 puts h # {a: 1, b: 2, c: 3} ``` --- ## `Nil Safety` Calling a method on `nil` raises a runtime error. Use the safe navigation operator `&.` to short-circuit instead: ```ruby name = nil puts name.upcase # Runtime error — nil has no .upcase puts name&.upcase # nil — safe, no crash ``` Chains short-circuit at the first nil: ```ruby user = nil puts user&.address&.city # nil — stops at user ``` --- ## `Type Summary` | Type | Primitive / Composite | Mutable | Literal syntax | |---|---|---|---| | `Integer` | Primitive | No | `42`, `-7` | | `Float` | Primitive | No | `3.14`, `1.0` | | `String` | Primitive | No | `"hello"` | | `Boolean` | Primitive | No | `true`, `false` | | `Nil` | Primitive | — | `nil` | | `Vector` | Composite | Yes | `[1, 2, 3]` | | `Hash` | Composite | Yes | `{a: 1}` | | `Lambda` | Composite | No | `->(x) { x * 2 }` | | `Record` | Composite | Yes | `record Point(x, y)` | --- # Integers ## What is an Integer? An Integer is a whole number — positive, negative, or zero — with no decimal point. Integers in Frankie have no fixed size limit; they grow as large as needed without overflow. ```ruby x = 42 y = -7 z = 0 big = 2 ** 64 # 18446744073709551616 — no overflow puts big # 18446744073709551616 ``` --- ## Integer Literals Write integers directly. Negative integers use a leading minus sign. ```ruby count = 100 offset = -32 zero = 0 big = 1000000 budget = 1_250_000 # underscore separators (v1.18) ``` Underscore separators (`1_000_000`) are supported since v1.18 — use them to make large numbers readable. Hexadecimal/binary literals are not supported; use plain decimal. --- ## Arithmetic Operators | Operator | Meaning | Example | Result | |---|---|---|---| | `+` | Addition | `10 + 3` | `13` | | `-` | Subtraction | `10 - 3` | `7` | | `*` | Multiplication | `10 * 3` | `30` | | `/` | Float division | `10 / 3` | `3.333...` | | `//` | Integer division | `10 // 3` | `3` | | `%` | Modulo (remainder) | `10 % 3` | `1` | | `**` | Exponentiation | `2 ** 8` | `256` | `/` always produces a Float. Use `//` (Fortran-style) when you want a truncated Integer result. ```ruby puts 10 / 3 # 3.3333333333333335 — Float puts 10 // 3 # 3 — Integer puts 10 % 3 # 1 — remainder puts 2 ** 10 # 1024 ``` ### Integer Division and Modulo with Negatives `//` truncates toward negative infinity (floor division), consistent with Python: ```ruby puts 7 // 2 # 3 puts (-7) // 2 # -4 (floors toward -∞, not toward zero) puts 7 % 2 # 1 puts (-7) % 2 # 1 (result has the sign of the divisor) ``` --- ## Compound Assignment ```ruby x = 10 x += 3 # x = 13 x -= 2 # x = 11 x *= 4 # x = 44 x //= 5 # x = 8 (integer division assign) x **= 2 # x = 64 x %= 10 # x = 4 puts x # 4 ``` --- ## Comparison Operators Comparisons return a Boolean. ```ruby puts 5 > 3 # true puts 5 < 3 # false puts 5 >= 5 # true puts 5 <= 4 # false puts 5 == 5 # true puts 5 != 3 # true ``` Integers and Floats compare naturally: ```ruby puts 3 == 3.0 # true puts 3 < 3.14 # true ``` --- ## Conversion ```ruby # Integer → Float puts 42.to_f # 42.0 # Integer → String puts 42.to_s # "42" # Integer → Integer (no-op, but valid in generic code) puts 42.to_i # 42 # String → Integer puts "42".to_i # 42 puts "-7".to_i # -7 puts to_int("99") # 99 — standalone function form # Float → Integer (truncates toward zero) puts 3.9.to_i # 3 puts (-3.9).to_i # -3 ``` Non-numeric strings produce a runtime error — there is no silent fallback to zero: ```ruby puts "hello".to_i # Runtime error ``` --- ## Math Functions These standalone functions work on both Integer and Float values: ```ruby puts abs(-42) # 42 — absolute value puts sqrt(144) # 12.0 — square root (always returns Float) puts floor(3.9) # 3 — round down puts ceil(3.1) # 4 — round up puts round(3.5) # 4 — round to nearest puts round(3.14159, 2) # 3.14 — round to n decimal places puts min(3, 7) # 3 puts max(3, 7) # 7 puts clamp(15, 0, 10) # 10 — clamp between lo and hi puts clamp(-5, 0, 10) # 0 ``` --- ## The `times` Loop `n.times do |i|` iterates `n` times, with `i` counting from `0` to `n-1`. This is one of Frankie's most used integer features, borrowed from Ruby. ```ruby 3.times do |i| puts "iteration #{i}" end # iteration 0 # iteration 1 # iteration 2 # Without the loop variable 5.times do print "* " end # * * * * * ``` The standalone `times(n) do |i|` form is identical: ```ruby times(3) do |i| puts i end ``` --- ## Sequences `seq(start, stop, step)` generates a vector of integers (or floats) from `start` to `stop`. ```ruby puts seq(1, 5) # [1, 2, 3, 4, 5] puts seq(0, 10, 2) # [0, 2, 4, 6, 8, 10] puts seq(10, 1, -1) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] puts seq(0, 1, 0.25) # [0, 0.25, 0.5, 0.75, 1.0] ``` `vec(range)` builds a vector from a range literal: ```ruby puts vec(1..10) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] puts vec(1...10) # [1, 2, 3, 4, 5, 6, 7, 8, 9] ``` --- ## Randomness ```ruby # Random integer between a and b inclusive puts rand_int(1, 6) # dice roll — e.g. 4 puts rand_int(0, 100) # 0 to 100 # Repeatable with a seed — a seed reproduces the whole sequence of # calls, not a single fixed value. Each call still returns a different # number; reseeding just replays that same sequence from the start. rand_seed(42) puts rand_int(1, 100) # 82 puts rand_int(1, 100) # 15 puts rand_int(1, 100) # 4 rand_seed(42) puts rand_int(1, 100) # 82 — same sequence, from the top puts rand_int(1, 100) # 15 puts rand_int(1, 100) # 4 ``` --- ## Integers in Vectors Vectors of integers support R-style vectorised arithmetic — `+`, `-`, `/`, `%`, and `**` apply element-wise: ```ruby v = [1, 2, 3, 4, 5] puts v + [10, 10, 10, 10, 10] # [11, 12, 13, 14, 15] puts v ** 2 # [1, 4, 9, 16, 25] ``` `*` is the one exception — on a vector it repeats (Python-list semantics), it does not scale: ```ruby puts v * 2 # [1, 2, 3, 4, 5, 1, 2, 3, 4, 5] — repeated, not scaled ``` To scale every element by a number, use `.map` instead: ```ruby puts v.map do |x| x * 2 end # [2, 4, 6, 8, 10] ``` ```ruby # Statistical functions on integer vectors puts sum(v) # 15 puts mean(v) # 3.0 puts min(v) # 1 puts max(v) # 5 puts median(v) # 3 puts stdev(v) # 1.5811... ``` --- ## Type Checking ```ruby puts is_integer(42) # true puts is_integer(3.14) # false puts is_integer("42") # false ``` --- ## Quick Reference | Category | Operation | Example | Result | |---|---|---|---| | Arithmetic | `+` `-` `*` | `10 + 3` | `13` | | Float division | `/` | `10 / 3` | `3.333...` | | Integer division | `//` | `10 // 3` | `3` | | Modulo | `%` | `10 % 3` | `1` | | Exponentiation | `**` | `2 ** 8` | `256` | | Comparison | `==` `!=` `<` `>` `<=` `>=` | `5 > 3` | `true` | | Compound assign | `+=` `-=` `*=` `//=` `**=` `%=` | `x += 1` | — | | Convert to Float | `.to_f` | `42.to_f` | `42.0` | | Convert to String | `.to_s` | `42.to_s` | `"42"` | | Absolute value | `abs(n)` | `abs(-7)` | `7` | | Square root | `sqrt(n)` | `sqrt(144)` | `12.0` | | Rounding | `floor` `ceil` `round` | `floor(3.9)` | `3` | | Clamp | `clamp(n, lo, hi)` | `clamp(15, 0, 10)` | `10` | | Loop n times | `n.times do \|i\|` | `3.times do \|i\|` | — | | Sequence | `seq(start, stop, step)` | `seq(1, 5)` | `[1,2,3,4,5]` | | Random | `rand_int(a, b)` | `rand_int(1, 6)` | `1`–`6` | | Type check | `is_integer(x)` | `is_integer(42)` | `true` | --- # Float A Float is a decimal number — any value with a fractional part, or a number produced by float division. Frankie uses IEEE 754 double-precision, the same standard as Python, Ruby, and R. ```ruby x = 3.14 y = -0.5 z = 1.0 # explicitly Float, not Integer e = 2.71828 ``` ## `Float Literals` ```ruby 3.14 # standard decimal -0.5 # negative 1.0 # integer value, Float type 1.0e6 # scientific notation — 1000000.0 (v1.18) 2.5e-3 # 0.0025 3.141_592 # underscore separators (v1.18) ``` Scientific notation (`1e6`, `2.5e-3`, `1E+9`) and underscore separators (`3.141_592`) are supported since v1.18. ## `Arithmetic` All standard operators work on Floats. Mixing Integer and Float produces a Float: ```ruby puts 3.14 + 1.0 # 4.140000000000001 (float precision) puts 3.14 * 2 # 6.28 puts 10.0 / 3 # 3.3333333333333335 puts 2.0 ** 8 # 256.0 # Integer / Integer always returns Float puts 10 / 4 # 2.5 puts 10 // 4 # 2 — use // for integer result ``` ## `Floating-point Precision` Floats cannot represent all decimal values exactly. This is standard IEEE 754 behaviour, not a Frankie quirk: ```ruby puts 0.1 + 0.2 # 0.30000000000000004 puts round(0.1 + 0.2, 2) # 0.3 — round when displaying ``` When comparing floats, compare within a tolerance or round first: ```ruby a = 0.1 + 0.2 b = 0.3 puts a == b # false — unsafe puts abs(a - b) < 0.0001 # true — safe comparison puts round(a, 10) == round(b, 10) # true — round then compare ``` ## `Math Functions` ```ruby puts abs(-3.14) # 3.14 puts sqrt(2.0) # 1.4142135623730951 puts floor(3.7) # 3 puts ceil(3.2) # 4 puts round(3.567, 2) # 3.57 puts round(3.567) # 4.0 (rounds to nearest, but still returns a Float) puts clamp(1.5, 0.0, 1.0) # 1.0 ``` `sqrt` always returns a Float. `floor` and `ceil` return an Integer. `round(x)`, even with no decimal argument, always returns a Float. ## `Conversion` ```ruby puts 3.14.to_i # 3 — truncates toward zero puts (-3.9).to_i # -3 — truncates toward zero (not floor) puts 3.14.to_s # "3.14" puts 3.14.to_f # 3.14 — no-op, already a Float puts "3.14".to_f # 3.14 puts 42.to_f # 42.0 ``` ## `Type Checking` ```ruby puts is_float(3.14) # true puts is_float(3) # false — Integer, not Float puts is_float("3.14") # false ``` --- # Boolean & Nil ## Boolean A Boolean is either `true` or `false`. Booleans are produced by comparisons, logical operators, and predicate methods (`.empty?`, `.nil?`, `is_integer()`, etc.). ```ruby flag = true missing = false puts 5 > 3 # true puts 5 < 3 # false puts 5 == 5 # true puts 5 != 3 # true ``` ### `Logical Operators` ```ruby puts true and false # false — both must be true puts true or false # true — at least one must be true puts not true # false — negation # Short-circuit evaluation # 'and' stops at the first false # 'or' stops at the first true puts false and risky() # false — risky() never called puts true or risky() # true — risky() never called ``` ### `Truthiness` `if`, `while`, `until`, and the inline-`if` expression follow Python-style truthiness: `false`, `nil`, `0`, `0.0`, `""`, `[]`, and `{}` are all falsy. Everything else is truthy. ```ruby puts(if 0 then "truthy" else "falsy" end) # falsy puts(if "" then "truthy" else "falsy" end) # falsy puts(if [] then "truthy" else "falsy" end) # falsy puts(if false then "truthy" else "falsy" end) # falsy puts(if nil then "truthy" else "falsy" end) # falsy ``` The one exception is `||=` (nil-coalescing assignment), which uses Ruby's model instead — only `nil` and `false` trigger the fallback, so `0`, `""`, and `[]` are kept as-is: ```ruby a = 0 a ||= 99 puts a # 0 — kept, not nil/false b = nil b ||= 99 puts b # 99 — nil triggers the fallback ``` ### `Boolean Comparison` ```ruby puts true == true # true puts true == false # false puts true != false # true # Booleans are not numbers — no arithmetic # puts true + 1 # Runtime error ``` ### `Type Checking` ```ruby puts is_bool(true) # true puts is_bool(false) # true puts is_bool(0) # false puts is_bool("true") # false ``` ### `Common Patterns` ```ruby # Guard clause with boolean def process(data) return nil if data == nil return nil if data.empty? data.map do |x| x * 2 end end # Store result of a condition valid = age >= 18 and not banned puts "Access: #{if valid then "granted" else "denied" end}" # Predicate methods return booleans puts "".empty? # true puts [1, 2].empty? # false puts "hello".include?("ell") # true puts is_integer(42) # true ``` --- ## Nil `nil` represents the absence of a value. It is Frankie's equivalent of `null`, `None`, or `undefined` in other languages. There is exactly one `nil` — every `nil` is the same value. ```ruby missing = nil puts missing # nil puts missing == nil # true ``` ### `When Nil Appears` ```ruby # Unset hash keys h = {name: "Alice"} puts h["age"] # nil — key doesn't exist # Out-of-range vector access v = [1, 2, 3] puts v[10] # nil # Missing function results def find_user(id) return nil if id == 0 {id: id, name: "User#{id}"} end puts find_user(0) # nil # Short-circuit of &. chain puts nil&.upcase # nil ``` ### `Checking for Nil` ```ruby x = nil # Three equivalent ways puts x == nil # true puts x != nil # false puts x.nil? # true — method form puts is_nil(x) # true — function form ``` Avoid testing `if not x` to check for nil — it also catches `false`: ```ruby x = false if not x # catches both nil AND false puts "this runs" end if x == nil # only catches nil puts "this does not run" end ``` ### `Nil Safety with `&.`` The safe navigation operator `&.` short-circuits on nil, returning nil instead of crashing: ```ruby name = nil puts name.upcase # Runtime error puts name&.upcase # nil — safe # Chain — stops at the first nil user = nil puts user&.name&.upcase&.length # nil # Useful when a value might or might not be present config = {db: {host: "localhost"}} puts config.dig("db", "host")&.upcase # LOCALHOST puts config.dig("db", "port")&.to_s # nil ``` ### `Nil in Collections` ```ruby v = [1, nil, 2, nil, 3] puts v.compact # [1, 2, 3] — removes all nils # nil propagates in arithmetic — raises an error # puts nil + 1 # TypeError # Nil-safe default pattern value = get_value() || 0 # note: || is not in Frankie # Instead use: raw = get_value() value = if raw == nil then 0 else raw end ``` ### `Conversion` ```ruby puts nil.to_s # "" — nil becomes empty string puts nil.to_a # [] — nil becomes empty vector (via stdlib) ``` ### `Type Checking` ```ruby puts is_nil(nil) # true puts is_nil(false) # false — false is not nil puts is_nil(0) # false puts is_nil("") # false ``` --- # Strings ## `What is a String?` A string is a sequence of UTF-8 characters. Strings are used for text — output, input, file content, keys, messages, templates. In Frankie, strings are **immutable** — every method that transforms a string returns a new string rather than modifying the original. ```ruby s = "Hello, Frankie!" puts s.upcase # "HELLO, FRANKIE!" puts s # "Hello, Frankie!" — unchanged ``` --- ## `String Literals` The standard form is a double-quoted string: ```ruby name = "Alice" ``` Single-quoted strings are also valid but do **not** support interpolation or escape sequences: ```ruby puts 'Hello, #{name}' → Hello, #{name} — literal, not interpolated ``` ## `Triple-quoted strings` Span multiple lines: ```ruby message = """ Hello, Alice! Welcome to Frankie. """ puts message ``` `Heredocs` (<<~DELIM) are the cleanest way to write multi-line strings in code. The `~` variant strips common leading indentation automatically: ```ruby query = <<~SQL SELECT name, age FROM employees WHERE age > 30 ORDER BY name SQL puts query ``` Heredocs support `#{}` interpolation just like regular strings: ```ruby table = "employees" limit = 10 query = <<~SQL SELECT * FROM #{table} LIMIT #{limit} SQL ``` --- ## `String Interpolation` Double-quoted strings support `#{}` to embed any expression directly: ```ruby name = "Alice" score = 95 puts "Hello, #{name}!" → Hello, Alice! puts "Score: #{score}" → Score: 95 puts "Double: #{score * 2}" → Double: 190 puts "Upper: #{name.upcase}" → Upper: ALICE puts "Pi ≈ #{round(3.14159, 2)}" → Pi ≈ 3.14 ``` Any valid Frankie expression works inside `#{}`. The result is automatically converted to a string. --- ## `Escape Sequences` Inside double-quoted strings: | Sequence | Meaning | |---|---| | `\n` | Newline | | `\t` | Tab | | `\\` | Literal backslash | | `\"` | Literal double quote | ```ruby puts "line one\nline two" puts "column\tone\ttwo" puts "She said \"hello\"" ``` --- ## `String Operators` ```ruby # Concatenation puts "Hello, " + "Frankie!" # Hello, Frankie! # Repetition puts "ha" * 3 → hahaha puts "-" * 40 → ──────────────────────────────────────── # Comparison puts "apple" == "apple" → true puts "apple" != "banana" → true puts "apple" < "banana" → true (lexicographic) # Match operator — returns position of first match or nil puts "frank123" =~ "\\d+" → 5 puts "no digits" =~ "\\d+" → nil ``` --- ## `Accessing Characters and Slices` Strings are 0-indexed. Negative indices count from the end. ```ruby s = "Frankie" puts s[0] → F puts s[1] → r puts s[-1] → e (last character) puts s[-3] → i # Inclusive range slice puts s[0..4] → Frank # Exclusive range slice (up to but not including index 5) puts s[0...4] → Fran # Last N characters puts s[-3..-1] → kie ``` --- ## `Nil Safety with Strings` Calling a method on `nil` raises a runtime error. Use `&.` to return nil safely instead: ```ruby name = nil puts name.upcase # Runtime error puts name&.upcase # nil — safe # Useful when a value might or might not be present user_input = nil puts user_input&.strip&.downcase # nil — whole chain short-circuits ``` --- ## `Quick Reference` | Category | Methods / Functions | |---|---| | Case | `.upcase` `.downcase` | | Whitespace | `.strip` `.lstrip` `.rstrip` `.chomp` `.chop` | | Inspection | `.length` `.empty?` `.include?` `.start_with?` `.end_with?` `.count` | | Search | `.match` `.match_all` `.matches?` `=~` | | Transform | `.replace` `.sub` `.gsub` `.gsub do` `.delete` `.squeeze` `.tr` `.reverse` | | Align | `.center` `.ljust` `.rjust` | | Split | `.split` `.lines` `.chars` `.bytes` | | Iterate | `.each_char` `.each_line` | | Convert | `.to_i` `.to_f` `.to_s` `.ord` `.encode` `.decode` | | Format | `template()` `.format()` `sprintf()` `paste()` | | Slice | `[i]` `[a..b]` `[a...b]` | | Operators | `+` `*` `==` `!=` `<` `>` `=~` | --- # Vector ## `What is a Vector?` A Vector is an ordered, 0-indexed list of values. Vectors can hold any mix of types — integers, strings, booleans, other vectors, hashes. They are Frankie's most-used composite type and the foundation of the R-inspired statistical functions. ```ruby numbers = [1, 2, 3, 4, 5] mixed = [42, "hello", true, nil, 3.14] empty = [] nested = [[1, 2], [3, 4], [5, 6]] ``` Vectors are **mutable** — their contents can be changed after creation. --- ## `Creating Vectors` ```ruby # Literal v = [10, 20, 30] # From a range v = vec(1..10) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] v = vec(0...5) # [0, 1, 2, 3, 4] # From seq() v = seq(0, 10, 2) # [0, 2, 4, 6, 8, 10] v = seq(1.0, 2.0, 0.25) # [1.0, 1.25, 1.5, 1.75, 2.0] # Repetition v = [0] * 5 # [0, 0, 0, 0, 0] v = [1, 2] * 3 # [1, 2, 1, 2, 1, 2] ``` --- ## Accessing Elements Vectors are 0-indexed. Negative indices count from the end. ```ruby v = [10, 20, 30, 40, 50] puts v[0] # 10 — first puts v[2] # 30 puts v[-1] # 50 — last puts v[-2] # 40 # Out of range returns nil puts v[99] # nil ``` ### `Slicing` ```ruby v = [10, 20, 30, 40, 50] puts v[1..3] # [20, 30, 40] — inclusive puts v[1...3] # [20, 30] — exclusive puts v[-3..-1] # [30, 40, 50] — last three puts v[0..1] # [10, 20] — first two ``` ### `Assignment` ```ruby v = [1, 2, 3, 4, 5] v[0] = 99 puts v # [99, 2, 3, 4, 5] v[-1] = 0 puts v # [99, 2, 3, 4, 0] ``` --- ## Basic Operations ```ruby v = [1, 2, 3, 4, 5] puts v.length # 5 puts v.first # 1 puts v.last # 5 puts v.empty? # false puts [].empty? # true puts v.include?(3) # true puts v.include?(9) # false ``` ### `Adding and Removing Elements` ```ruby v = [1, 2, 3] v.push(4) # append — v is now [1, 2, 3, 4] v.pop() # remove last — returns 4, v is now [1, 2, 3] v.delete(2) # remove by value — v is now [1, 3] puts v # [1, 3] ``` --- ## `Vectorised Arithmetic` Operations on vectors apply element-wise — R does this natively, and it's the same whole-array math FORTRAN 90+ pioneered decades earlier: ```ruby v = [1, 2, 3, 4, 5] puts v + [10, 10, 10, 10, 10] # [11, 12, 13, 14, 15] puts v ** 2 # [1, 4, 9, 16, 25] ``` `*` is the one exception — it repeats the vector (Python-list semantics), not element-wise scaling: ```ruby puts v * 2 # [1, 2, 3, 4, 5, 1, 2, 3, 4, 5] — repeated, not scaled ``` Vectors of different lengths raise a runtime error for arithmetic. For pairing, use `.zip` instead. A matrix is just a vector of vectors — since v1.22, arithmetic recurses through nested vectors too, so `[[1,2],[3,4]] + [[5,6],[7,8]]` is genuinely element-wise. See [Matrix Math](../standard_library/math_statistics.md#matrix-math-v122) for `matrix_new`, `matrix_multiply`, and friends. --- ## `Statistical Functions` ```ruby data = [23, 45, 12, 67, 34, 89, 56] puts sum(data) # 326 puts mean(data) # 46.57... puts median(data) # 45 puts min(data) # 12 puts max(data) # 89 puts stdev(data) # 24.9... puts variance(data) # 621.6... ``` Also as methods: ```ruby puts data.sum # 326 puts data.min # 12 puts data.max # 89 puts data.mean # 46.57... ``` --- ## `Sorting and Ordering` ```ruby v = [3, 1, 4, 1, 5, 9, 2, 6] puts v.sort # [1, 1, 2, 3, 4, 5, 6, 9] puts v.reverse # [6, 2, 9, 5, 1, 4, 1, 3] puts v.uniq # [3, 1, 4, 5, 9, 2, 6] — deduped # Sort by computed key words = ["banana", "fig", "apple", "cherry"] puts words.sort_by do |w| w.length end # [fig, apple, banana, cherry] puts words.sort_by do |w| w end # [apple, banana, cherry, fig] # Min/max by key puts words.min_by do |w| w.length end # fig puts words.max_by do |w| w.length end # banana ``` --- ## `Transformation` ```ruby v = [1, 2, 3, 4, 5] # map — transform each element puts v.map do |x| x * x end # [1, 4, 9, 16, 25] puts v.map do |x| x.to_s end # ["1", "2", "3", "4", "5"] # select / reject — filter puts v.select do |x| x > 3 end # [4, 5] puts v.reject do |x| x > 3 end # [1, 2, 3] # reduce — fold into a single value puts v.reduce(0) do |acc, x| acc + x end # 15 puts v.reduce(1) do |acc, x| acc * x end # 120 # flat_map — map then flatten one level puts [[1,2],[3,4]].flat_map do |sub| sub end # [1, 2, 3, 4] puts ["hi","bye"].flat_map do |w| w.chars end # [h,i,b,y,e] # map_with_index — element and position together puts v.map_with_index do |x, i| "#{i}:#{x}" end # ["0:1", "1:2", "2:3", "3:4", "4:5"] ``` --- ## `Searching` ```ruby v = [1, 2, 3, 4, 5, 6] # find — first matching element puts v.find do |x| x > 4 end # 5 # any? / all? / none? puts v.any? do |x| x > 5 end # true puts v.all? do |x| x > 0 end # true puts v.none? do |x| x > 9 end # true # count — with a block puts v.count do |x| x.even? end # error — .even? not available puts v.count do |x| x % 2 == 0 end # 3 ``` --- ## `Grouping and Bucketing` ```ruby v = [1, 2, 3, 4, 5, 6] # tally — count occurrences puts ["a","b","a","c","b","a"].tally # {a: 3, b: 2, c: 1} # group_by — bucket by key by_parity = v.group_by do |x| if x % 2 == 0 then "even" else "odd" end end puts by_parity["even"] # [2, 4, 6] puts by_parity["odd"] # [1, 3, 5] # chunk — fixed-size sub-vectors puts v.chunk(2) # [[1,2],[3,4],[5,6]] ``` --- ## `Iteration with State` ```ruby # each_with_object — shared accumulator freq = ["a","b","a","c","b","a"].each_with_object({}) do |x, h| cur = h[x] h[x] = (if cur == nil then 0 else cur end) + 1 end puts freq # {a: 3, b: 2, c: 1} # each_with_index ["x", "y", "z"].each_with_index do |val, i| puts "#{i}: #{val}" end # each_slice — non-overlapping windows [1,2,3,4,5,6].each_slice(2) do |s| puts s end # [1, 2] [3, 4] [5, 6] # each_cons — sliding window [1,2,3,4,5].each_cons(3) do |w| puts w end # [1,2,3] [2,3,4] [3,4,5] ``` --- ## `Combining Vectors` ```ruby a = [1, 2, 3] b = [4, 5, 6] # zip — pair elements puts a.zip(b) # [[1,4],[2,5],[3,6]] # zip_with — pair and transform puts a.zip_with(b) do |x, y| x + y end # [5, 7, 9] # product — cartesian product puts [1,2].product([3,4]) # [[1,3],[1,4],[2,3],[2,4]] # flatten — deep flatten puts [[1,[2]],[3,[4,5]]].flatten # [1, 2, 3, 4, 5] puts [[1,[2]],[3,[4,5]]].flatten(1) # [1, [2], 3, [4, 5]] # compact — remove nils puts [1, nil, 2, nil, 3].compact # [1, 2, 3] # unzip — split pairs back into two vectors puts unzip([[1,"a"],[2,"b"],[3,"c"]]) # [[1,2,3],["a","b","c"]] ``` --- ## `The Pipe Operator` Vectors work naturally with `|>`: ```ruby data = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3] data |> sum |> puts # 39 data |> mean |> puts # 3.9 data |> min |> puts # 1 data |> max |> puts # 9 ``` --- ## `Quick Reference` | Category | Method / Function | |---|---| | Access | `[i]` `[a..b]` `.first` `.last` `.take(n)` `.drop(n)` `.dig(...)` | | Inspect | `.length` `.empty?` `.include?(x)` `.count` `.tally` | | Mutate | `.push(x)` `.pop()` `.delete(x)` `[i]=` | | Transform | `.map` `.flat_map` `.map_with_index` `.reverse` `.flatten` `.compact` | | Filter | `.select` `.reject` `.find` `.uniq` | | Aggregate | `.reduce` `.each_with_object` `.sum` `.min` `.max` `.mean` | | Test | `.any?` `.all?` `.none?` `.count do` | | Sort | `.sort` `.sort_by` `.min_by` `.max_by` `.reverse` | | Group | `.group_by` `.chunk` `.each_slice` `.each_cons` | | Combine | `.zip` `.zip_with` `.product` `.flatten` `unzip()` | | Stats | `sum()` `mean()` `median()` `stdev()` `variance()` `min()` `max()` | | Create | `vec(range)` `seq(start, stop, step)` `[x] * n` | --- # Hash ## What is a Hash? A Hash is an ordered collection of key-value pairs. Keys map to values — you look up a value by its key. Hashes are Frankie's dictionary type, modelled after Python's `dict` but with Ruby's `do...end` iteration syntax. ```ruby person = {name: "Alice", age: 30, active: true} config = {host: "localhost", port: 5432, db: "app"} empty = {} ``` Hashes are **mutable** — you can add, change, and remove keys after creation. --- ## Creating Hashes ### `Symbol Keys (most common)` ```ruby user = {name: "Alice", age: 30} ``` Symbol keys are written without quotes — `name:` is the key, `"Alice"` is the value. ### `String Keys` When keys come from external data (JSON, user input, database results), they are string keys: ```ruby row = {"name" => "Alice", "age" => 30} ``` In practice, both forms work interchangeably for access — Frankie normalises keys internally. ### `Nested Hashes` ```ruby config = { database: { host: "localhost", port: 5432, credentials: {user: "admin", pass: "secret"} }, cache: {ttl: 300} } ``` --- ## Accessing Values ```ruby h = {name: "Alice", age: 30} puts h["name"] # Alice puts h["age"] # 30 # Missing key returns nil — no crash puts h["missing"] # nil ``` ### `Safe Nested Access with .dig` ```ruby config = {database: {host: "localhost", port: 5432}} puts config.dig("database", "host") # localhost puts config.dig("database", "port") # 5432 puts config.dig("database", "missing") # nil — no crash puts config.dig("nope", "also_nope") # nil — no crash ``` `.dig` works through any combination of hashes and vectors: ```ruby data = {users: [{name: "Alice", score: 95}, {name: "Bob", score: 87}]} puts data.dig("users", 0, "name") # Alice puts data.dig("users", 1, "score") # 87 puts data.dig("users", 5, "name") # nil ``` ### `Fetch with Default` ```ruby h = {name: "Alice"} puts h.fetch("name", "unknown") # Alice puts h.fetch("age", 0) # 0 — key missing, returns default ``` --- ## Modifying Hashes ```ruby h = {a: 1, b: 2} # Add or update a key h["c"] = 3 h["a"] = 99 puts h # {a: 99, b: 2, c: 3} # Remove a key h.delete("b") puts h # {a: 99, c: 3} # Merge — returns new hash, right wins on conflict puts {a: 1, b: 2} | {b: 3, c: 4} # {a: 1, b: 3, c: 4} # Merge in place h.merge_bang({d: 5, a: 0}) puts h # {a: 0, c: 3, d: 5} ``` --- ## Hash destructuring ```ruby user = {name: "Alice", age: 30, role: "admin"} {name, age} = user puts name → Alice puts age → 30 ``` --- ## Inspecting Hashes ```ruby h = {name: "Alice", age: 30, active: true} puts h.keys # [name, age, active] puts h.values # [Alice, 30, true] puts h.size # 3 puts h.has_key?("name") # true puts h.has_key?("missing") # false ``` --- ## Iterating ### `.each — key and value` ```ruby {name: "Alice", age: 30}.each do |k, v| puts "#{k}: #{v}" end # name: Alice # age: 30 ``` ### `.each_pair — identical to .each` ```ruby config.each_pair do |key, val| puts "#{key} = #{val}" end ``` ### `.map — transform to a vector` `.map` on a hash yields `[key, value]` pairs as a vector of vectors: ```ruby pairs = {a: 1, b: 2, c: 3}.map do |k, v| "#{k}=#{v}" end puts pairs # ["a=1", "b=2", "c=3"] ``` ### `.map_hash — transform to a new hash` ```ruby prices = {apple: 1.20, banana: 0.50, cherry: 3.00} doubled = prices.map_hash do |k, v| [k, v * 2] end puts doubled # {apple: 2.4, banana: 1.0, cherry: 6.0} # Upcase all keys upper = {a: 1, b: 2}.map_hash do |k, v| [k.to_s.upcase, v] end puts upper # {"A": 1, "B": 2} ``` ### `.select / .reject — filter pairs` ```ruby scores = {alice: 95, bob: 72, carol: 88, dave: 61} passing = scores.select do |k, v| v >= 80 end puts passing # {alice: 95, carol: 88} failing = scores.reject do |k, v| v >= 80 end puts failing # {bob: 72, dave: 61} ``` --- ## `Converting` ```ruby h = {x: 1, y: 2, z: 3} # To a vector of [key, value] pairs puts h.to_a # [["x", 1], ["y", 2], ["z", 3]] # Build a hash from a vector using each_with_object squares = [1,2,3,4,5].each_with_object({}) do |n, h| h[n] = n * n end puts squares # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} ``` --- ## `The | Merge Operator` Merges two hashes. Right-hand keys win on conflict. Chains naturally. ```ruby defaults = {color: "blue", size: "md", weight: "normal"} custom = {color: "red", size: "lg"} result = defaults | custom puts result # {color: red, size: lg, weight: normal} # Layered config base = {debug: false, log: "info", timeout: 30} env = {log: "debug"} local = {timeout: 5} config = base | env | local puts config # {debug: false, log: debug, timeout: 5} ``` --- ## `Nested Access Patterns` ```ruby # Safe navigation with &. h = {user: {name: "Alice"}} puts h["user"]&.[]("name") # Alice — awkward # Better: use .dig puts h.dig("user", "name") # Alice — clean # Deep default pattern def get_config(h, *keys) result = h.dig(*keys) if result == nil then "default" else result end end puts get_config(h, "user", "name") # Alice puts get_config(h, "user", "age") # default ``` --- ## `Common Patterns` ```ruby # Frequency count words = ["apple", "banana", "apple", "cherry", "banana", "apple"] freq = words.each_with_object({}) do |w, h| cur = h[w] h[w] = (if cur == nil then 0 else cur end) + 1 end puts freq # {apple: 3, banana: 2, cherry: 1} # Index by field people = [ {name: "Alice", id: 1}, {name: "Bob", id: 2}, {name: "Carol", id: 3} ] by_id = people.each_with_object({}) do |person, h| h[person["id"]] = person["name"] end puts by_id[2] # Bob # Invert a hash original = {a: 1, b: 2, c: 3} inverted = original.map_hash do |k, v| [v, k.to_s] end puts inverted # {1: "a", 2: "b", 3: "c"} ``` --- ## `Quick Reference` | Category | Method / Operation | |---|---| | Access | `h[key]` `.dig(k1, k2, ...)` `.fetch(key, default)` | | Inspect | `.keys` `.values` `.size` `.has_key?(k)` | | Mutate | `h[key]=` `.delete(key)` `.merge_bang(other)` | | Merge | `h1 \| h2` `.merge(other)` | | Iterate | `.each do \|k,v\|` `.each_pair do \|k,v\|` | | Transform | `.map do \|k,v\|` `.map_hash do \|k,v\|` | | Filter | `.select do \|k,v\|` `.reject do \|k,v\|` | | Convert | `.to_a` `.keys` `.values` | --- # Lambda ## `What is a Lambda?` A Lambda is an anonymous function stored as a value. Unlike a `def` function which is declared and called by name, a lambda can be assigned to a variable, stored in a vector or hash, and passed to other functions. Lambdas bring first-class function behaviour to Frankie. ```ruby double = ->(x) { x * 2 } puts double.call(5) # 10 ``` --- ## Creating Lambdas ### `Single-expression body — braces { }` ```ruby double = ->(x) { x * 2 } add = ->(a, b) { a + b } greet = ->(name) { "Hello, #{name}!" } square = ->(x) { x * x } is_even = ->(x) { x % 2 == 0 } ``` ### `Multi-statement body — do...end` ```ruby clamp = ->(n, lo, hi) do return lo if n < lo return hi if n > hi n end describe = ->(v) do avg = mean(v) sd = stdev(v) "mean=#{round(avg,2)}, stdev=#{round(sd,2)}" end ``` ### `No parameters` ```ruby timestamp = ->() { now().format("%H:%M:%S") } puts timestamp.call # 14:23:07 ``` ### `Default parameters` ```ruby greet = ->(name, prefix = "Hello") { "#{prefix}, #{name}!" } puts greet.call("Alice") # Hello, Alice! puts greet.call("Bob", "Hi") # Hi, Bob! ``` --- ## Calling a Lambda Use `.call(args)`: ```ruby add = ->(a, b) { a + b } puts add.call(3, 4) # 7 puts add.call(10, 20) # 30 ``` --- ## Lambdas as Values Because lambdas are values, they can be stored and passed anywhere a value can go. ### `Stored in a variable` ```ruby transform = ->(x) { x * 3 + 1 } puts transform.call(5) # 16 ``` ### `Stored in a vector` ```ruby pipeline = [ ->(x) { x + 1 }, ->(x) { x * 2 }, ->(x) { x ** 2 } ] pipeline.each do |fn| puts fn.call(5) end # 6 # 10 # 25 ``` ### `Stored in a hash` ```ruby ops = { add: ->(a, b) { a + b }, subtract: ->(a, b) { a - b }, multiply: ->(a, b) { a * b } } puts ops["add"].call(10, 3) # 13 puts ops["subtract"].call(10, 3) # 7 puts ops["multiply"].call(10, 3) # 30 ``` ### `Passed to a function` ```ruby def apply(fn, value) fn.call(value) end square = ->(x) { x * x } puts apply(square, 7) # 49 def apply_all(fns, value) fns.reduce(value) do |acc, fn| fn.call(acc) end end steps = [->(x) { x + 1 }, ->(x) { x * 3 }, ->(x) { x - 2 }] puts apply_all(steps, 4) # (4+1)*3-2 = 13 ``` --- ## Lambdas vs `def` Functions | | `def` | Lambda | |---|---|---| | Has a name | Yes | No (stored in a variable) | | Storable as value | No | Yes | | Passable to functions | No | Yes | | Default parameters | Yes | Yes | | Multi-statement body | Yes | Yes (`do...end`) | | Implicit return | Yes | Yes | | Explicit `return` | Yes | Yes | | Recursion | Yes | Via the variable name | Use `def` for named, reusable functions. Use lambdas when you need to pass behaviour as data. --- ## Higher-order Patterns Lambdas enable higher-order programming — functions that operate on other functions. ### `Map with a lambda` ```ruby double = ->(x) { x * 2 } result = [1, 2, 3, 4, 5].map do |x| double.call(x) end puts result # [2, 4, 6, 8, 10] ``` ### `Function composition` ```ruby def compose(f, g) ->(x) { f.call(g.call(x)) } end add1 = ->(x) { x + 1 } double = ->(x) { x * 2 } add1_then_double = compose(double, add1) puts add1_then_double.call(5) # (5+1)*2 = 12 double_then_add1 = compose(add1, double) puts double_then_add1.call(5) # (5*2)+1 = 11 ``` ### `Memoisation` ```ruby def memoize(fn) cache = {} ->(x) do if cache[x] == nil cache[x] = fn.call(x) end cache[x] end end slow_square = ->(x) do sleep(0.001) # simulate slow computation x * x end fast_square = memoize(slow_square) puts fast_square.call(10) # computed puts fast_square.call(10) # cached — instant ``` ### `Strategy pattern` ```ruby def sort_by_strategy(items, strategy) items.sort_by do |item| strategy.call(item) end end words = ["banana", "fig", "apple", "cherry", "kiwi"] by_length = ->(w) { w.length } by_alpha = ->(w) { w } by_reverse = ->(w) { w.chars.reverse.join("") } puts sort_by_strategy(words, by_length) # [fig, kiwi, apple, banana, cherry] puts sort_by_strategy(words, by_alpha) # [apple, banana, cherry, fig, kiwi] ``` --- ## `Closures` Lambdas close over variables from the scope where they are created — they can read and remember values that were in scope at definition time. ```ruby multiplier = 10 scale = ->(x) { x * multiplier } puts scale.call(5) # 50 # The lambda captures the variable, not just its value multiplier = 3 puts scale.call(5) # 15 — uses the current value of multiplier ``` --- ## `Recursion with Lambdas` A lambda can call itself by referencing its own variable: ```ruby factorial = ->(n) do return 1 if n <= 1 n * factorial.call(n - 1) end puts factorial.call(10) # 3628800 ``` --- ## `Quick Reference` ```ruby # Define fn = ->(x) { x * 2 } fn = ->(a, b) { a + b } fn = ->(x, n = 1) { x + n } # default param fn = ->(x) do # multi-line y = x * 2 y + 1 end # Call fn.call(5) fn.call(3, 4) # Store pipeline = [fn1, fn2, fn3] ops = {double: fn1, triple: fn2} # Pass def apply(fn, val) fn.call(val) end # Use in iterators [1,2,3].map do |x| fn.call(x) end ``` --- # Record ## `What is a Record?` A Record is a named data object — a Hash with a declared structure and a readable name. Where a plain hash is anonymous, a Record prints as `Point(x: 3, y: 4)` and carries its type name everywhere it goes. Records are ideal when your data has a consistent shape and a meaningful name matters — domain objects, configuration structures, function return values. ```ruby record Point(x, y) pt = Point(3, 4) puts pt # Point(x: 3, y: 4) puts pt["x"] # 3 puts pt["__type__"] # Point ``` --- ## `Defining a Record` ```ruby record Point(x, y) record Employee(name, dept, salary) record Config(host, port, db, timeout) record RGB(r, g, b) ``` `record` takes a name and a list of field names. Field names become the hash keys. --- ## `Creating Instances` Call the record name as a function, passing values in order: ```ruby record Point(x, y) record Person(name, age, role) pt = Point(10, 20) alice = Person("Alice", 30, "Engineer") origin = Point(0, 0) puts pt # Point(x: 10, y: 20) puts alice # Person(name: Alice, age: 30, role: Engineer) ``` --- ## `Accessing Fields` Since v1.17, record fields support **dot access**: ```ruby record Point(x, y) p1 = Point(3, 4) puts p1.x # 3 puts p1.y # 4 ``` Records are still Hashes underneath — string-key access keeps working: ```ruby record Employee(name, dept, salary) emp = Employee("Alice", "Engineering", 95000) puts emp.name # Alice puts emp["name"] # Alice — equivalent puts emp["dept"] # Engineering puts emp["salary"] # 95000 # The type name is stored under __type__ puts emp["__type__"] # Employee ``` --- ## `Records are Hashes` Every hash method and iterator works on records — they are not special objects, just hashes with a `__type__` key and a readable `puts` representation. ```ruby record Point(x, y) pt = Point(3, 4) puts pt.keys # [__type__, x, y] puts pt.values # [Point, 3, 4] puts pt.size # 3 # Merge — creates a plain hash (type info preserved) moved = pt | {"x" => 10} puts moved # {__type__: Point, x: 10, y: 4} # dig record Config(db) db_config = Config({host: "localhost", port: 5432}) puts db_config.dig("db", "host") # localhost ``` --- ## `Records in Collections` Because records are hashes, all vector and hash iterators work on them naturally: ```ruby record Person(name, age, dept) people = [ Person("Alice", 32, "Engineering"), Person("Bob", 25, "Marketing"), Person("Carol", 35, "Engineering"), Person("Dave", 28, "Marketing"), Person("Eve", 41, "Engineering") ] # select — filter by field engineers = people.select do |p| p["dept"] == "Engineering" end puts engineers.length # 3 # map — transform field values names = people.map do |p| p["name"] end puts names # [Alice, Bob, Carol, Dave, Eve] # sort_by by_age = people.sort_by do |p| p["age"] end puts by_age.map do |p| "#{p["name"]} (#{p["age"]})" end # [Bob (25), Dave (28), Alice (32), Carol (35), Eve (41)] # group_by by_dept = people.group_by do |p| p["dept"] end by_dept.each do |dept, members| puts "#{dept}: #{members.map do |m| m["name"] end.join(", ")}" end # Engineering: Alice, Carol, Eve # Marketing: Bob, Dave # each_with_object — build a salary index salary_index = people.each_with_object({}) do |person, h| h[person["name"]] = person["salary"] end ``` --- ## `Records vs Plain Hashes` | | Hash | Record | |---|---|---| | Literal syntax | `{name: "Alice"}` | `Person("Alice", 30)` | | `puts` output | `{name: Alice, age: 30}` | `Person(name: Alice, age: 30)` | | Type name available | No | `r["__type__"]` | | Field order guaranteed | Yes (insertion order) | Yes (definition order) | | All hash methods | Yes | Yes | | All iterators | Yes | Yes | | Best for | Arbitrary/dynamic data | Structured domain objects | Use a plain hash when the shape is dynamic or comes from external data (JSON, CSV, DB rows). Use a Record when your code defines the shape and the name carries meaning. --- ## Modifying Records Records are mutable — field values can be changed by key assignment: ```ruby record Config(host, port, debug) cfg = Config("localhost", 5432, false) puts cfg # Config(host: localhost, port: 5432, debug: false) cfg["debug"] = true cfg["port"] = 5433 puts cfg # Config(host: localhost, port: 5433, debug: true) ``` --- ## `Pattern: Factory Function` Wrap record creation in a function for validation or default values: ```ruby record User(name, email, role, active) def make_user(name, email, role = "viewer") raise "Name required" if name == nil or name == "" raise "Email required" if email == nil or email == "" User(name, email, role, true) end admin = make_user("Alice", "alice@example.com", "admin") guest = make_user("Bob", "bob@example.com") puts admin # User(name: Alice, email: alice@example.com, role: admin, active: true) puts guest # User(name: Bob, email: bob@example.com, role: viewer, active: true) ``` --- ## `Pattern: Records as Return Values` Records make multi-value returns self-documenting: ```ruby record Stats(count, mean, stdev, min, max) def describe(data) Stats( data.length, round(mean(data), 2), round(stdev(data), 2), min(data), max(data) ) end result = describe([23, 45, 12, 67, 34, 89]) puts result # Stats(count: 6, mean: 45.0, stdev: 26.74, min: 12, max: 89) puts result["mean"] # 45.0 puts result["min"] # 12 ``` Compared to returning a plain vector `[6, 45.0, 26.74, 12, 89]`, the record is self-describing — field names are the documentation. --- ## `Quick Reference` ```ruby # Define record Point(x, y) record Person(name, age, role) # Create pt = Point(3, 4) person = Person("Alice", 30, "Engineer") # Access pt.x # field value via dot access (v1.17) pt["x"] # field value via key pt["__type__"] # "Point" # Inspect pt.keys # [__type__, x, y] pt.values # [Point, 3, 4] pt.has_key?("x") # true # Modify pt["x"] = 10 # Merge pt | {"x" => 99} # {__type__: Point, x: 99, y: 4} # In collections — all vector/hash iterators work people.select do |p| p["dept"] == "Engineering" end people.sort_by do |p| p["age"] end people.group_by do |p| p["dept"] end people.map do |p| p["name"] end ``` --- # Math & Statistics ## `Overview` Frankie has a built-in math and statistics library covering everything from basic arithmetic to descriptive statistics. The statistical functions are borrowed from R — `mean`, `median`, `stdev`, `variance` are first-class citizens, not an afterthought. Since v1.22, the library leans harder into its FORTRAN heritage too: real matrix math, complex numbers, and a full set of intrinsic math functions (`sin`, `log`, `factorial`, and friends). All functions are available without any import. --- ## Arithmetic Operators | Operator | Meaning | Example | Result | |---|---|---|---| | `+` | Addition | `10 + 3` | `13` | | `-` | Subtraction | `10 - 3` | `7` | | `*` | Multiplication | `10 * 3` | `30` | | `/` | Float division | `10 / 3` | `3.333...` | | `//` | Integer division | `10 // 3` | `3` | | `%` | Modulo | `10 % 3` | `1` | | `**` | Exponentiation | `2 ** 8` | `256` | `/` always returns a Float. Use `//` (borrowed from Fortran) for a whole-number result. ```ruby puts 10 / 3 # 3.3333333333333335 puts 10 // 3 # 3 puts 10 % 3 # 1 puts 2 ** 10 # 1024 puts 2 ** 0 # 1 ``` ### `Integer Division and Modulo with Negatives` `//` uses floor division — it rounds toward negative infinity: ```ruby puts 17 // 5 # 3 puts (-17) // 5 # -4 (floors toward -∞) puts 17 % 5 # 2 puts (-17) % 5 # 3 (result has the sign of the divisor) ``` --- ## Core Math Functions ### `abs(x)` Absolute value ```ruby puts abs(-42) → 42 puts abs(42) → 42 puts abs(-3.14) → 3.14 ``` ### `sqrt(x)` Square root Always returns a Float. ```ruby puts sqrt(144) → 12.0 puts sqrt(2) → 1.4142135623730951 puts sqrt(0) → 0.0 ``` ### `floor(x)` Round down Returns the largest integer less than or equal to `x`. ```ruby puts floor(3.7) → 3 puts floor(3.0) → 3 puts floor(-3.2) → -4 (toward -∞, not toward zero) ``` ### `ceil(x)` Round up Returns the smallest integer greater than or equal to `x`. ```ruby puts ceil(3.2) → 4 puts ceil(3.0) → 3 puts ceil(-3.7) → -3 ``` ### `round(x, n)` Round to n decimal places `n` defaults to 0. Returns a Float when `n > 0`, an integer-like Float when `n = 0`. ```ruby puts round(3.14159, 2) → 3.14 puts round(3.14159, 4) → 3.1416 puts round(3.5) → 4.0 puts round(-3.5) → -4.0 puts round(2.71828, 3) → 2.718 ``` ### `sin(x)`, `cos(x)`, `tan(x)`, `asin(x)`, `acos(x)`, `atan(x)`, `atan2(y, x)` (v1.22) Trigonometric functions Angles are in radians, matching FORTRAN's intrinsic `SIN`/`COS`/`TAN` family. ```ruby puts sin(0) → 0.0 puts cos(0) → 1.0 puts atan2(1, 1) → 0.7853981633974483 — π/4 ``` ### `exp(x)`, `log(x, base = nil)`, `log10(x)`, `log2(x)` (v1.22) Exponential and logarithms `log(x)` is natural log by default; pass a second argument for a specific base. ```ruby puts exp(1) → 2.718281828459045 puts log(E) → 1.0 puts log(8, 2) → 3.0 puts log10(1000) → 3.0 puts log2(8) → 3.0 ``` ### `PI` and `E` (v1.22) Constants ```ruby puts PI → 3.141592653589793 puts E → 2.718281828459045 ``` ### `factorial(n)`, `gcd(a, b)`, `lcm(a, b)` (v1.22) Number theory ```ruby puts factorial(5) → 120 puts gcd(12, 18) → 6 puts lcm(4, 6) → 12 ``` `factorial` raises for negative input. ### `clamp(x, lo, hi)` Constrain to a range Returns `lo` if `x < lo`, `hi` if `x > hi`, otherwise `x`. ```ruby puts clamp(15, 0, 10) → 10 — above max puts clamp(-5, 0, 10) → 0 — below min puts clamp(5, 0, 10) → 5 — within range puts clamp(3.14, 0.0, 3.0) → 3.0 ``` ### `min` and `max` Work on two values or on a vector: ```ruby puts min(3, 7) → 3 puts max(3, 7) → 7 puts min([3, 1, 4, 1, 5, 9]) → 1 puts max([3, 1, 4, 1, 5, 9]) → 9 # Also available as vector methods puts [3, 1, 4, 1, 5, 9].min → 1 puts [3, 1, 4, 1, 5, 9].max → 9 ``` --- ## Statistics Functions All statistics functions take a vector of numbers. ### `sum(v)` Total ```ruby puts sum([1, 2, 3, 4, 5]) → 15 puts [10, 20, 30].sum → 60 — method form ``` ### `mean(v)` Arithmetic mean ```ruby data = [23, 45, 12, 67, 34, 89, 56] puts mean(data) → 46.57142857142857 puts data.mean → same — method form ``` ### `median(v)` Middle value For even-length vectors, returns the average of the two middle values. ```ruby puts median([1, 2, 3, 4, 5]) → 3 puts median([1, 2, 3, 4, 5, 6]) → 3.5 puts median([23, 45, 12, 67, 34]) → 34 ``` ### `stdev(v)` Sample standard deviation Measures spread. Uses `n-1` (Bessel's correction) — sample standard deviation, not population. ```ruby data = [23, 45, 12, 67, 34, 89, 56, 11, 78, 42] puts stdev(data) → 26.84130316425705 ``` ### `variance(v)` Sample variance The square of the standard deviation. ```ruby puts variance(data) → 720.4555555555554 ``` --- ## Sequences and Ranges ### `seq(start, stop, step)` Numeric sequence Generates a vector from `start` to `stop` in steps of `step`. Borrowed from R. ```ruby puts seq(1, 5) → [1, 2, 3, 4, 5] puts seq(0, 10, 2) → [0, 2, 4, 6, 8, 10] puts seq(5, 1, -1) → [5, 4, 3, 2, 1] puts seq(0.0, 1.0, 0.25) → [0.0, 0.25, 0.5, 0.75, 1.0] ``` ### `linspace(start, stop, n)` Evenly spaced values Generates exactly `n` values evenly distributed between `start` and `stop`, inclusive. ```ruby puts linspace(0.0, 1.0, 5) → [0.0, 0.25, 0.5, 0.75, 1.0] puts linspace(0.0, 100.0, 6) → [0.0, 20.0, 40.0, 60.0, 80.0, 100.0] ``` ### `vec(range)` Vector from a range literal ```ruby puts vec(1..10) → [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] puts vec(0...5) → [0, 1, 2, 3, 4] ``` ### `rep(x, n)` Repeat a value ```ruby puts rep(0, 5) → [0, 0, 0, 0, 0] puts rep(3.14, 3) → [3.14, 3.14, 3.14] puts rep("ha", 3) → ["ha", "ha", "ha"] ``` --- ## `Vectorised Arithmetic` Operations on vectors apply element-wise — R does this natively, and it's exactly the whole-array math FORTRAN 90+ pioneered decades earlier (`C = A + B` adds two arrays element-wise with no explicit loop). `+`, `-`, `/`, `%`, and `**` all work this way: ```ruby v = [1, 2, 3, 4, 5] puts v + [10,10,10,10,10] → [11, 12, 13, 14, 15] puts v ** 2 → [1, 4, 9, 16, 25] puts v - [1, 1, 1, 1, 1] → [0, 1, 2, 3, 4] ``` Vectors must be the same length for binary operations. Use `linspace` or `rep` to create a matching vector. `*` is the one exception — `v * 2` repeats the vector (Python-list semantics: `[1,2,3] * 2 → [1,2,3,1,2,3]`), not element-wise scaling. For scaling, either add the vector to itself the needed number of times, or reach for `matrix_scale` if you're working with a matrix (below). --- ## `Matrix Math (v1.22)` A matrix is just a vector of vectors, and since v1.22 arithmetic recurses through nested vectors at every depth — so `+`, `-`, `/`, `%`, and `**` on two matrices are genuinely element-wise, not a silent row-by-row concatenation: ```ruby m1 = [[1, 2], [3, 4]] m2 = [[5, 6], [7, 8]] puts m1 + m2 → [[6, 8], [10, 12]] puts m1 - m2 → [[-4, -4], [-4, -4]] ``` ### `matrix_new(rows, cols, fill = 0)` Build a filled matrix ```ruby puts matrix_new(2, 3, 0) → [[0, 0, 0], [0, 0, 0]] ``` ### `matrix_identity(n)` Build an n×n identity matrix ```ruby puts matrix_identity(3) → [[1, 0, 0], [0, 1, 0], [0, 0, 1]] ``` ### `matrix_shape(m)` Return `[rows, cols]` ```ruby puts matrix_shape(matrix_new(2, 5, 0)) → [2, 5] ``` ### `matrix_transpose(m)` Swap rows and columns ```ruby puts matrix_transpose([[1, 2, 3], [4, 5, 6]]) → [[1, 4], [2, 5], [3, 6]] ``` ### `matrix_scale(m, n)` Multiply every element by `n` Since `*` stays as vector-repeat at the top level (unchanged, matching pre-v1.22 behavior), use `matrix_scale` for true element-wise scalar multiplication: ```ruby puts matrix_scale([[1, 2], [3, 4]], 3) → [[3, 6], [9, 12]] ``` ### `matrix_multiply(m1, m2)` Real matrix multiplication (row · column) This is different from `*`, which stays element-wise for two matrices of the same shape — `matrix_multiply` does the actual linear-algebra dot-product multiplication, and requires `m1`'s column count to match `m2`'s row count. ```ruby puts matrix_multiply([[1, 2], [3, 4]], [[5, 6], [7, 8]]) → [[19, 22], [43, 50]] ``` Raises if the shapes are incompatible. --- ## `Complex Numbers (v1.22)` FORTRAN has shipped a native `COMPLEX` type since FORTRAN 66. Frankie exposes Python's built-in complex number support the same flat, no-import-needed way as everything else in this library — `+`, `-`, `*`, `/`, and `**` all work natively once you have one. ```ruby c1 = complex_new(3, 4) c2 = complex_new(1, 2) puts c1 → 3+4i puts c1 + c2 → 4+6i puts c1 * c2 → -5+10i ``` Printed in conventional math notation (`3+4i`), not Python's electrical-engineering-flavored `3+4j`. ### `complex_new(real, imag = 0)` Build a complex number ### `complex_real(c)` / `complex_imag(c)` Read the real / imaginary parts ```ruby c = complex_new(3, 4) puts complex_real(c) → 3.0 puts complex_imag(c) → 4.0 ``` ### `complex_conj(c)` Complex conjugate (negates the imaginary part) ```ruby puts complex_conj(complex_new(3, 4)) → 3-4i ``` ### `complex_abs(c)` Magnitude ```ruby puts complex_abs(complex_new(3, 4)) → 5.0 — 3-4-5 triangle ``` --- ## `The Pipe Operator for Data Pipelines` `|>` passes the left value as the argument to the right function. Combines naturally with stats: ```ruby data = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3] data |> sum |> puts → 39 data |> mean |> puts → 3.9 data |> min |> puts → 1 data |> max |> puts → 9 # Chain transformations [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] .select do |x| x % 2 == 0 end |> sum |> puts → 30 ``` ## Randomness ### `rand_int(a, b)` Random integer Returns a random integer between `a` and `b` inclusive. ```ruby puts rand_int(1, 6) → dice roll — 1 to 6 puts rand_int(0, 100) → 0 to 100 ``` ### `rand_float(a, b)` Random float Returns a random float between `a` and `b`. ```ruby puts rand_float(0.0, 1.0) → e.g. 0.7493381866018054 puts rand_float(-1.0, 1.0) → e.g. -0.234... ``` ### `rand()` Random float 0..1 ```ruby puts rand() # e.g. 0.4217... ``` ### `rand_seed(n)` Seed for reproducibility Fix the random seed to get the same sequence every time — useful for tests and reproducible simulations. ```ruby rand_seed(42) puts rand_int(1, 100) → always the same value for seed 42 puts rand_int(1, 100) → next value in the same sequence ``` ### `shuffle(v)` Randomly reorder a vector ```ruby v = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] puts shuffle(v) → e.g. [4, 9, 1, 7, 3, 10, 5, 2, 8, 6] ``` ### `sample(v, n)` Random sample without replacement ```ruby v = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] puts sample(v, 3) → e.g. [7, 2, 9] puts sample(v, 1) → e.g. [4] ``` --- ## Numeric Formatting Use `sprintf` for precise control over how numbers are displayed: ```ruby puts sprintf("%.2f", 3.14159) → 3.14 puts sprintf("%.4f", 3.14159) → 3.1416 puts sprintf("%08.3f", 3.14) → 0003.140 puts sprintf("%+d", 42) → +42 puts sprintf("%+d", -42) → -42 puts sprintf("%d items at $%.2f each", 5, 1.99) → 5 items at $1.99 each ``` Or use `round` for display without format strings: ```ruby data = [1.23456, 7.89012, 3.45678] puts data.map do |x| round(x, 2) end → [1.23, 7.89, 3.46] ``` --- ## Quick Reference | Function | Description | Example | |---|---|---| | `abs(x)` | Absolute value | `abs(-5)` → `5` | | `sqrt(x)` | Square root | `sqrt(9)` → `3.0` | | `floor(x)` | Round down | `floor(3.9)` → `3` | | `ceil(x)` | Round up | `ceil(3.1)` → `4` | | `round(x, n)` | Round to n places | `round(3.14159, 2)` → `3.14` | | `clamp(x, lo, hi)` | Constrain to range | `clamp(15, 0, 10)` → `10` | | `min(a, b)` / `min(v)` | Minimum | `min(3, 7)` → `3` | | `max(a, b)` / `max(v)` | Maximum | `max(3, 7)` → `7` | | `sum(v)` | Sum of all elements | `sum([1,2,3])` → `6` | | `mean(v)` | Arithmetic mean | `mean([1,2,3])` → `2.0` | | `median(v)` | Middle value | `median([1,2,3])` → `2` | | `stdev(v)` | Sample standard deviation | `stdev([2,4,4,4,5,5,7,9])` → `2.0` | | `variance(v)` | Sample variance | `variance([2,4,6])` → `4.0` | | `seq(start, stop, step)` | Numeric sequence | `seq(1, 5)` → `[1,2,3,4,5]` | | `linspace(start, stop, n)` | n evenly-spaced values | `linspace(0.0, 1.0, 3)` → `[0.0, 0.5, 1.0]` | | `vec(range)` | Vector from range | `vec(1..5)` → `[1,2,3,4,5]` | | `rep(x, n)` | Repeat value | `rep(0, 3)` → `[0,0,0]` | | `rand_int(a, b)` | Random integer a..b | `rand_int(1, 6)` | | `rand_float(a, b)` | Random float a..b | `rand_float(0.0, 1.0)` | | `rand()` | Random float 0..1 | `rand()` | | `rand_seed(n)` | Fix random seed | `rand_seed(42)` | | `shuffle(v)` | Randomly reorder | `shuffle([1,2,3,4,5])` | | `sample(v, n)` | Random sample | `sample(v, 3)` | | `sprintf(fmt, ...)` | Formatted number string | `sprintf("%.2f", 3.14159)` | | `sin(x)` / `cos(x)` / `tan(x)` (v1.22) | Trigonometric functions | `sin(0)` → `0.0` | | `asin(x)` / `acos(x)` / `atan(x)` / `atan2(y, x)` (v1.22) | Inverse trig | `atan2(1, 1)` → `0.785...` | | `exp(x)` (v1.22) | e^x | `exp(1)` → `2.718...` | | `log(x, base = nil)` (v1.22) | Logarithm | `log(8, 2)` → `3.0` | | `log10(x)` / `log2(x)` (v1.22) | Base-10 / base-2 log | `log10(1000)` → `3.0` | | `PI` / `E` (v1.22) | Constants | `PI` → `3.14159...` | | `factorial(n)` (v1.22) | n! | `factorial(5)` → `120` | | `gcd(a, b)` / `lcm(a, b)` (v1.22) | Number theory | `gcd(12, 18)` → `6` | | `matrix_new(rows, cols, fill)` (v1.22) | Filled matrix | `matrix_new(2, 2, 0)` → `[[0,0],[0,0]]` | | `matrix_identity(n)` (v1.22) | Identity matrix | `matrix_identity(2)` → `[[1,0],[0,1]]` | | `matrix_shape(m)` (v1.22) | `[rows, cols]` | `matrix_shape([[1,2,3]])` → `[1,3]` | | `matrix_transpose(m)` (v1.22) | Swap rows/cols | `matrix_transpose([[1,2]])` → `[[1],[2]]` | | `matrix_scale(m, n)` (v1.22) | Element-wise scalar multiply | `matrix_scale([[1,2]], 2)` → `[[2,4]]` | | `matrix_multiply(m1, m2)` (v1.22) | Real matrix multiplication | `matrix_multiply([[1,2]], [[1],[2]])` → `[[5]]` | | `complex_new(real, imag)` (v1.22) | Complex number | `complex_new(3, 4)` → `3+4i` | | `complex_real(c)` / `complex_imag(c)` (v1.22) | Real / imaginary part | `complex_real(complex_new(3,4))` → `3.0` | | `complex_conj(c)` (v1.22) | Complex conjugate | `complex_conj(complex_new(3,4))` → `3-4i` | | `complex_abs(c)` (v1.22) | Magnitude | `complex_abs(complex_new(3,4))` → `5.0` | --- # Integer Methods ## Conversion ### `.to_f` Convert to Float. ```ruby puts 42.to_f → 42.0 ``` ### .to_s Convert to String. ```ruby puts 42.to_s → "42" ``` ### `.to_i` Return self — no-op, but useful in generic code where the type isn't known. ```ruby puts 42.to_i → 42 ``` --- ## Iteration ### `.times do |i|` Repeat a block exactly n times. i counts from 0 to n-1. ```ruby 3.times do |i| puts i end → 0, 1, 2 ``` --- ## `Standalone functions` | What do you want | How you do it Frankie | |---|---| | `Absolute value` | abs(n) | | `Is it zero?` | n == 0 | | `Is it even?` | n % 2 == 0 | | `Is it odd?` | n % 2 != 0 | | `Is it positive?` | n > 0 | | `Clamp to range` | clamp(n, lo, hi) | | `Square root` | sqrt(n) | | `Random integer` | rand_int(a, b) | | `Type check` | is_integer(n) | --- # String methods ## Case and Whitespace ### `.upcase` Convert all characters to uppercase. ```ruby "hello".upcase → "HELLO" ``` ### `.downcase` Convert all characters to lowercase. ```ruby "HELLO".downcase → "hello" ``` ### `.strip` Remove leading and trailing whitespace. ```ruby " hi ".strip → "hi" ``` ### `.lstrip` Remove leading whitespace only. ### `.rstrip` Remove trailing whitespace only. ### `.chomp` Remove a trailing newline character. Useful after file_lines or user input. ### `.chop` Remove the last character unconditionally. ```ruby "hello!".chop → "hello" ``` --- ## Inspection & testing ### `length` Number of characters. ```ruby "Frankie".length → 7 ``` ### `.empty?` True if the string has zero characters. ```ruby "".empty? → true ``` ### `.nil?` Always false for a string; useful in nil-safe chains with &. ### `.include?(n)` True if n appears anywhere in the string. ```ruby "Frankie".include?("n") → true ``` ### `.start_with?(n)` True if the string begins with n. ```ruby "Frankie".start_with?("F") → true ``` ### `.end_with?(s)` True if the string ends with s. ```ruby "Frankie".end_with?("e") → true ``` ### `.count(sub)` Count non-overlapping occurrences of sub. ```ruby "hello".count("l") → 2 ``` --- ## Transformation ### `.reverse` Reverse the string character by character. ```ruby "Frankie".reverse → "eiknarF" ``` ### `.replace(old, new)` Replace the first occurrence of old with new. Alias for sub(). ```ruby "Franpie".replace("p","k") → "Frankie" ``` ### `.delete(chars)` Remove all occurrences of any character in chars. ```ruby "hello".delete("l") → "heo" ``` ### `.squeeze` Collapse runs of consecutive identical characters. ```ruby "aaabbbccc".squeeze → "abc" ``` ### `.tr(from, to)` Translate characters — each character in from is replaced by the corresponding character in to. ```ruby "hello".tr("aeiou", "*") → "h*ll*" ``` ### `.center(width, pad)` Center in a field of width, padded with pad. ```ruby "hi".center(10, "-") → "----hi----" ``` ### `.ljust(width, pad)` Left-justify in a field of width. ```ruby "hi".ljust(10, "-") → hi-------- ``` ### `.rjust(width, pad)` Right-justify in a field of width. ```ruby "hi".rjust(10, "-") → --------hi ``` ### `.encode` Convert string to a vector of byte values (UTF-8). ```ruby "hi".encode → [104, 105] ``` --- ## Splitting & joining ### `.split(sep)` Split on a separator string, return a Vector. ```ruby "a,b,c".split(",") → [a, b, c] ``` ### `.join(sep)` Join a vector of strings with a separator. Called on a Vector but takes a string arg. ```ruby ["a","b"].join("-") → a-b ``` ### `.lines` Split into a vector of lines, stripping newline characters ```ruby "a,b,c".lines → [a,b,c] ``` ### `.chars` Split into a vector of individual characters. Chains naturally into iterators. ```ruby puts "abc".chars → [a b c] ``` ### `.bytes` Return a vector of integer byte values. ```ruby puts "abc".bytes → [97, 98, 99] ``` ### `.each_char do |c|` Iterate over each character with a block. ```ruby "Frankie".each_char do |c| puts c end → F r a n k i e ``` ### `.each_line do |l|` Iterate over each line with a block. ```ruby "Frankie is great!".each_line do |c| c = c.delete("i") puts c end → Franke s great! ``` --- ## Slicing ### `[i]` Character at index i. Negative indices count from the end. ```ruby "hello"[-1] → "o" ``` --- ### `[a..b]` Inclusive slice from index a to b. ```ruby "hello"[1..3] → "ell" ``` ### `[a...b]` Exclusive slice — up to but not including b ``` "hello"[1...3] → "el" ``` ### `template(str, hash)` {{key}} placeholder replacement. ```ruby puts template("{{name}} is awesome!", {name: "Frankie"}) → Frankie is awesome! ``` ### `sprintf(fmt, args)` C-style formatting. ```ruby puts sprintf("%-10s %5d %8.2f", "Frankie", 1, 3.14444) → Frankie 1 3.14 ``` ### `.format(hash)` Named placeholder substitution. *(introduced in v1.15)* Replaces `{key}` placeholders using values from the given hash. Raises a descriptive error if a key is missing. ```ruby puts "Hello, {name}! You have {count} messages.".format({name: "Alice", count: 5}) → Hello, Alice! You have 5 messages. puts "Order {id} placed by {user}".format({id: 42, user: "Bob"}) → Order 42 placed by Bob ``` ### `paste(a, b, sep)` Concatenate with separator. ```ruby puts paste("2026", "03", "14", sep: "/") → 2026/03/14 ``` --- ## Pattern Extraction *(introduced in v1.16)* ### `.scan(pattern)` Find all non-overlapping matches of a regex pattern in the string. Returns a vector of matched strings (or capture groups if the pattern contains them). ```ruby # Extract all words puts "hello world frankie".scan("[a-z]+") # ["hello", "world", "frankie"] # Extract email addresses text = "Contact alice@example.com or bob@test.org for help." emails = text.scan("[\\w.]+@[\\w.]+") puts emails # ["alice@example.com", "bob@test.org"] # Extract dates log = "Errors on 2026-01-15 and 2026-02-03." dates = log.scan("\\d{4}-\\d{2}-\\d{2}") puts dates # ["2026-01-15", "2026-02-03"] # Extract numbers prices = "Items cost $12.50, $3.99, and $45.00." amounts = prices.scan("\\d+\\.\\d{2}") puts amounts # ["12.50", "3.99", "45.00"] ``` `scan` is commonly combined with iterators: ```ruby html = "Frankie" urls = html.scan("href='([^']+)'") urls.each do |url| puts "Found link: #{url}" end ``` --- # Vector Methods ## Access ### `.first` First element. Returns nil if empty. ```ruby puts [1,2,3].first → 1 ``` ### `.last` Last element. Returns nil if empty. ```ruby puts [1,2,3].last → 3 ``` ### `[i]` Element at index i. Negative indices count from the end. v[-1] is the last element. ```ruby puts [1,2,3][1] → 2 ``` ### `[a..b]` Inclusive slice. ```ruby [1,2,3,4][1..2] → [2,3] ``` ### `[a...b]` Exclusive slice — up to but not including b. ```ruby [1,2,3,4][1...2] → [2] ``` ### `.take(n)` First n elements. ```ruby [1,2,3,4].take(2) → [1,2] ``` ### `.drop(n)` All elements after the first n. ```ruby [1,2,3,4].drop(2) → [3,4] ``` ### `.dig(i1, i2, ...)` Safe nested access through vectors and hashes. Returns nil instead of crashing. ```ruby puts [1,2,3].dig(4) → nil ``` --- ## Inspection ### `.length` Number of elements. ```ruby puts [1,2,3].length → 3 ``` ### `.size` *Alias for .length* ```ruby puts [1,2,3].size → 3 ``` ### `.count` *Alias for .length* With a block: count elements satisfying the condition. ```ruby numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] puts numbers.count do |x| x % 2 == 0 end → 5 ``` ### `.empty?` True if the vector has no elements. ```ruby puts [].empty? → true ``` ### `.include?(n)` True if n is an element. ```ruby puts ["a","b","c"].include?("b") → true ``` ### `.nil?` Always false for a vector; useful in nil-safe chains. ```ruby puts [].nil? → false ``` ### `.tally` Count occurrences of each element, return a Hash. ```ruby puts ["a","b","a"].tally → {a: 2, b: 1} ``` --- ## Iteration ### `.each do |x|` Iterate over each element. Returns nothing — used for side effects. ```ruby [1,2,3].each do |x| puts x * 2 end → 2 4 6 ``` ### `.each_with_index do |x, i|` Iterate with element and its index available. ```ruby [1,2,3].each_with_index do |x, i| puts "i: #{i}, x: #{x}" end → i: 0, x: 1 i: 1, x: 2 i: 2, x: 3 ``` ### `.each_with_object(init) do |x, obj|` Iterate with a shared accumulator. Works with any init type — vector, hash, integer. ```ruby double = [1,2,3].each_with_object([]) do |x, arr| arr.push(x * 2) end puts double → [2, 4, 6] ``` ### `.each_slice(n) do |slice|` Iterate in non-overlapping chunks of n elements ```ruby [1,2,3,4,5].each_slice(2) do |slice| puts slice end → [1, 2] [3, 4] [5] ``` ### `.each_cons(n) do |window|` Iterate with a sliding window of n elements. ```ruby [1,2,3,4,5].each_cons(2) do |window| puts window end ``` --- ## Transformation ### `.map do |x|` Transform each element, return a new vector. ```ruby puts [1,2,3].map do |x| x * 3 end → [3, 6, 9] ``` ### `.map_with_index do |x, i|` Map with both the element and its index available. ```ruby puts [1,2,3,4,5].map_with_index do |x, i| x * i end → [0, 2, 6, 12, 20] ``` ### `.flat_map do |x|` Map then flatten one level. Block returns a vector per element. ```ruby sentences = ["hello world", "frankie is great"] puts sentences.flat_map do |s| s.split(" ") end → [hello, world, frankie, is, great] ``` ### `.select do |x|` Keep elements where block returns true. *Alias: .filter* ```ruby puts [1,2,3,4,5].select do |x| x % 2 == 0 end → [2, 4] ``` ### `.reject do |x|` Keep elements where block returns false — opposite of .select. ```ruby puts [1,2,3,4,5].reject do |x| x % 2 == 0 end → [1, 3, 5] ``` ### `.inject(init) do |acc, x|` Fold elements into a single value. ### `.reduce(init) do |acc, x|` Fold elements into a single value. *Alias: .inject* ```ruby puts [1,2,3,4,5].reduce(0) do |acc, x| acc + x end → 15 ``` ### `.sort` Sorted copy using natural ordering. ```ruby puts [1,3,8,4,5].sort → [1, 3, 4, 5, 8] ``` ### `.sort_by do |x|` Sort by a computed key. ```ruby puts ["frankie","hello","world"].sort_by do |w| w.length end → [hello, world, frankie] ``` ### `.reverse` Reversed copy. ```ruby puts [1,2,3,4,5].reverse → [5, 4, 3, 2, 1] ``` ### `.uniq` Remove duplicates, preserving first occurrence order. ```ruby puts [1,2,3,1,1,4,5,3].uniq → [1, 2, 3, 4, 5] ``` ### `.union(other)` *(v1.18)* All elements from both vectors — order-preserving, deduplicating. ```ruby puts [1, 2, 3].union([3, 4, 5]) → [1, 2, 3, 4, 5] ``` ### `.intersect(other)` *(v1.18)* Elements present in both vectors. ```ruby puts [1, 2, 3].intersect([2, 3, 9]) → [2, 3] ``` ### `.difference(other)` *(v1.18)* Elements of the receiver not present in the argument. ```ruby puts [1, 2, 3].difference([2]) → [1, 3] ``` ### `.flatten` Deep flatten — recursively collapses all nested vectors. ```ruby puts [[1,2,3],["a","b","c"]].flatten → [1, 2, 3, a, b, c] ``` ### `flatten(n)` Flatten exactly n levels deep. ```ruby puts [[[1,2,3],["a","b","c"]]].flatten(2) → [1, 2, 3, a, b, c] ``` ### `.compact` Remove all nil values. ```ruby puts [1,2,nil,4,nil,6].compact → [1, 2, 4, 6] ``` ### `.zip(other)` Pair elements with another vector. ```ruby [1,2].zip([3,4]) → [[1,3],[2,4]] ``` ### `.zip_with(other) do |a, b|` Zip and transform each pair in one step. ```ruby puts [1,2].zip_with([3,4]) do |a, b| a * b end → [3, 8] ``` ### `.product(other)` Cartesian product. ``` [1,2].product([3,4]) → [[1,3],[1,4],[2,3],[2,4]]. ``` ### `.chunk(n)` Split into sub-vectors of size n. Last chunk may be smaller. ```ruby puts [1,2,3,4,5,6].chunk(3) → [[1, 2, 3], [4, 5, 6]] ``` ### `.group_by do |x|` Bucket elements into a Hash of arrays keyed by block result. ```ruby numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] result = numbers.group_by do |x| (if x % 2 == 0 then "even" else "odd" end) end puts result["even"] → [2, 4, 6, 8, 10] puts result["odd"] → [1, 3, 5, 7, 9] ``` ### `join(sep)` Concatenate all elements as strings with a separator between them. ```ruby puts [1,2,3,4,5].join("-") → 1-2-3-4-5 ``` ### `.encode` Convert a vector of byte integers back to a string. ```ruby puts [70, 114, 97, 110, 107, 105, 101].encode → Frankie ``` ### `* n` Repeat the vector n times. ```ruby [1,2] * 3 → [1,2,1,2,1,2] ``` --- ## Search & test ### `.find do |x|` First element where block is true. Returns nil if none. *Alias: .detect* ```ruby puts [1,2,3,4,5].find do |x| x > 3 end → 4 ``` ### `.any? do |x|` True if at least one element satisfies the block. ```ruby puts [1,2,3,4,5].any? do |x| x > 3 end → true ``` ### `.all? do |x|` True if every element satisfies the block. ```ruby puts [1,2,3,4,5].all? do |x| x > 3 end → false ``` ### `.none? do |x|` True if no element satisfies the block. ```ruby puts [1,2,3,4,5].none? do |x| x > 6 end → true ``` ### `.count do |x|` Count of elements satisfying the block. ```ruby puts [1,2,3,4,5].count do |x| x % 2 == 0 end → 2 ``` ### `.min_by do |x|` Element with the smallest key value. ```ruby puts [1,2,3,4,5].min_by do |x| x end → 1 ``` ### `.max_by do |x|` Element with the largest key value. ```ruby puts [1,2,3,4,5].max_by do |x| x end → 5 ``` ### `.sum_by do |x|` Sum of block results across all elements. ```ruby puts [1,2,3,4,5].sum_by do |x| x + 1 end → 20 ``` --- ## Mutation ### `.push(x)` Append an element, return the vector. ```ruby puts [1,2,3].push("a") → [1, 2, 3, a] ``` ### `.pop()` Remove and return the last element. ```ruby puts [1,2,3,"a"].pop() → a ``` ### `.delete(x)` Remove first occurrence of x. ```ruby puts [1,2,3,4].delete(3) → [1, 2, 4] ``` --- ## Aggregation ### `.sum` Sum of all elements. ```ruby puts [1,2,3,4,5].sum → 15 ``` ### `.min` Smallest element. ``` puts [1,2,3,4,5].min → 1 ``` ### `.max` Largest element. ```ruby puts [1,2,3,4,5].min → 5 ``` ### `unzip(vec)` Standalone function. Split a vector of pairs into two vectors. ```ruby unzip([[1,"a"],[2,"b"]]) → [[1,2],["a","b"]] ``` ## Statistics ### `.mean` Arithmetic mean. ```ruby puts [1,2,3,4,5].mean → 3.0 ``` ### `median(vec)` Median value — standalone only. ```ruby puts median([1,2,3,4,5]) → 3 ``` ### `stdev(vec)` Sample standard deviation — standalone only. ```ruby puts stdev([1,2,3,4,5]) → 1.5811388300841898 ``` ### `variance(vec)` Sample variance — standalone only. ```ruby puts variance([1,2,3,4,5]) → 2.5000000000000004 ``` --- # Hash Methods ## Access ### `h[key]` Get the value for a key. Returns nil if the key doesn't exist. ```ruby prices = {"apple": 1.20, "banana": 0.50} puts prices["apple"] → 1.20 ``` ### `.fetch(key, default)` Get a value with an explicit default if the key is missing. ```ruby prices = {"apple": 1.20, "banana": 0.50} puts prices.fetch("Pears", 0.75) → 0.75 ``` ### `.dig(k1, k2, ...)` Safe nested access through any combination of hashes and vectors. Returns nil instead of crashing at any level. ```ruby prices = {"fruit": {"apples": 1.20, "banana":0.50}, "vegetables": {"lettuce":0.45}} puts prices.dig("fruit", "banana") → 0.5 ``` --- ## Inspection ### `.keys` Vector of all keys. ```ruby {a: 1, b: 2}.keys → ["a", "b"]. ``` ### `.values` Vector of all values. ```ruby {a: 1, b: 2}.values → [1, 2] ``` ### `.size` Number of key-value pairs. Alias: .count. ```ruby puts {"fruit": {"apples": 1.20, "banana":0.50}, "vegetables": {"lettuce":0.45}}.size → 2 ``` ### `.has_key?(k)` True if key k exists. ``` puts {"apple": 1.20, "banana": 0.50}.has_key?("banana") → true ``` ### `.empty?` True if the hash has no pairs. ``` puts {"apple": 1.20, "banana": 0.50}.empty? → false ``` ### `.nil?` Always false for a hash. useful in nil-safe chains. ```ruby puts {"apple": 1.20, "banana": 0.50}.nil? → false ``` --- ## Mutation ### `h[key] = value` Add or update a key. ```ruby prices = {"apple": 1.20, "banana": 0.50} prices["apple"] = 1.50 puts prices["apple"] → 1.5 ``` ### `.store(key, value)` Identical to h[key] = value — method form of key assignment. ### `.delete(key)` Remove a key, return the hash. Doesn't crash if the key is missing. ```ruby prices = {"apple": 1.20, "banana": 0.50, "orange": 0.4}.delete("banana") puts prices → {apple: 1.2, orange: 0.4} ``` ### `.merge_bang(other)` Merge other into the hash in place. Right-hand keys win. ``` prices = {"apple": 1.20, "banana": 0.50}.merge_bang({"orange": 0.4}) puts prices → {apple: 1.2, banana: 0.5, orange: 0.4} ``` --- ## Merging ### `.merge(other)` Return a new merged hash. Right-hand keys win on conflict. Does not modify the original. ```ruby hash = {"apple": 1.20, "banana": 0.50} prices = hash.merge({"orange": 0.4}) puts prices puts hash → {apple: 1.2, banana: 0.5, orange: 0.4} → {apple: 1.2, banana: 0.5} ``` ### `h1 | h2` Merge operator — identical to .merge. Chains cleanly: base | env | local ``` hash = {"apple": 1.20, "banana": 0.50} prices = hash | {"orange": 0.4} puts prices puts hash → {apple: 1.2, banana: 0.5, orange: 0.4} → {apple: 1.2, banana: 0.5} ``` --- ## Iteration ### `.each do |k, v|` Iterate over all key-value pairs. With two block params gives key and value separately; with one param gives a [key, value] pair. ```ruby {"apple": 1.20, "banana": 0.50}.each do |k, v| puts "#{k} : #{v}" end → apple : 1.2 → banana : 0.5 ``` ### `.each_pair do |k, v|` Identical to .each — explicit pair-iteration alias. ### `.each_with_object(init) do |pair, obj|` Iterate with a shared accumulator. The pair arrives as [key, value]. ```ruby puts {"apple": 1.20, "banana": 0.50}.each_with_object({}) do |pair, acc| key = pair[0] value = pair[1] acc[key] = "$#{value}" end → {apple: $1.2, banana: $0.5} ``` --- ## Transformation ### `.map do |k, v|` Transform each pair, return a vector of results. Block receives key and value. ```ruby puts {"apple": 1.20, "banana": 0.50, "orange": 0.4}.map do |k, v| h = {} h[k] = v * 2 h end → [{apple: 2.4}, {banana: 1.0}, {orange: 0.8}] ``` ### `.map_hash do |k, v|` Transform each pair, return a new hash. Block must return [new_key, new_value]. ```ruby puts {"apple": 1.20, "banana": 0.50, "orange": 0.4}.map_hash do |k, v| [k, v * 2] end → {apple: 2.4, banana: 1.0, orange: 0.8} ``` ### `.select do |k, v|` Keep pairs where the block returns true. Returns a new hash. ```ruby puts {"apple": 1.20, "banana": 0.50, "orange": 0.4}.select do |k, v| v > 0.4 end → ``` ### `.reject do |k, v|` Keep pairs where the block returns false. Returns a new hash. ```ruby puts {"apple": 1.20, "banana": 0.50, "orange": 0.4}.reject do |k, v| v > 0.4 end → {orange: 0.4} ``` --- ## Conversion ### `.to_a` Convert to a vector of [key, value] pairs. ```ruby {a: 1, b: 2}.to_a → [["a", 1], ["b", 2]] ``` ### `.keys` Already listed above — also a conversion in the sense of extracting one dimension. ```ruby puts {"apple": 1.20, "banana": 0.50, "orange": 0.4}.keys → [apple, banana, orange] ``` ### `.values` Already listed above — also a conversion in the sense of extracting one dimension. ```ruby puts {"apple": 1.20, "banana": 0.50, "orange": 0.4}.keys → [1.2, 0.5, 0.4] ``` --- ## Standalone functions that operate on hashes ### `json_write(path, hash)` Serialise a hash to a JSON file. ```ruby puts json_write("PATH/test.json", {"apple": 1.20, "banana": 0.50, "orange": 0.4}) → true ``` ### `json_read(path)` Read it back. ```ruby puts json_read("PATH/test.json") → {apple: 1.2, banana: 0.5, orange: 0.4} ``` ### `template(str, hash)` {{key}} placeholder replacement. ```ruby puts template("{{name}} is awesome!", {name: "Frankie"}) → Frankie is awesome! ``` ### `str.format(hash)` {key} placeholder substitution. ```ruby template = "Hello, {name}! You are {age} years old." puts template.format({name: "Frankie", age: 1}) → Hello, Frankie! You are 1 years old. ``` --- ## Advanced Transformation *(introduced in v1.16)* ### `.transform_values do |v| ... end` Return a new hash with the same keys but each value replaced by the block's return value. ```ruby prices = {apple: 1.0, banana: 0.5, cherry: 2.5} doubled = prices.transform_values do |v| v * 2 end # {apple: 2.0, banana: 1.0, cherry: 5.0} taxed = prices.transform_values do |v| round(v * 1.08, 2) end # {apple: 1.08, banana: 0.54, cherry: 2.7} # Stringify all values stringified = prices.transform_values do |v| v.to_s end # {apple: "1.0", banana: "0.5", cherry: "2.5"} ``` --- ### `.transform_keys do |k| ... end` Return a new hash with transformed keys and unchanged values. ```ruby data = {first_name: "Alice", last_name: "Smith"} upcased = data.transform_keys do |k| k.upcase end # {FIRST_NAME: "Alice", LAST_NAME: "Smith"} # Convert symbol-style keys to string format normalized = data.transform_keys do |k| k.gsub("_", "-") end # {"first-name": "Alice", "last-name": "Smith"} ``` --- ### `.deep_merge(other)` Recursively merge `other` into the hash. Where both hashes have the same key and both values are themselves hashes, the merge recurses rather than overwriting. Returns a new hash; the originals are not mutated. ```ruby defaults = { db: {host: "localhost", port: 5432, pool: 5}, app: {debug: false, log_level: "info"}, cache: {ttl: 300} } overrides = { db: {host: "prod-db.example.com"}, app: {debug: true} } config = defaults.deep_merge(overrides) # { # db: {host: "prod-db.example.com", port: 5432, pool: 5}, # app: {debug: true, log_level: "info"}, # cache: {ttl: 300} # } puts config["db"]["host"] # prod-db.example.com puts config["db"]["port"] # 5432 ← kept from defaults puts config["app"]["debug"] # true puts config["app"]["log_level"] # info ← kept from defaults ``` Contrast with `.merge` (shallow) and `|` (shallow): ```ruby # shallow merge — nested hash is replaced entirely a = {db: {host: "localhost", port: 5432}} b = {db: {host: "prod"}} puts (a | b)["db"]["port"] # nil — port was lost # deep merge — nested hash is merged recursively puts a.deep_merge(b)["db"]["port"] # 5432 — port preserved ``` --- # DateTime Methods ## `now()` Current date and time as a DateTime object ```ruby puts now() → 2026-04-02 06:21:00.946891 ``` ## `today()` Today's date at midnight ```ruby puts today() → 2026-04-02 00:00:00 ``` ## `date_parse(str, fmt)` Parse a string into a DateTime. Default format is "%Y-%m-%d". Pass a custom format as the second argument ```ruby puts date_parse("02/04/2026", "%d/%m/%Y") → 2026-04-02 00:00:00 ``` ## `date_from(year, month, day, hour, minute, second)` Build a DateTime from components. Hour, minute, and second default to 0. ```ruby puts date_from(2026, 04, 02, 13, 25, 0) → 2026-04-02 13:25:00 ``` ## `.year` Integer year. ```ruby puts now().year → 2026 ``` ## .month Integer month. ```ruby puts now().month → 4 ``` ## `.day` Integer day of month. ```ruby puts now().day → 2 ``` ## `.hour` Integer hour (0–23). ```ruby puts now().day → 14 ``` ## `.minute` Integer minute (0–23). ```ruby puts now().minute → 30 ``` ## `.second` Integer second (0–23). ```ruby puts now().second → 40 ``` ## `.format(fmt)` Format as a string using strftime codes. Default format is "%Y-%m-%d %H:%M:%S". ```ruby puts now().format("%d/%m/%Y") → 02/04/2026 ``` ## `.add_days(n)` Return a new DateTime n days in the future. Negative values go backward. ```ruby puts now().add_days(5) → 2026-04-07 22:59:30.275494 ``` ## `.add_minutes(n)` Return a new DateTime n minutes in the future. ```ruby puts now().add_minutes(5) → 2026-04-02 23:08:00.487584 ``` ## `.diff_days(other)` Number of days between two DateTime values. Always positive. ```ruby puts now().diff_days(date_parse("1977-11-22", "%Y-%m-%d")) → 17664 ``` ## `.diff_seconds(other)` Number of seconds between two DateTime values. Always positive. ```ruby puts now().diff_seconds(date_parse("1977-11-22", "%Y-%m-%d")) → 1526252921 ``` ## `.weekday` Day of week as integer. 0 = Monday, 6 = Sunday. ```ruby puts now().weekday → 4 ``` ## `.is_before(other)` True if this DateTime is earlier than other. ```ruby puts now().is_before(date_parse("1977-11-22", "%Y-%m-%d")) → false ``` ## `.is_after(other)` True if this DateTime is later than other. ```ruby puts now().is_after(date_parse("1977-11-22", "%Y-%m-%d")) → true ``` ## `.timestamp` Unix timestamp as a Float. Seconds since 1970-01-01 00:00:00 UTC. ```ruby puts now().timestamp → 1775275966.768478 ``` --- ## Date Arithmetic *(introduced in v1.15)* Date objects support `+` and `-` with integers (days) and comparison operators. ### `date + n` / `date - n` Add or subtract a number of days. Returns a new date object. ```ruby d = date_from(2025, 6, 1) puts (d + 30).format("%Y-%m-%d") # 2025-07-01 puts (d - 7).format("%Y-%m-%d") # 2025-05-25 ``` ### `date_a - date_b` Subtract two dates to get the difference in days as an integer. ```ruby d1 = date_from(2025, 6, 1) d2 = date_from(2025, 7, 1) puts d2 - d1 # 30 ``` ### Comparison operators `<`, `>`, `<=`, `>=`, `==` all work between date objects. ```ruby d = date_from(2025, 6, 1) puts d < date_from(2025, 12, 31) # true puts d == date_from(2025, 6, 1) # true puts d > date_from(2024, 1, 1) # true ``` --- # Regular Expressions ## `.match(pattern)` Return the first match object for pattern, or nil. ```ruby s = "The password is 123x123".match("(?<=The password is )\\S+") → 123x123 ``` ## `.match_all(pattern)` Return a vector of all matches. ```ruby puts "4 languages, 1 Frankie".match_all("\\d+") → [4, 1] ``` ## `.matches?(pattern)` True if pattern matches anywhere. ```ruby puts "4 languages, 1 Frankie".matches("\\d+") → true ``` ## `=~` Match operator. Returns the position of the first match, or nil. ```ruby puts "frankie123" =~ "\\d+" → 7 ``` ## `.sub(pattern, replacement)` Replace the first regex match. ```ruby puts "Frank1e".sub("\\d", "i") → Frankie ``` ## `.gsub(pattern, replacement)` Replace all regex matches with a fixed string. ```ruby puts "Frank1e 1s great!".gsub("\\d", "i") → Frankie is great! ``` ## `.gsub(pattern) do |m| … end` Replace all matches — block receives each match and returns its replacement. ```ruby puts "Round 1 of 3 starts in 5 seconds".gsub("\\d+") do |m| n = m.to_i suffix = if n == 1 then "st" elsif n == 2 then "nd" elsif n == 3 then "rd" else "th" end m + suffix end → Round 1st of 3rd starts in 5th seconds ``` ## `sub(str, pattern, rep)` Replace first match. ```ruby puts sub("Frakie is good", "good", "great!") → Frankie is great! ``` ## `gsub(str, pattern, rep)` Replace all. ```ruby puts gsub("Ruby is great, Ruby is slick!", "Ruby", "Frankie") → Frankie is great, Frankie is slick! ``` ## `match(str, pattern)` First match. ```ruby s = match("Frankie 101 and Frankie 102", "\\d+") puts s[0] → 101 ``` ## `match_all(str, pattern)` All matches. ```ruby s = match_all("Frankie 101 and Frankie 102", "\\d+") puts s → [101, 102] ``` ## `matches(str, pattern)` Boolean test. ```ruby puts matches("Frankie", "\\d+") → false ``` --- ## Standalone functions ### `sub(str, pattern, rep)` Replace first match ```ruby puts sub("Fran123ie" , "\\d+", "k") → Frankie ``` ### `gsub(str, pattern, rep)` Replace all ```ruby puts gsub("Frank123ie 1is ru3nn1ing" , "\\d+", "") → Frankie is running ``` ### `match(str, pattern)` First match. ```ruby matched = match("The password is 123x123", "(?<=The password is )\\S+") puts matched[0] → 123x123 ``` ### `match_all(str, pattern)` All matches ```ruby matched = "4 languages, 1 Frankie".match_all("\\d+") puts matched → [4, 1] ``` ### `matches(str, pattern)` Boolean test ```ruby puts matches("4 languages, 1 Frankie", "\\d+") → true ``` --- # File I/O ## Overview Frankie has a complete file I/O library built on Python's standard `open()` — zero external dependencies. All functions are available without any import. --- ## Reading Files ### `file_read(path)` Read entire file as a string ```ruby content = file_read("data.txt") puts content ``` ### `file_lines(path)` Read file as a vector of lines Strips trailing newlines from each line. ```ruby lines = file_lines("data.csv") puts lines.length → number of lines puts lines[0] → first line lines.each do |line| puts line end ``` ### `file_read_base64(path)` *(v1.21)* Read a binary file, Base64-encoded `file_read` is text-mode and will corrupt binary data (images, audio, zip files). Use `file_read_base64` for anything that isn't text — [`load_image`](../stitches/frankiecanvas.md#load_image-path-v121) in `frankiegame`/`frankiecanvas` uses it internally for PNG/JPEG/GIF sprites. ```ruby data = file_read_base64("sprite.png") puts data.length # Base64 text, safe to embed in a data: URL or JSON ``` Both `file_read` and `file_lines` (and `file_read_base64`) raise `FileNotFoundError` if the file doesn't exist — use `rescue` to handle it gracefully: ```ruby begin content = file_read("config.json") rescue FileNotFoundError e puts "Config missing — using defaults" content = "{}" end ``` --- ## Writing Files ### `file_write(path, content)` Write string to file (overwrites) Creates the file if it doesn't exist. Overwrites silently if it does. ```ruby file_write("output.txt", "Hello, Frankie!\n") file_write("report.csv", "name,score\nAlice,95\nBob,87\n") ``` ### `file_append(path, content)` Append to file Adds content to the end of the file without overwriting. ```ruby file_write("log.txt", "Session started\n") file_append("log.txt", "User logged in\n") file_append("log.txt", "User logged out\n") puts file_read("log.txt") → Session started → User logged in → User logged out ``` --- ## File Management ### `file_exists(path)` Check if a file exists Returns `true` or `false`. Never raises. ```ruby if file_exists("config.json") config = json_read("config.json") else config = {host: "localhost", port: 3000} end ``` ### `file_delete(path)` Delete a file Returns `false` if the file doesn't exist — deleting a missing file is a no-op, not an error. ```ruby file_delete("temp.txt") → true if deleted, false if missing file_delete("/tmp/scratch.json") → safe to call even if missing ``` ### `file_copy(src, dst)` Copy a file Returns the destination path on success. Raises `FileNotFoundError` if source is missing. ```ruby file_copy("data.csv", "data.csv.bak") ``` ### `file_rename(src, dst)` Rename or move a file Raises `FileNotFoundError` if source is missing. ```ruby file_rename("draft.txt", "final.txt") file_rename("output.csv", "/tmp/output.csv") → move to different directory ``` --- ## Directory Operations ### `file_mkdir(path)` Create a directory Creates all intermediate directories automatically (like `mkdir -p`). ```ruby file_mkdir("data/reports/2024") → creates all three levels ``` ### `dir_exists(path)` Check if a directory exists ```ruby if not dir_exists("output") file_mkdir("output") end ``` ### `dir_list(path)` List directory contents Returns a sorted vector of filenames (not full paths). Defaults to current directory. ```ruby entries = dir_list("data") puts entries → ["config.json", "users.csv", "report.txt"] # List current directory puts dir_list() ``` --- ## File Handles For fine-grained control, open a file as a handle with `file_open`: ```ruby f = file_open("output.txt", "w") f.write("line one\n") f.write("line two\n") f.close ``` Modes: `"r"` (read), `"w"` (write/overwrite), `"a"` (append). Always close the handle when done. Use `ensure` to guarantee it: ```ruby f = file_open("data.txt", "r") begin content = f.read puts content ensure f.close end ``` --- ## Consistent Error Behaviour | Function | Missing file behaviour | |---|---| | `file_read(path)` | Raises `FileNotFoundError` | | `file_read_base64(path)` | Raises `FileNotFoundError` | | `file_lines(path)` | Raises `FileNotFoundError` | | `file_copy(src, dst)` | Raises `FileNotFoundError` (src must exist) | | `file_rename(src, dst)` | Raises `FileNotFoundError` (src must exist) | | `file_delete(path)` | Returns `false` — idempotent | | `file_exists(path)` | Returns `false` — that's what it tests | | `dir_exists(path)` | Returns `false` — same | --- ## Quick Reference | Function | Description | |---|---| | `file_read(path)` | Read entire file as string | | `file_read_base64(path)` | Read binary file, Base64-encoded (v1.21) | | `file_lines(path)` | Read file as vector of lines | | `file_write(path, str)` | Write string to file (overwrites) | | `file_append(path, str)` | Append string to file | | `file_exists(path)` | True if file exists | | `file_delete(path)` | Delete file — returns false if missing | | `file_copy(src, dst)` | Copy file | | `file_rename(src, dst)` | Rename or move file | | `file_open(path, mode)` | Open file handle (`"r"`, `"w"`, `"a"`) | | `file_mkdir(path)` | Create directory (and parents) | | `dir_exists(path)` | True if directory exists | | `dir_list(path)` | Sorted vector of filenames in directory | | `path_join(*parts)` | Join path segments with the OS separator | | `path_dirname(path)` | Parent directory of a path | | `path_basename(path)` | Filename component of a path | | `path_extname(path)` | File extension including the dot | | `path_stem(path)` | Filename without the extension | | `path_absolute(path)` | Resolve to an absolute path | --- ## Path Helpers *(introduced in v1.15)* Pure path manipulation — no filesystem access required. ### `path_join(*parts)` Join one or more path segments with the OS separator. Handles trailing slashes correctly. ```ruby puts path_join("home", "alice", "docs") # home/alice/docs puts path_join("/usr", "local", "bin") # /usr/local/bin ``` ### `path_dirname(path)` Return the parent directory of the given path. ```ruby puts path_dirname("/home/alice/report.txt") # /home/alice puts path_dirname("data/results.csv") # data ``` ### `path_basename(path)` Return the filename component (last segment) of the path. ```ruby puts path_basename("/home/alice/report.txt") # report.txt puts path_basename("data/results.csv") # results.csv ``` ### `path_extname(path)` Return the file extension including the leading dot. Returns an empty string if there is none. ```ruby puts path_extname("/home/alice/report.txt") # .txt puts path_extname("archive.tar.gz") # .gz puts path_extname("Makefile") # (empty string) ``` ### `path_stem(path)` Return the filename without the extension. ```ruby puts path_stem("/home/alice/report.txt") # report puts path_stem("archive.tar.gz") # archive.tar ``` ### `path_absolute(path)` Resolve a relative path to an absolute path based on the current working directory. ```ruby puts path_absolute("./data/db.sqlite") # /home/alice/myapp/data/db.sqlite puts path_absolute("../config.json") # /home/alice/config.json ``` --- ## Shell & Environment *(introduced in v1.16)* ### `shell(cmd)` Run an OS shell command and return a structured result hash. Uses `subprocess` internally — no shell injection surprises. | Field | Type | Description | |---|---|---| | `stdout` | string | Standard output from the command | | `stderr` | string | Standard error from the command | | `exit_code` | integer | Process exit code (`0` = success) | | `ok` | boolean | `true` when `exit_code == 0` | ```ruby result = shell("git log --oneline -5") if result["ok"] puts result["stdout"] else puts "git failed (exit #{result["exit_code"]}): #{result["stderr"]}" end # Capture command output into a variable branch = shell("git rev-parse --abbrev-ref HEAD")["stdout"].strip puts "Current branch: #{branch}" # Check for a program's existence if shell("which python3")["ok"] puts "python3 is available" end ``` --- ### `dotenv(path = ".env")` Load a `.env` file and merge its key/value pairs into the process environment (accessible via `env()`). Returns a hash of the keys that were loaded. ```ruby # Load the default .env file dotenv() # Load a specific file dotenv(".env.production") # The loaded vars are now available via env() puts env("DATABASE_URL") puts env("SECRET_KEY") ``` The `.env` file format: ```bash # .env — lines starting with # are comments, blank lines are ignored DATABASE_URL=postgres://localhost/myapp SECRET_KEY=changeme PORT=3000 ``` ```ruby # Inspect what was loaded loaded = dotenv(".env.staging") puts "Loaded #{loaded.keys.length} variables" loaded.each do |k, v| puts " #{k}=#{v}" end ``` Combined with `shell()`: ```ruby dotenv() # load .env first result = shell("pg_dump #{env("DATABASE_URL")} > backup.sql") if result["ok"] puts "Backup complete" else puts "Backup failed: #{result["stderr"]}" end ``` --- # Concurrency & Networking Introduced in **v1.17**, with TLS and UDP added in **v1.19**. Thread-pool mapping, raw TCP/UDP sockets, and WebSockets — all built on the Python standard library, zero external dependencies. --- ## `parallel_map` Thread-pool map for I/O-bound work: HTTP calls, shell commands, file reads. Runs the block across a pool of worker threads and returns results **in input order**. ```ruby urls = [ "https://api.example.com/a", "https://api.example.com/b", "https://api.example.com/c" ] pages = parallel_map(urls, workers: 8) do |u| http_get(u) end ``` - `workers:` defaults to `4`. - Results always come back in the same order as the input vector. - The first exception raised by any worker is re-raised. - An empty vector returns `[]` immediately. Because Frankie threads share one Python interpreter, `parallel_map` shines for **I/O-bound** work (waiting on the network or disk), not CPU-bound number crunching. ```ruby # Run several shell commands at once results = parallel_map(["ls", "date", "whoami"], workers: 3) do |cmd| shell(cmd)["stdout"] end ``` --- ## TCP Sockets ### `tcp_connect(host, port, timeout: nil, tls: false)` — client Opens a TCP connection and returns a socket object: ```ruby sock = tcp_connect("example.com", 7777, timeout: 5) sock.send_line("ping") puts sock.recv_line() puts sock.peer() # "93.184.216.34:7777" sock.close() ``` Pass `tls: true` for a certificate-verified TLS connection (v1.19), via Python's stdlib `ssl`: ```ruby sock = tcp_connect("example.com", 443, tls: true) sock.send_line("GET / HTTP/1.0\r\n\r\n") puts sock.recv_line() sock.close() ``` Server-side TLS stays on the wish list — `tcp_listen`/`tcp_serve` are plaintext only. ### Socket methods | Method | Description | |---|---| | `sock.send(s)` | Send a string — returns bytes sent | | `sock.send_line(s)` | Send a string followed by a newline | | `sock.recv(n)` | Receive up to `n` bytes as a string (default 4096) — `nil` when the peer closes | | `sock.recv_line()` | Receive until newline (exclusive) — `nil` when the peer closes | | `sock.peer()` | Remote end as `"host:port"` | | `sock.close()` | Close the connection | Use `send`/`recv(n)` for raw data, `send_line`/`recv_line` for line-based protocols. ### `tcp_listen(port, host: "0.0.0.0")` — manual server ```ruby server = tcp_listen(7777) client = server.accept() # blocks until a client connects msg = client.recv_line() client.send_line("got: #{msg}") client.close() server.close() ``` ### `tcp_serve(port) do |client| ... end` — threaded server loop One thread per client, sockets closed automatically when the block returns. Blocks forever (Ctrl+C to stop): ```ruby tcp_serve(7777) do |client| msg = client.recv_line() client.send_line("echo: #{msg}") end # 🧟 Frankie TCP server listening on 0.0.0.0:7777 ``` ### Example: a tiny client/server pair ```ruby # server.fk tcp_serve(7777) do |client| name = client.recv_line() client.send_line("Hello, #{name}!") end ``` ```ruby # client.fk sock = tcp_connect("localhost", 7777) sock.send_line("Frankie") puts sock.recv_line() # Hello, Frankie! sock.close() ``` --- ## UDP Sockets (v1.19) Connectionless datagrams — no handshake, no ordering guarantees, fire-and-forget or request/response as you like. ### `udp_listen(port, host: "0.0.0.0")` ```ruby sock = udp_listen(9999) msg = sock.recv() # blocks for the next datagram puts msg["data"] # the payload as a string puts msg["host"] # sender's address sock.send_to(msg["host"], msg["port"], "pong") sock.close() ``` ### `udp_send(host, port, message)` Fire-and-forget — opens a socket, sends one datagram, closes: ```ruby udp_send("127.0.0.1", 9999, "ping") ``` ### UDP socket methods | Method | Description | |---|---| | `sock.recv(n: 4096)` | Block for the next datagram → `{data:, host:, port:}` | | `sock.send_to(host, port, msg)` | Send a datagram to a specific address | | `sock.close()` | Close the socket | --- ## WebSockets (v1.18) + TLS (v1.19) Full WebSocket coverage lives on the [Web Server](webserver.md#websockets-v118) page — `app.websocket` for the server side, `ws_connect` for clients. Since v1.19, `ws_connect` also accepts `wss://` URLs for TLS-secured connections: ```ruby sock = ws_connect("wss://echo.example.com/socket") sock.send("hello") puts sock.recv() sock.close() ``` --- ## Error Handling Socket operations raise on failure — connection refused, timeouts, etc. Rescue them like any other error: ```ruby begin sock = tcp_connect("localhost", 9999, timeout: 2) rescue TimeoutError => e puts "Connection timed out: #{e}" rescue e puts "Could not connect: #{e}" end ``` --- ## Quick Reference | Function | Description | |---|---| | `parallel_map(vec, workers: 4) do \|x\| ... end` | Thread-pool map, results in input order | | `tcp_connect(host, port, timeout: nil, tls: false)` | Open a TCP connection — `tls: true` for TLS (v1.19) | | `tcp_listen(port, host: "0.0.0.0")` | Listen on a port; `.accept()` returns a client socket | | `tcp_serve(port) do \|client\| ... end` | Threaded accept loop, auto-closes clients | | `sock.send(s)` / `sock.send_line(s)` | Send a string (newline appended by `send_line`) | | `sock.recv(n)` / `sock.recv_line()` | Receive a string — `nil` when peer closes | | `sock.peer()` / `sock.close()` | Remote `"host:port"` / close the connection | | `udp_listen(port, host: "0.0.0.0")` | Bind a UDP socket (v1.19) | | `udp_send(host, port, msg)` | Fire-and-forget datagram (v1.19) | | `sock.recv(n)` / `sock.send_to(host, port, msg)` | UDP receive/send (v1.19) | | `ws_connect(url, timeout: nil)` | WebSocket client — `ws://` or `wss://` (v1.18 / TLS in v1.19) | --- # JSON & CSV ## Overview Frankie has built-in support for reading and writing both JSON and CSV — no external libraries, no imports required. J SON is handled with Python's `json` module; CSV with the standard `csv` module. Both are zero-dependency. --- ## JSON ### `json_write(path, data)` Write data to a JSON file Accepts any Frankie value — hash, vector, string, number. Returns `true` on success. ```ruby data = {name: "Alice", age: 30, scores: [95, 87, 92]} json_write("data.json", data) ``` Pass `true` as a third argument for pretty-printed output: ```ruby json_write("data.json", data, true) → produces: → { → "name": "Alice", → "age": 30, → "scores": [95, 87, 92] → } ``` ### `json_read(path)` Read a JSON file Returns the parsed value — a Hash, Vector, String, or number depending on the file content. Hash keys come back as strings regardless of how you wrote them. ```ruby data = json_read("data.json") puts data["name"] → Alice puts data["age"] → 30 puts data["scores"] → [95, 87, 92] ``` ### `json_parse(str)` Parse a JSON string Parses a JSON string directly without touching the filesystem. ```ruby raw = '{"host": "localhost", "port": 5432}' config = json_parse(raw) puts config["host"] → localhost puts config["port"] → 5432 ``` ### `json_encode(data)` Serialise to a JSON string *(preferred — introduced in v1.15)* The preferred name for `json_dump`. Accepts `pretty: true` for formatted output. ```ruby data = {name: "Alice", scores: [95, 87, 92]} puts json_encode(data) # {"name": "Alice", "scores": [95, 87, 92]} puts json_encode(data, pretty: true) # { # "name": "Alice", # "scores": [95, 87, 92] # } # Round-trip raw = json_encode([1, 2, 3]) back = json_parse(raw) puts back[1] # 2 ``` ### `json_dump(data)` Serialise to a JSON string Alias for `json_encode` — kept for backwards compatibility. Pass `true` for pretty output. ```ruby h = {name: "Alice", scores: [95, 87]} puts json_dump(h) # {"name": "Alice", "scores": [95, 87]} puts json_dump(h, true) # { # "name": "Alice", # "scores": [95, 87] # } ``` ### Round-trip Example ```ruby original = { user: "Alice", prefs: {theme: "dark", lang: "en"}, scores: [95, 87, 92] } json_write("/tmp/user.json", original, true) loaded = json_read("/tmp/user.json") puts loaded["user"] # Alice puts loaded.dig("prefs", "theme") # dark puts loaded["scores"][1] # 87 file_delete("/tmp/user.json") ``` ### Handling Missing Files ```ruby begin config = json_read("config.json") rescue FileNotFoundError e puts "No config found — using defaults" config = {host: "localhost", port: 3000} end ``` --- ## CSV ### `csv_write(path, data)` Write data to a CSV file Accepts a vector of hashes (one hash per row) or a vector of vectors. Column headers are inferred from the first hash's keys. ```ruby employees = [ {name: "Alice", dept: "Engineering", salary: 95000}, {name: "Bob", dept: "Marketing", salary: 72000}, {name: "Carol", dept: "Finance", salary: 88000} ] csv_write("employees.csv", employees) ``` Produces: ``` name,dept,salary Alice,Engineering,95000 Bob,Marketing,72000 Carol,Finance,88000 ``` Pass explicit headers to control column order: ```ruby csv_write("employees.csv", employees, ["name", "salary", "dept"]) ``` ### `csv_read(path)` Read a CSV file Returns a vector of hashes. The first row is treated as headers by default. ```ruby rows = csv_read("employees.csv") puts rows.length # 3 puts rows[0]["name"] # Alice puts rows[0]["salary"] # 95000 rows.each do |r| puts "#{r["name"]} — #{r["dept"]}" end ``` Pass `false` to skip header interpretation — returns a vector of vectors instead: ```ruby rows = csv_read("data.csv", false) puts rows[0] → first row as a vector ``` ### `csv_parse(text)` Parse a CSV string Parses CSV content directly from a string. ```ruby raw = "name,score\nAlice,95\nBob,87\nCarol,92\n" rows = csv_parse(raw) puts rows[0]["name"] → Alice puts rows[1]["score"] → 87 ``` ### `csv_dump(data)` Serialise to a CSV string ```ruby data = [ {city: "Lima", pop: 10000000}, {city: "Cusco", pop: 430000} ] puts csv_dump(data) # city,pop # Lima,10000000 # Cusco,430000 ``` --- ## Quick Reference | Function | Description | |---|---| | `json_write(path, data)` | Write data to JSON file | | `json_write(path, data, true)` | Write pretty-printed JSON | | `json_read(path)` | Read and parse JSON file | | `json_parse(str)` | Parse JSON string → value | | `json_encode(data)` | Serialise value → JSON string (preferred) | | `json_encode(data, pretty: true)` | Pretty-printed JSON string | | `json_dump(data)` | Serialise value → JSON string (alias for `json_encode`) | | `json_dump(data, true)` | Pretty-printed JSON string | | `csv_write(path, data)` | Write vector of hashes to CSV | | `csv_write(path, data, headers)` | Write with explicit column order | | `csv_read(path)` | Read CSV → vector of hashes | | `csv_read(path, false)` | Read CSV → vector of vectors (no headers) | | `csv_parse(str)` | Parse CSV string → vector of hashes | | `csv_dump(data)` | Serialise to CSV string | --- # DateTime ## Overview Frankie has a built-in DateTime type for working with dates and times — no external libraries required. DateTime objects are created by functions like `now()`, `today()`, and `date_parse()`, and support arithmetic, formatting, comparison, and field access. --- ## Creating DateTime Values ### `now()` Current date and time ```ruby dt = now() puts dt → Date(2024-03-15 14:23:07.123456) ``` ### `today()` Today at midnight ```ruby d = today() puts d.year → 2024 puts d.month → 3 puts d.day → 15 ``` ### `date_parse(str, fmt)` Parse a string Default format is `"%Y-%m-%d"`. Pass a custom format string as the second argument. ```ruby d = date_parse("2024-03-15") puts d.year → 2024 puts d.month → 3 puts d.day → 15 # Custom format d2 = date_parse("15/03/2024", "%d/%m/%Y") puts d2.year → 2024 d3 = date_parse("March 15, 2024", "%B %d, %Y") puts d3.month → 3 ``` ### `date_from(year, month, day, hour, minute, second)` Build from components Hour, minute, and second default to 0. ```ruby d = date_from(2024, 3, 15) puts d → Date(2024-03-15 00:00:00) dt = date_from(2024, 3, 15, 14, 30, 0) puts dt → Date(2024-03-15 14:30:00) ``` --- ## Accessing Fields ```ruby dt = date_from(2024, 3, 15, 14, 30, 45) puts dt.year → 2024 puts dt.month → 3 puts dt.day → 15 puts dt.hour → 14 puts dt.minute → 30 puts dt.second → 45 ``` --- ## Formatting Use `strftime` format codes: ```ruby dt = date_from(2024, 3, 15, 14, 30, 0) puts dt.format("%Y-%m-%d") → 2024-03-15 puts dt.format("%d/%m/%Y") → 15/03/2024 puts dt.format("%B %d, %Y") → March 15, 2024 puts dt.format("%A") → Friday puts dt.format("%H:%M:%S") → 14:30:00 puts dt.format("%Y-%m-%d %H:%M:%S") → 2024-03-15 14:30:00 puts dt.format("%d %b %Y %I:%M %p") → 15 Mar 2024 02:30 PM ``` ### Common Format Codes | Code | Meaning | Example | |---|---|---| | `%Y` | 4-digit year | `2024` | | `%m` | Month (01–12) | `03` | | `%d` | Day (01–31) | `15` | | `%H` | Hour 24h (00–23) | `14` | | `%I` | Hour 12h (01–12) | `02` | | `%M` | Minute (00–59) | `30` | | `%S` | Second (00–59) | `00` | | `%A` | Full weekday name | `Friday` | | `%a` | Short weekday name | `Fri` | | `%B` | Full month name | `March` | | `%b` | Short month name | `Mar` | | `%p` | AM/PM | `PM` | --- ## Arithmetic ### `.add_days(n)` Add days Returns a new DateTime. Negative values subtract. ```ruby d = date_from(2024, 3, 15) puts d.add_days(7).format("%Y-%m-%d") # 2024-03-22 puts d.add_days(-1).format("%Y-%m-%d") # 2024-03-14 puts d.add_days(30).format("%Y-%m-%d") # 2024-04-14 ``` ### `.add_hours(n)` Add hours ```ruby dt = date_from(2024, 3, 15, 10, 0, 0) puts dt.add_hours(5).format("%H:%M") # 15:00 puts dt.add_hours(48).format("%Y-%m-%d %H:%M") # 2024-03-17 10:00 ``` ### `.add_minutes(n)` Add minutes ```ruby dt = date_from(2024, 3, 15, 14, 45, 0) puts dt.add_minutes(20).format("%H:%M") # 15:05 puts dt.add_minutes(-30).format("%H:%M") # 14:15 ``` --- ## Comparison ### `.is_before(other)` / `.is_after(other)` ```ruby a = date_from(2024, 1, 1) b = date_from(2024, 6, 1) puts a.is_before(b) # true puts a.is_after(b) # false puts b.is_after(a) # true ``` --- ## Difference ### `.diff_days(other)` Days between two dates ```ruby start_date = date_from(2024, 1, 1) end_date = date_from(2024, 3, 15) puts start_date.diff_days(end_date) # 74 ``` ### `.diff_seconds(other)` Seconds between two datetimes ```ruby a = date_from(2024, 3, 15, 9, 0, 0) b = date_from(2024, 3, 15, 11, 30, 0) puts a.diff_seconds(b) # 9000 (2.5 hours) ``` --- ## Weekday ### `.weekday`\\Day of week as integer Returns 0 (Monday) through 6 (Sunday). ```ruby d = date_from(2024, 3, 15) # a Friday puts d.weekday # 4 days = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"] puts days[d.weekday] # Friday ``` --- ## Unix Timestamp ### `.timestamp` Seconds since epoch ```ruby dt = now() puts dt.timestamp # e.g. 1710507787.123456 ``` --- ## Quick Reference | Function / Method | Description | |---|---| | `now()` | Current date and time | | `today()` | Today at midnight | | `date_parse(str, fmt)` | Parse string → DateTime | | `date_from(y, m, d, h, min, s)` | Build from components | | `.year` `.month` `.day` | Date components | | `.hour` `.minute` `.second` | Time components | | `.format(fmt)` | Format with strftime codes | | `.add_days(n)` | Add n days (negative to subtract) | | `.add_hours(n)` | Add n hours | | `.add_minutes(n)` | Add n minutes | | `.diff_days(other)` | Days between two dates | | `.diff_seconds(other)` | Seconds between two datetimes | | `.weekday` | 0=Monday … 6=Sunday | | `.is_before(other)` | True if earlier | | `.is_after(other)` | True if later | | `.timestamp` | Unix timestamp as float | --- # HTTP Client ## Overview Frankie has a built-in HTTP client for making GET, POST, PUT, and DELETE requests — no external libraries, no imports. Built on Python's `urllib`, it handles JSON automatically and supports custom headers. --- ## Making Requests ### `http_get(url)` GET request ```ruby resp = http_get("https://api.example.com/users") puts resp.status → 200 puts resp.body → raw response body string ``` ### `http_post(url, data)` POST request Pass a hash to send as JSON, or a string for plain text. ```ruby # Send JSON resp = http_post("https://api.example.com/users", { name: "Alice", email: "alice@example.com" }) puts resp.status → 201 ``` ### `http_put(url, data)` PUT request ```ruby resp = http_put("https://api.example.com/users/42", { name: "Alice Updated" }) puts resp.status → 200 ``` ### `http_delete(url)` DELETE request ```ruby resp = http_delete("https://api.example.com/users/42") puts resp.status → 204 ``` --- ## The Response Object Every HTTP function returns an `HTTPResponse` with these fields and methods: | Property / Method | Type | Description | |---|---|---| | `.status` | Integer | HTTP status code | | `.body` | String | Raw response body | | `.headers` | Hash | Response headers | | `.json()` | Hash / Vector | Parse body as JSON | | `.ok()` | Boolean | True if status is 2xx | ```ruby resp = http_get("https://api.example.com/data") puts resp.status → 200 puts resp.ok() → true puts resp.headers["Content-Type"] # application/json # Parse JSON body data = resp.json() puts data["name"] ``` --- ## Custom Headers Pass a hash of headers as the last argument to any function. ```ruby # Bearer token auth resp = http_get( "https://api.example.com/protected", {"Authorization": "Bearer your_token_here"} ) # Multiple headers resp = http_post( "https://api.example.com/data", {value: 42}, { "Authorization": "Bearer token", "X-Request-ID": "abc-123" } ) ``` When you pass a hash as `data`, Frankie automatically sets `Content-Type: application/json`. You don't need to set it manually. --- ## Checking Status ```ruby resp = http_get("https://api.example.com/resource") if resp.ok() data = resp.json() puts data["result"] else puts "Error #{resp.status}: #{resp.body}" end ``` Common status codes: | Code | Meaning | |---|---| | `200` | OK | | `201` | Created | | `204` | No Content | | `400` | Bad Request | | `401` | Unauthorized | | `403` | Forbidden | | `404` | Not Found | | `500` | Internal Server Error | --- ## URL Utilities ### `url_encode(hash)` Encode a hash as a query string ```ruby params = {page: 1, limit: 20, sort: "name"} puts url_encode(params) # page=1&limit=20&sort=name # Append to URL manually base = "https://api.example.com/users" resp = http_get("#{base}?#{url_encode(params)}") ``` ### `url_decode(str)` Decode a query string into a hash ```ruby qs = "page=1&limit=20&sort=name" params = url_decode(qs) puts params["page"] # 1 puts params["sort"] # name ``` --- ## Error Handling HTTP errors (4xx, 5xx) are returned as responses with the corresponding status code — they do not raise exceptions. Network errors (no connection, timeout, DNS failure) do raise `RuntimeError`. ```ruby # HTTP error — returns a response, no raise resp = http_get("https://api.example.com/missing") puts resp.status # 404 puts resp.body # error body from server # Network error — raises begin resp = http_get("https://does-not-exist.invalid/") rescue RuntimeError e puts "Network error: #{e}" end ``` --- ## Quick Reference | Function | Description | |---|---| | `http_get(url)` | GET request | | `http_get(url, headers)` | GET with custom headers | | `http_post(url, data)` | POST — hash sends as JSON | | `http_post(url, data, headers)` | POST with custom headers | | `http_put(url, data)` | PUT request | | `http_put(url, data, headers)` | PUT with custom headers | | `http_delete(url)` | DELETE request | | `http_delete(url, headers)` | DELETE with custom headers | | `url_encode(hash)` | Hash → query string | | `url_decode(str)` | Query string → hash | | `resp.status` | HTTP status code | | `resp.body` | Raw response string | | `resp.headers` | Response headers hash | | `resp.json()` | Parse body as JSON | | `resp.ok()` | True if 2xx status | --- # Database Access (SQLite) Frankie has built-in SQLite support via `db_open()` — zero external dependencies, works everywhere Python does. --- ## `Opening a Database` ```ruby # In-memory database (great for testing) db = db_open(":memory:") # File-based database (persists to disk) db = db_open("myapp.db") db = db_open("/path/to/data.db") ``` --- ## `Creating Tables` ```ruby db.exec("CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, email TEXT UNIQUE, age INTEGER )") ``` Use triple-quoted strings for multi-line SQL: ```ruby sql = """ CREATE TABLE IF NOT EXISTS products ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, price REAL NOT NULL, stock INTEGER DEFAULT 0 ) """ db.exec(sql) ``` --- ## Inserting Data ### `Convenience insert with a hash` ```ruby db.insert("users", {name: "Alice", email: "alice@example.com", age: 30}) db.insert("users", {name: "Bob", email: "bob@example.com", age: 25}) ``` ### `Raw SQL with `?` placeholders (safe from SQL injection)` ```ruby db.exec("INSERT INTO users (name, email, age) VALUES (?, ?, ?)", ["Carol", "carol@example.com", 28]) ``` ### `Bulk insert` ```ruby rows = [ {name: "Dave", email: "dave@x.com", age: 35}, {name: "Eve", email: "eve@x.com", age: 29}, {name: "Frank", email: "frank@x.com", age: 42} ] db.insert_many("users", rows) ``` ### `Getting the new row ID` ```ruby id = db.insert("users", {name: "Grace", email: "g@x.com", age: 31}) puts "New user ID: #{id}" # or db.insert("users", {name: "Hector", email: "h@x.com", age: 27}) puts "Last ID: #{db.last_id}" ``` --- ## Querying Data ### `Get all rows from a table` ```ruby users = db.find_all("users") users.each do |u| puts "#{u["name"]} (#{u["age"]})" end ``` ### `Filter by conditions (hash → AND clauses)` ```ruby devs = db.find("users", {department: "Engineering"}) puts "Engineers: #{devs.length}" ``` ### `Find a single row (returns nil if not found)` ```ruby alice = db.find_one("users", {name: "Alice"}) if alice != nil puts "Found: #{alice["name"]}, age #{alice["age"]}" end ``` ### `Raw SQL queries` ```ruby # Parameterised — always use ? placeholders for user input results = db.query( "SELECT name, age FROM users WHERE age > ? ORDER BY age DESC", [25] ) results.each do |row| puts "#{row["name"]}: #{row["age"]}" end ``` ### `Single-row raw query` ```ruby row = db.query_one("SELECT COUNT(*) AS n, AVG(age) AS avg FROM users") puts "Count: #{row["n"]}, Avg age: #{row["avg"]}" ``` --- ## `Counting Rows` ```ruby puts db.count("users") # all rows puts db.count("users", {department: "Finance"}) # filtered ``` --- ## `Updating Data` ```ruby updated = db.update("users", {age: 31}, {name: "Alice"}) puts "Updated #{updated} row(s)" # Raw SQL update db.exec("UPDATE users SET age = age + 1 WHERE department = ?", ["Engineering"]) ``` --- ## `Deleting Data` ```ruby deleted = db.delete("users", {name: "Bob"}) puts "Deleted #{deleted} row(s)" # Raw SQL delete db.exec("DELETE FROM users WHERE age > ?", [60]) ``` --- ## `Transactions` Wrap multiple operations in a transaction — all succeed or all roll back: ```ruby db.transaction do db.insert("accounts", {owner: "Alice", balance: 1000}) db.insert("accounts", {owner: "Bob", balance: 500}) end # Transfer with rollback on error begin db.transaction do db.exec("UPDATE accounts SET balance = balance - 100 WHERE owner = ?", ["Alice"]) db.exec("UPDATE accounts SET balance = balance + 100 WHERE owner = ?", ["Bob"]) # If either fails, both roll back end puts "Transfer complete" rescue e puts "Transfer failed: #{e}" end ``` --- ## `Schema Introspection` ```ruby puts db.tables # ["users", "products", ...] cols = db.columns("users") cols.each do |col| puts "#{col["name"]} (#{col["type"]})" end ``` --- ## `Combining with Frankie's Stats` Query results are vectors of hashes — pipe them straight into stdlib functions: ```ruby rows = db.query("SELECT salary FROM employees") salaries = rows.map do |r| r["salary"] end puts mean(salaries) # average salary puts stdev(salaries) # standard deviation puts max(salaries) # top salary # Or filter with select senior_salaries = rows.select do |r| r["salary"] > 100000 end.map do |r| r["salary"] end puts "Senior mean: #{mean(senior_salaries)}" ``` --- ## `Closing the Connection` ```ruby db.close ``` Always close when done. In-memory databases are destroyed on close. --- ## `Full API Reference` | Method | Description | |---|---| | `db_open(path)` | Open/create DB. `":memory:"` for in-memory. | | `db.exec(sql, params)` | Run DDL/DML statement. Returns row count. | | `db.query(sql, params)` | SELECT → vector of hashes | | `db.query_one(sql, params)` | SELECT → first hash or nil | | `db.insert(table, hash)` | Insert a row. Returns new row id. | | `db.insert_many(table, rows)` | Bulk insert vector of hashes. | | `db.find_all(table)` | All rows as vector of hashes | | `db.find(table, where)` | Filtered rows (hash → AND) | | `db.find_one(table, where)` | First matching row or nil | | `db.update(table, data, where)` | Update matching rows. Returns count. | | `db.delete(table, where)` | Delete matching rows. Returns count. | | `db.count(table)` | Total row count | | `db.count(table, where)` | Filtered row count | | `db.last_id` | Rowid of last INSERT | | `db.tables` | List of table names | | `db.columns(table)` | Column info as vector of hashes | | `db.transaction do...end` | Atomic block — rollback on error | | `db.begin` | Begin explicit transaction | | `db.commit` | Commit current transaction | | `db.rollback` | Roll back current transaction | | `db.close` | Close the connection | --- ## `Notes` - Uses Python's built-in `sqlite3` — **no external dependencies** - All query results are **vectors of hashes** keyed by column name (strings) - Always use `?` placeholders for user data — never interpolate into SQL strings - `":memory:"` databases are perfect for testing and temporary work - File databases persist between program runs --- # Frankie Web Server Frankie ships a built-in HTTP web server in the style of Sinatra / Camping. Zero external dependencies — it runs on Python's standard library `http.server`. --- ## `Quick Start` ```ruby app = web_app() app.get("/") do |req| html_response("

Hello from Frankie! 🧟

") end app.run(3000) ``` ```bash frankiec run myapp.fk # 🧟 Frankie web server running on http://0.0.0.0:3000 ``` --- ## Routes Register routes with `.get`, `.post`, `.put`, `.delete`, `.patch`. Each takes a path pattern and a `do |req| ... end` block. The block receives a `FrankieRequest` and must return a response value. ```ruby app.get("/hello") do |req| response("Hello!") end app.post("/echo") do |req| response(req.body) end app.delete("/items/:id") do |req| response("Deleted #{req.params["id"]}") end ``` ### `Path Parameters` Use `:name` segments to capture parts of the URL: ```ruby app.get("/users/:id/posts/:slug") do |req| id = req.params["id"] slug = req.params["slug"] response("User #{id}, post #{slug}") end ``` ### `Query Parameters` ```ruby # GET /search?q=frankie&page=2 app.get("/search") do |req| q = req.query["q"] page = req.query["page"] response("q=#{q} page=#{page}") end ``` --- ## `Request Object` | Property | Type | Description | |-------------|--------|------------------------------------------------------| | `method` | String | `"GET"`, `"POST"`, `"PUT"`, `"DELETE"`, `"PATCH"` | | `path` | String | URL path, e.g. `"/users/42"` | | `params` | Hash | Path parameters, e.g. `{id: "42"}` | | `query` | Hash | Query-string parameters, e.g. `{page: "2"}` | | `headers` | Hash | HTTP request headers | | `body` | String | Raw request body | | `json` | Hash | Body parsed as JSON, or `nil` if not valid JSON | | `form` | Hash | Body parsed as `application/x-www-form-urlencoded` | | `cookies` | Hash | Incoming cookies | ### Query Parameter Helpers *(introduced in v1.15)* `req.query` values are always strings. These helpers parse and coerce them with a fallback default so route handlers stay clean. | Method | Returns | Notes | |---|---|---| | `req.query_int(key, default)` | Integer | Returns `default` if key is missing or not a valid integer | | `req.query_float(key, default)` | Float | Returns `default` if key is missing or not a valid float | | `req.query_bool(key, default)` | Boolean | `"true"`, `"1"`, `"yes"` → `true`; everything else → `false` | ```ruby app.get("/items") do |req| page = req.query_int("page", 1) per_page = req.query_int("per_page", 20) min_score = req.query_float("min_score", 0.0) show_all = req.query_bool("show_all", false) items = db.find_all("items") json_response({page: page, per_page: per_page, items: items}) end ``` --- ## Response Helpers | Function | Status | Content-Type | |-----------------------------------|--------|----------------------| | `response(body)` | 200 | text/plain | | `response(body, status)` | custom | text/plain | | `response(body, status, headers)` | custom | text/plain | | `html_response(html)` | 200 | text/html | | `html_response(html, status)` | custom | text/html | | `json_response(hash)` | 200 | application/json | | `json_response(hash, status)` | custom | application/json | | `redirect(location)` | 302 | — | | `redirect(location, status)` | custom | — | | `halt(status, body)` | custom | text/plain | Returning a plain string from the handler is also fine — it becomes a `200 text/plain` response automatically. Returning a hash or vector auto-converts to JSON. --- ## `JSON API` ```ruby # Receive JSON app.post("/api/users") do |req| data = req.json # parsed hash or nil if data == nil halt(400, "Expected JSON") else name = data["name"] json_response({id: 1, name: name}, 201) end end # Send JSON app.get("/api/info") do |req| json_response({version: "1.4", alive: true}) end ``` --- ## `Before / After Filters` Filters run before or after every matched route. ```ruby app.before do |req| puts "#{req.method} #{req.path}" end app.after do |req, res| puts " -> #{res.status}" end ``` `before` receives the request. `after` receives the request and the response. --- ## `Custom 404` ```ruby app.not_found do |req| html_response("

404

Nothing at #{req.path}

", 404) end ``` --- ## `Starting the Server` ```ruby app.run(3000) # listen on 0.0.0.0:3000 (default) app.run(8080) # custom port app.run(3000, "127.0.0.1") # localhost only ``` The server is multi-threaded (one thread per request) and blocks until Ctrl+C. --- ## Cookies and Sessions *(v1.13.1)* ### `Reading and Writing Cookies` Every request exposes its cookies as a hash via `req.cookies`. Every response can set a cookie via `resp.set_cookie(name, value, opts)`. ```ruby app.get("/prefs") do |req| theme = req.cookies["theme"] or "light" resp = html_response("

Theme: #{theme}

") resp.set_cookie("theme", theme, {max_age: 86400}) resp end ``` `set_cookie` options (all optional): | Option | Default | Description | |---|---|---| | `path` | `"/"` | Cookie scope path | | `http_only` | `true` | Hide from JavaScript | | `max_age` | `nil` | Expiry in seconds (omit for session cookie) | | `same_site` | `"Lax"` | CSRF protection (`"Strict"`, `"Lax"`, `"None"`) | ### `Cookie-Backed Sessions` `session(req, resp)` returns a `FrankieSession` — a hash-like object backed by a single JSON cookie (`_fk_session`). Read it, mutate it, and call `.save()` before returning the response. No server-side state, no database, no configuration. ```ruby app = web_app() app.get("/counter") do |req| resp = response("") s = session(req, resp) count = (s["count"] or 0) + 1 s["count"] = count s.save() html_response("You have visited #{count} time(s).") end app.post("/login") do |req| user = req.json["username"] resp = response("") s = session(req, resp) s["user"] = user s["logged_in_at"] = now() s.save() redirect("/dashboard") end app.get("/logout") do |req| resp = response("") s = session(req, resp) s.clear() s.save() redirect("/") end app.run() ``` **Session API:** | Method | Description | |---|---| | `s["key"]` | Read value (`nil` if missing) | | `s["key"] = value` | Write value | | `s.has_key?(key)` | Check existence | | `s.keys` | All session keys | | `s.delete(key)` | Remove one key | | `s.clear()` | Remove all keys | | `s.save()` | Write cookie to response — must be called before returning | **Important:** the session cookie is `HttpOnly` and `SameSite=Lax`. It is **not encrypted** — store user IDs, not passwords or secrets. --- ## Concurrency *(v1.14)* ### `spawn { }` Background Blocks `spawn` runs a block in a background thread and returns immediately — the rest of the handler keeps going without waiting for the block to finish. Use it for work that shouldn't delay the response: sending emails, writing logs, hitting a slow external API, processing an uploaded file. ```ruby app.post("/register") do |req| user = req.json # Respond right away — email sends in the background spawn do send_welcome_email(user["email"]) end json_response({status: "registered"}, 201) end ``` `spawn` works anywhere in a Frankie program, not just inside route handlers: ```ruby spawn do report = build_monthly_report(data) file_write("report.json", json_dump(report)) end puts "Report building in background..." ``` Spawned blocks capture variables by value at spawn time. Mutations inside the block do not affect the outer scope. --- ### `timeout(n) { }` Time-Bounded Execution `timeout(seconds)` runs a block and raises `TimeoutError` if it takes longer than `n` seconds. Wrap it in `begin/rescue` to handle the failure gracefully. Essential any time you call an external service that might hang. ```ruby app.get("/weather") do |req| begin data = timeout(5) do http_get("https://api.weather.example.com/current") end json_response(data) rescue TimeoutError json_response({error: "weather service unavailable"}, 503) end end ``` Use a short timeout and a sensible fallback — a hung external call should never take your whole server down with it: ```ruby app.get("/profile/:id") do |req| user = db.find("users", {id: req.params["id"]}) # Try to enrich with remote data, fall back to basics if slow begin extra = timeout(2) do http_get("https://profile-api.example.com/#{user["id"]}") end user["bio"] = extra["bio"] rescue TimeoutError user["bio"] = "" end json_response(user) end ``` --- ### `Async Routes` app.get_async Regular routes are synchronous — one slow handler blocks others waiting in queue. Async routes are non-blocking: while one handler is waiting on I/O, another request can run. Use `await` inside the block to pause without blocking. ```ruby app = web_app() # Both fetches run while other requests are served freely app.get_async("/dashboard") do |req| posts = await http_get("https://api.example.com/posts") alerts = await http_get("https://api.example.com/alerts") json_response({posts: posts, alerts: alerts}) end app.run(3000) ``` All five HTTP methods have async variants: ```ruby app.get_async("/items") do |req| ... end app.post_async("/items") do |req| ... end app.put_async("/items/:id") do |req| ... end app.delete_async("/items/:id") do |req| ... end app.patch_async("/items/:id") do |req| ... end ``` Use async routes when your handler spends most of its time waiting — on a database, an HTTP call, a file read. For CPU-heavy work, `spawn` is the better fit. --- ## Middleware *(v1.14)* `app.use` registers a middleware layer that wraps every request. Middleware receives the request and a `next_fn` — call `next_fn.(req)` to pass control to the next layer (and eventually the route handler). Return a response directly to short-circuit the chain without reaching the route. Middleware layers run in registration order, so register them before your routes. ### `Logging` ```ruby app.use do |req, next_fn| puts "→ #{req.method} #{req.path}" resp = next_fn.(req) puts "← #{resp.status}" resp end ``` ### `Auth guard` ```ruby app.use do |req, next_fn| if req.path.start_with?("/admin") key = req.headers["X-Api-Key"] if key != env("API_KEY") halt(401, "Unauthorized") end end next_fn.(req) end app.get("/admin/users") do |req| json_response(db.find_all("users")) end ``` ### `Combining middleware` ```ruby app = web_app() # 1. Log every request app.use do |req, next_fn| puts "#{req.method} #{req.path}" next_fn.(req) end # 2. Require a session for anything under /app/* app.use do |req, next_fn| if req.path.start_with?("/app") resp = response("") s = session(req, resp) if s["user_id"] == nil redirect("/login") else next_fn.(req) end else next_fn.(req) end end app.get("/app/dashboard") do |req| html_response("

Dashboard

") end app.get("/login") do |req| html_response("
") end app.run(3000) ``` `before` and `after` filters still work alongside `use` — they run inside the middleware chain. --- ## `Static File Serving *(v1.14)*` `app.static` serves all files in a directory. The path is relative to where `frankiec` is run from (normally the project root). ```ruby app = web_app() # Serve ./public/ at / — http://localhost:3000/style.css → ./public/style.css app.static("./public") app.run(3000) ``` Serve at a URL prefix to keep static assets at a predictable path: ```ruby # http://localhost:3000/static/app.js → ./assets/app.js app.static("/static", "./assets") ``` Static files are matched before routes — if both a static file and a route exist at the same path, the file wins. File types served automatically: `.html`, `.css`, `.js`, `.json`, `.png`, `.jpg`, `.gif`, `.svg`, `.webp`, `.ico`, `.woff`, `.woff2`. Directory listing is disabled — unknown paths return 404. --- ## WebSockets *(v1.18)* Hand-rolled RFC 6455 on the built-in web server — handshake, framing, ping/pong, clean close. Zero dependencies, as always. ### Server — `app.websocket` ```ruby app = web_app() app.websocket("/ws/:room") do |ws| ws.send("welcome to #{ws.params["room"]}") loop do msg = ws.recv() break if msg == nil # client closed ws.send("echo: #{msg}") end end app.run(3000) ``` Each connection runs the handler in its own thread and closes automatically when the handler returns. `recv()` answers pings for you and returns `nil` when the peer disconnects. ### Client — `ws_connect` ```ruby sock = ws_connect("ws://localhost:3000/ws/lobby", timeout: 5) sock.send("hello") puts sock.recv() sock.close() ``` Only `ws://` URLs are supported (no TLS). ### WebSocket object | Method / property | Description | |---|---| | `ws.send(msg)` | Send a text message | | `ws.recv()` | Receive a text message — `nil` when the peer closes | | `ws.close()` | Close the connection | | `ws.params` | Route parameters (e.g. `:room`) — server side | | `ws.path` | Request path — server side | | `ws.peer` | Remote `"host:port"` | --- ## `Web API Summary` | Function / Method | Description | |----------------------------------------|-------------------------------------------| | `web_app()` | Create a new application | | `app.get(path) do \|req\| end` | Register a GET route | | `app.post(path) do \|req\| end` | Register a POST route | | `app.put(path) do \|req\| end` | Register a PUT route | | `app.delete(path) do \|req\| end` | Register a DELETE route | | `app.patch(path) do \|req\| end` | Register a PATCH route | | `app.get_async(path) do \|req\| end` | Register a non-blocking GET route | | `app.post_async(path) do \|req\| end` | Register a non-blocking POST route | | `app.use do \|req, next_fn\| end` | Register a middleware layer | | `app.static(dir)` | Serve a directory at `/` | | `app.static(prefix, dir)` | Serve a directory at a URL prefix | | `app.websocket(path) do \|ws\| end` | Register a WebSocket route (v1.18) | | `ws_connect(url, timeout: nil)` | WebSocket client connection (v1.18) | | `app.before do \|req\| end` | Register a before-filter | | `app.after do \|req, res\| end` | Register an after-filter | | `app.not_found do \|req\| end` | Register a custom 404 handler | | `app.run(port)` | Start the server (blocking) | | `response(body, status, headers)` | Plain-text response | | `html_response(body, status)` | HTML response | | `json_response(data, status)` | JSON response | | `redirect(location, status)` | Redirect response | | `halt(status, body)` | Error response | | `req.cookies` | Parsed Cookie header as a hash | | `resp.set_cookie(name, val, opts)` | Append a Set-Cookie header | | `session(req, resp)` | Cookie-backed session hash | | `spawn { }` | Run a block in a background thread | | `timeout(n) { }` | Run a block with a time limit in seconds | | `await expr` | Non-blocking wait inside async routes | --- # Testing ## Overview Frankie has a built-in test runner — no external libraries, no configuration. Write assertions in any `.fk` file and run it with `frankiec test`. Every assertion prints a ✓ or ✗ in real time, and the runner exits with code 1 if any test fails, making it CI-friendly. --- ## Running Tests ```bash frankiec test # runs test.fk in the current directory frankiec test mytest.fk # runs a specific file frankiec test --filter math # v1.17 — only test groups whose name contains "math" frankiec test --tag slow # v1.17 — only test groups tagged "slow" frankiec test --coverage # v1.19 — report line coverage after the run ``` Output looks like: ``` ╔══ Frankie Test Runner ════════════════════════════════ ║ test.fk ╠═══════════════════════════════════════════════════════ ✓ addition works ✓ mean of [1,2,3] is 2.0 ✗ expected 4, got 5 ✓ FileNotFoundError raised on missing file ╠═══════════════════════════════════════════════════════ ║ 3/4 passed, 1 failed (12.3ms) ╚═══════════════════════════════════════════════════════ ``` --- ## Assertions All assertion functions are available without any import inside a test file. ### `assert_eq(actual, expected, msg)` Equality The workhorse. Passes if `actual == expected`. ```ruby assert_eq(2 + 2, 4, "addition") assert_eq(mean([1,2,3]), 2.0, "mean of 1..3") assert_eq("hello".upcase, "HELLO", "upcase") assert_eq([1,2,3].length, 3, "vector length") ``` ### `assert_neq(actual, expected, msg)` Inequality Passes if `actual != expected`. ```ruby assert_neq(rand_int(1, 100), 0, "rand_int never returns 0") assert_neq("hello", "", "non-empty string") ``` ### `assert_true(value, msg)` Truthy Passes if `value` is truthy (anything except `false` and `nil`). ```ruby assert_true(file_exists("/tmp"), "tmp dir exists") assert_true([1,2,3].include?(2), "include? works") assert_true("hello".start_with?("he"), "start_with?") assert_true(5 > 3, "comparison") ``` ### `assert_nil(value, msg)` Nil check Passes if `value` is `nil`. ```ruby assert_nil(find_user(999), "missing user returns nil") assert_nil([1,2,3].find do |x| x > 9 end, "find with no match") assert_nil({a: 1}["missing"], "missing hash key is nil") ``` ### `assert_match(value, pattern, msg)` Regex match Passes if `pattern` matches anywhere in `value`. ```ruby assert_match("alice@example.com", "\\w+@\\w+\\.\\w+", "valid email") assert_match("2024-03-15", "^\\d{4}-\\d{2}-\\d{2}$", "ISO date") assert_match("Error: timeout", "timeout", "error message contains timeout") ``` ### `assert_not_nil(value, msg)` Non-nil check *(introduced in v1.15)* Passes if `value` is anything other than `nil`. ```ruby assert_not_nil(find_user(1), "user exists") assert_not_nil(result["id"], "result has an id") assert_not_nil("", "empty string is not nil") ``` ### `assert_in(value, collection, msg)` Membership check *(introduced in v1.15)* Passes if `collection` includes `value`. ```ruby assert_in("admin", roles, "user has admin role") assert_in(42, valid_ids, "id is valid") assert_in("fr", ["en", "fr", "de"], "French supported") ``` ### `assert_approx_eq(actual, expected, delta, msg)` Approximate float equality *(introduced in v1.13.1)* Passes if `|actual - expected| <= delta`. Default delta is `0.001`. ```ruby assert_approx_eq(3.14159, 3.14, 0.01, "pi rounded") assert_approx_eq(mean([1,2,3]), 2.0, 0.001, "mean") assert_approx_eq(0.1 + 0.2, 0.3, 0.0001, "float addition") ``` ### `assert_raises(fn, msg)` Any error raised Passes if calling `fn` raises any error. ```ruby assert_raises(->() { x = 1 // 0 }, "division by zero raises") assert_raises(->() { file_read("/no/such/file.txt") }, "missing file raises") ``` ### `assert_raises_typed(fn, type, msg)` Specific error type Passes if calling `fn` raises exactly the specified error type. ```ruby assert_raises_typed(->() { x = 1 // 0 }, "ZeroDivisionError", "division raises ZeroDivisionError") assert_raises_typed(->() { file_read("/no/such/file.txt") }, "FileNotFoundError", "missing file raises FileNotFoundError") assert_raises_typed(->() { "hello" + 42 }, "TypeError", "string + int raises TypeError") ``` Supported type strings: `"ZeroDivisionError"`, `"FileNotFoundError"`, `"TypeError"`, `"ValueError"`, `"IndexError"`, `"KeyError"`, `"NameError"`, `"AttributeError"`, `"TimeoutError"`, `"RuntimeError"`, `"Exception"` — plus any user-defined error type declared with `error` (v1.17). --- ## Test Groups — `test` (v1.17) Group related assertions into named, filterable blocks with `test`: ```ruby test "math basics" do assert_eq(1 + 1, 2, "addition works") assert_eq(abs(-5), 5, "abs negative") end test "slow integration", tags: ["slow", "network"] do assert_true(http_get("http://localhost:3000/health")["ok"]) end ``` Run a subset from the command line: ```bash frankiec test # run everything frankiec test --filter math # groups whose name contains "math" frankiec test --tag slow # groups tagged "slow" ``` Skipped groups are reported in the summary. `test` is a contextual keyword — a variable named `test` keeps working. --- ## Test Coverage — `--coverage` (v1.19) Add `--coverage` to see which lines your tests actually exercised: ```bash frankiec test tcov.fk --coverage ``` ``` ╠══ Coverage ═══════════════════════════════════════════ ║ 80.0% tcov.fk missing: 6 ║ ── overall: 80.0% (4/5 lines) ``` - Percentages and missing-line ranges are mapped back to `.fk` source. - Writes `.frankie_coverage.json` in the current directory. - The LSP reads that file — after a coverage run, uncovered lines show up as unobtrusive hints directly in your editor. --- ## Stubbing — `stub` / `unstub` (v1.17) Swap any global function during a test — including stdlib functions like `shell` and `http_get` — to test without side effects: ```ruby test "stubbing" do stub("shell", ->(cmd) { {ok: true, stdout: "fake", exit_code: 0} }) assert_eq(shell("anything")["stdout"], "fake") unstub("shell") # restore the real shell end ``` `unstub(name)` restores one function; `unstub()` with no arguments restores everything. --- ## Structuring Tests Use `test` groups (above), or simply place assertions anywhere in the file — they are collected and reported together. For readability, group related assertions with comments: ```ruby # test.fk # ── Math ────────────────────────────────────────────────────── assert_eq(abs(-5), 5, "abs negative") assert_eq(abs(5), 5, "abs positive") assert_eq(round(3.14159,2), 3.14, "round to 2dp") assert_eq(clamp(15, 0, 10), 10, "clamp above max") assert_eq(clamp(-5, 0, 10), 0, "clamp below min") # ── String ──────────────────────────────────────────────────── assert_eq("hello".upcase, "HELLO", "upcase") assert_eq(" hi ".strip, "hi", "strip") assert_eq("a,b,c".split(",").length, 3, "split count") assert_match("frank123", "\\d+", "contains digits") # ── Vector ──────────────────────────────────────────────────── v = [3, 1, 4, 1, 5, 9, 2, 6] assert_eq(v.length, 8, "length") assert_eq(min(v), 1, "min") assert_eq(max(v), 9, "max") assert_eq(v.sort[0], 1, "sort first") assert_eq(v.uniq.length, 7, "uniq removes one duplicate") # ── Error handling ──────────────────────────────────────────── assert_raises_typed(->() { 1 // 0 }, "ZeroDivisionError", "division by zero") assert_raises_typed(->() { file_read("/no/such/file.txt") }, "FileNotFoundError", "missing file") ``` --- ## Testing Your Own Functions Require your lib files the same way `main.fk` does: ```ruby # test.fk require "lib/math_utils" require "lib/string_utils" # ── math_utils ──────────────────────────────────────────────── assert_eq(circle_area(1), round(3.14159, 2), "unit circle") assert_eq(circle_area(0), 0.0, "zero radius") assert_eq(factorial(5), 120, "factorial 5") assert_eq(factorial(0), 1, "factorial 0") # ── string_utils ────────────────────────────────────────────── assert_eq(slugify("Hello World"), "hello-world", "slugify basic") assert_eq(slugify(" spaces "), "spaces", "slugify trims") assert_eq(truncate("hello", 3), "hel...", "truncate") assert_nil(truncate("hi", 10), "no truncate needed returns nil") ``` --- ## Testing File I/O Use a temporary path and clean up in every test: ```ruby path = "/tmp/fk_test_#{rand_int(1000, 9999)}.txt" # Write and read back file_write(path, "hello frankie\n") assert_true(file_exists(path), "file was created") assert_eq(file_read(path).strip, "hello frankie", "content correct") # Append file_append(path, "second line\n") assert_eq(file_lines(path).length, 2, "two lines after append") # Delete file_delete(path) assert_true(not file_exists(path), "file deleted") # FileNotFoundError assert_raises_typed(->() { file_read("/no/such/file.txt") }, "FileNotFoundError", "missing file raises correctly") ``` --- ## Watch Mode Run tests automatically whenever you save: ```bash frankiec watch test.fk --test ``` Every time you save `test.fk` (or any file, since watch triggers on the target file), the test suite re-runs. Combine with `require` to automatically pick up changes in your lib files too. --- ## Quick Reference | Assertion | Passes when | |---|---| | `assert_eq(actual, expected, msg)` | `actual == expected` | | `assert_neq(actual, expected, msg)` | `actual != expected` | | `assert_true(value, msg)` | `value` is truthy | | `assert_nil(value, msg)` | `value` is nil | | `assert_not_nil(value, msg)` | `value` is not nil | | `assert_in(value, collection, msg)` | `collection` includes `value` | | `assert_approx_eq(a, b, delta, msg)` | `|a - b| <= delta` (default delta `0.001`) | | `assert_match(value, pattern, msg)` | pattern matches anywhere in value | | `assert_raises(fn, msg)` | calling `fn` raises any error | | `assert_raises_typed(fn, type, msg)` | calling `fn` raises that specific type | | Helper (v1.17) | Purpose | |---|---| | `test "name", tags: [...] do ... end` | Named, filterable test group | | `stub(name, fn)` | Replace a global function for the test | | `unstub(name)` / `unstub()` | Restore one / all stubbed functions | | `frankiec test --coverage` | Report line coverage; writes `.frankie_coverage.json` (v1.19) | --- # Random ## Overview Frankie has a built-in random number library — no imports required. It covers integers, floats, seeding for reproducibility, and collection operations like shuffle and sample. All functions are wrappers around Python's `random` module. --- ## Random Numbers ### `rand_int(a, b)` Random integer, both ends inclusive ```ruby puts rand_int(1, 6) # dice roll: 1, 2, 3, 4, 5, or 6 puts rand_int(0, 100) # 0 to 100 puts rand_int(-10, 10) # -10 to 10 ``` ### `rand_float(a, b)` Random float in range Returns a float in `[a, b)` — inclusive on the left, exclusive on the right. ```ruby puts rand_float(0.0, 1.0) # e.g. 0.7493... puts rand_float(-1.0, 1.0) # e.g. -0.234... puts rand_float(0.0, 100.0) # e.g. 42.17... ``` ### `rand()` Random float 0.0 to 1.0 ```ruby puts rand() # e.g. 0.4217... ``` ### `rand(n)` Random integer 0 to n-1 ```ruby puts rand(10) # 0 to 9 (exclusive upper bound) puts rand(2) # 0 or 1 — coin flip ``` --- ## Reproducibility ### `rand_seed(n)` Fix the random seed Seeding produces the same sequence every time — essential for tests, simulations, and reproducible results. ```ruby rand_seed(42) puts rand_int(1, 100) # always the same value puts rand_int(1, 100) # next value in the same sequence puts rand_int(1, 100) # and so on ``` Re-seed to restart the sequence: ```ruby rand_seed(42) a = rand_int(1, 1000) rand_seed(42) b = rand_int(1, 1000) assert_eq(a, b, "same seed produces same value") ``` --- ## Collections ### `shuffle(v)` Return a randomly reordered copy Returns a new vector — does not modify the original. ```ruby v = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] puts shuffle(v) # e.g. [4, 9, 1, 7, 3, 10, 5, 2, 8, 6] puts v # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] — unchanged ``` ### `sample(v, n)` Random sample without replacement Returns `n` randomly chosen elements. No element is chosen twice. ```ruby v = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] puts sample(v, 3) # e.g. [7, 2, 9] puts sample(v, 1) # e.g. [4] ``` `n` defaults to 1 if omitted: ```ruby puts sample(["red", "green", "blue"]) # e.g. ["green"] ``` --- ## Quick Reference | Function | Description | |---|---| | `rand_int(a, b)` | Random integer between a and b inclusive | | `rand_float(a, b)` | Random float in [a, b) | | `rand()` | Random float in [0.0, 1.0) | | `rand(n)` | Random integer in [0, n) | | `rand_seed(n)` | Fix seed for reproducibility | | `shuffle(v)` | Return randomly reordered copy of vector | | `sample(v, n)` | Return n randomly chosen elements (no repeats) | --- # Encoding & Signing Built-in functions for Base64 encoding and HMAC signing. Zero dependencies — backed by Python's `base64` and `hmac` / `hashlib` standard library modules. Introduced in **v1.15** (previously available as internal `_fk_hmac_*` functions). --- ## Base64 ### `base64_encode(str)` Encode a string to standard Base64. ```ruby puts base64_encode("hello:world") # aGVsbG86d29ybGQ= puts base64_encode("Alice") # QWxpY2U= # Build an HTTP Basic Auth header creds = base64_encode("#{user}:#{pass}") puts "Authorization: Basic #{creds}" ``` ### `base64_decode(str)` Decode a Base64 string back to its original value. ```ruby puts base64_decode("aGVsbG86d29ybGQ=") # hello:world puts base64_decode("QWxpY2U=") # Alice # Decode an incoming Basic Auth header encoded = req.headers["Authorization"][6..-1].strip decoded = base64_decode(encoded) # "username:password" ``` --- ## HMAC Signing ### `hmac_sign(subject, secret)` Create a tamper-proof signed token by combining a subject string with a secret key using HMAC-SHA256. Returns a string in the form `subject:signature`. ```ruby SECRET = env("APP_SECRET", "dev-only") token = hmac_sign("user_id=42", SECRET) puts token # user_id=42:be38cbad... ``` ### `hmac_verify(token, secret)` Verify a token produced by `hmac_sign`. Returns the original subject string if the signature is valid, or `nil` if the token is missing, malformed, or tampered with. ```ruby SECRET = env("APP_SECRET", "dev-only") subject = hmac_verify("user_id=42:be38cbad...", SECRET) puts subject # user_id=42 puts hmac_verify("tampered:abc", SECRET) # nil ``` --- ## Signed Token Flow ```ruby SECRET = env("APP_SECRET", "dev-only") # Create token = hmac_sign("user_id=42", SECRET) # Verify subject = hmac_verify(token, SECRET) if subject == nil puts "Invalid token" else puts "Verified: #{subject}" # Verified: user_id=42 end # Tampering is detected bad = token[0..-3] + "XX" puts hmac_verify(bad, SECRET) # nil ``` --- ## Notes - `hmac_sign` produces signed strings, not encrypted ones. The subject is visible in the token — store a user ID, not a password or sensitive value. - Tokens produced by `hmac_sign` do not expire. To add expiry, include a timestamp in the subject and check it after verifying: `hmac_sign("user=42,exp=#{now().timestamp + 3600}", SECRET)`. - The `frankieauth` stitch builds a full Basic Auth + Bearer token middleware layer on top of these functions. Use it if you need drop-in route protection. --- ## Quick Reference | Function | Description | |---|---| | `base64_encode(str)` | Encode string to Base64 | | `base64_decode(str)` | Decode Base64 string | | `hmac_sign(subject, secret)` | Create a signed token | | `hmac_verify(token, secret)` | Verify token — returns subject or `nil` | --- # Debugging & Benchmarking Introduced in **v1.18**, with a full stepping debugger added in **v1.19**. A debugger you can drop anywhere, and friendly block timing — both built into the language, zero dependencies. --- ## `breakpoint` — Stepping Debugger Drop `breakpoint` anywhere. When execution reaches it in a terminal, the program pauses into a scoped REPL: ```ruby def price(qty) total = qty * 4.5 breakpoint total end price(10) ``` ``` 🧟 breakpoint — pricing.fk:3 ──▶ 3 │ breakpoint (c)ontinue · s(tep) · n(ext) · stack · vars · where · exit · or type any Frankie expression (fkdb) vars qty = 10 total = 45.0 (fkdb) total * 2 => 90.0 (fkdb) c ``` ### Commands | Command | Effect | |---|---| | `c` | Continue execution | | `s` | Step — execute one line, stepping into calls *(v1.19)* | | `n` | Next — one line, stepping over calls *(v1.19)* | | `stack` | Show the Frankie call stack, innermost first *(v1.19)* | | `vars` | List local variables in the paused scope (clean — no stdlib noise) | | `where` | Show the current file and line | | `exit` | Abort the program | | *anything else* | Evaluated as a Frankie expression against the paused scope | Stepping is line-accurate everywhere thanks to the compiler's line maps — including inside `require`d files. ### Debug from the very first line (v1.19) ```bash frankiec run --debug app.fk ``` Breaks before the first statement runs, so you can step through a program you've never read — no need to add a `breakpoint` line yourself. ### Conditional breakpoints Postfix conditions work: ```ruby breakpoint if qty > 100 ``` ### CI-safe by design When stdin isn't a terminal (CI, pipes, `frankiec test` in a pipeline), breakpoints print a notice and are skipped — your test runs never hang. `breakpoint` is a contextual keyword — a variable named `breakpoint` keeps working. --- ## `benchmark` — Friendly Timing Times a block, prints the elapsed time, and returns the elapsed milliseconds: ```ruby ms = benchmark "crunch" do heavy_work() end # ⏱ crunch: 132.4ms benchmark do # label optional quick_thing() end ``` Because it returns the elapsed ms, you can assert on it in tests or collect timings in a vector: ```ruby timings = [100, 1000, 10000].map do |n| benchmark "n=#{n}" do (1..n).to_vec.map do |x| x * x end end end puts timings ``` `benchmark` is a contextual keyword — a variable named `benchmark` keeps working. --- ## Quick Reference | Syntax | Description | |---|---| | `breakpoint` | Pause into a scoped debug REPL (skipped when stdin isn't a tty) | | `breakpoint if cond` | Conditional breakpoint | | `frankiec run --debug app.fk` | Break at the first line automatically (v1.19) | | `(fkdb) s` / `n` / `stack` | Step in / step over / show call stack (v1.19) | | `benchmark "label" do ... end` | Time a block — prints `⏱ label: 12.3ms`, returns elapsed ms | | `benchmark do ... end` | Same, without a label | --- # Stitches ## `What are stitches?` Frankie's zero-dependency, zero-registry package system. Drop a `.fk` file in the right folder and stitch it in. | Feature | Category | Summary | |---|---|---| | **`stitch "name"`** | language | Load a package by name — resolves from `./stitches/` then `~/.frankie/stitches/` | | **`frankieforms`** | stitch | Form field validation — required, min/max length, email, numeric, pattern | | **`frankietable`** | stitch | ASCII table rendering from a vector of hashes | | **`frankiecolor`** | stitch | ANSI color helpers for terminal output | | **`frankiepager`** | stitch | Pagination math — total pages, slicing, prev/next | | **`frankieconfig`** | stitch | Layered config loading from defaults, JSON file, and env vars | | **`frankiestring`** | stitch | Additional string functions | | **`frankietemplate`** | stitch | Mustache-compatible template rendering for Frankie | | **`frankiecookie`** | stitch | Signed cookie helpers for Frankie | | **`frankieauth`** | stitch | HTTP Basic Auth and Bearer token authentication — introduced in v1.15 | | **`frankieratelimit`** | stitch | In-memory per-IP sliding-window rate limiting — introduced in v1.15 | | **`frankiemail`** | stitch | Send email via SMTP — plain text or HTML, CC/BCC — introduced in v1.16 | | **`frankiecli`** | stitch | Structured CLI argument parsing — flags, options, subcommands — introduced in v1.16 | | **`frankiecache`** | stitch | In-memory key/value cache with optional TTL — introduced in v1.16 | | **[`frankiegame`](frankiegame.md)** | stitch | Terminal game engine — raw keys, double-buffered ANSI rendering — introduced in v1.20 | | **[`frankiecanvas`](frankiecanvas.md)** | stitch | Browser game engine, same API as frankiegame — HTML5 canvas over WebSockets — introduced in v1.20 | --- ## The `stitch` Keyword `stitch` loads a Frankie package by name. It resolves the file in two locations, in order: 1. `./stitches/.fk` — project-local (checked first) 2. `~/.frankie/stitches/.fk` — user-global If neither exists, a clear error tells you exactly what to do: ``` ╔══ Frankie Runtime Error ══════════════════════════════ ║ [Frankie] Stitch not found: "frankieforms" ║ Put frankieforms.fk in ./stitches/ or ~/.frankie/stitches/ ╚═══════════════════════════════════════════════════════ ``` Each stitch is loaded **at most once** — calling `stitch "name"` multiple times in the same program is safe. --- ## Installing Stitches (v1.17) The stitch installer fetches stitches straight from the Frankie GitHub repository using the Python stdlib HTTP client — a package manager with no packaging: ```bash frankiec stitch install frankiecolor # → ./stitches/ frankiec stitch install frankiecache --global # → ~/.frankie/stitches/ frankiec stitch list # installed + registry ``` ### Lockfile — `stitch.lock` (v1.18) Installing a stitch pins it in `stitch.lock` (sha256, source, size, date). Commit the lockfile and your builds are reproducible: ```bash frankiec stitch install frankiecolor # writes/updates stitch.lock frankiec stitch verify # ✓ pinned · ⚠ modified · ✗ missing frankiec stitch update # re-fetch everything + re-pin frankiec stitch update frankiecolor # or just one ``` `verify` exits 1 on problems — drop it straight into CI. Global installs (`--global`) don't touch the lockfile. ### Installing from any URL (v1.19) Not every stitch has to come from the Frankie registry: ```bash frankiec stitch install https://example.com/stitches/foo.fk ``` It's pinned in `stitch.lock` exactly like a registry stitch, with the URL recorded as its source — `verify` and `update` work the same way. ### Compared to `require` | | `require` | `stitch` | |---|---|---| | Path | Explicit: `require "lib/utils"` | By name: `stitch "frankieforms"` | | Resolution | Relative to cwd | `./stitches/` then `~/.frankie/stitches/` | | Signals | Your own code | Third-party packages | | Convention | `lib/` folder | `stitches/` folder | They use the same underlying machinery — `stitch` is `require` with a conventional resolution path and a more meaningful name for the job. ### `Project layout with stitches` ``` myapp/ ├── main.fk ├── test.fk ├── lib/ │ └── utils.fk ← your own code, loaded with require └── stitches/ ├── frankieforms.fk ← third-party, loaded with stitch └── frankietable.fk ``` Anyone cloning your repo immediately knows what `stitches/` contains. --- ## `Writing Your Own Stitch` A stitch is any `.fk` file. Drop it in `./stitches/` and `stitch "name"` loads it. ```ruby # stitches/myutils.fk def slugify(s) s.downcase.gsub("[^a-z0-9]+", "-").strip end def truncate(s, n) if s.length <= n s else s[0...n] + "..." end end ``` ```ruby # main.fk stitch "myutils" puts slugify("Hello World!") # hello-world puts truncate("Long string", 4) # Long... ``` ## `Conventions` - Prefix private helper functions with `_` to signal they're internal. - Use `##` doc-comments for `frankiec docs` compatibility. - Keep each stitch focused on one concern. - Avoid redefining stdlib functions. --- # Frankiecolor Terminal Colors ## `Color functions` `black`, `red`, `green`, `yellow`, `blue`, `magenta`, `cyan`, `white` wrap a string in that ANSI color. ```ruby stitch "frankiecolor" puts red("Error: something failed") ``` ## `Style functions` `bold`, `dim`, `italic`, `underline`, `inverse` — apply text styles. ```ruby stitch "frankiecolor" puts underline("Click here") ``` ## Utilities ### `colorize(str, color_name)` generic color by name string. ```ruby stitch "frankiecolor" puts colorize("hello", "magenta") ``` ### `strip_color(str)` remove all ANSI escape codes (for writing colored output to a log file). ``` stitch "frankiecolor" msg = warn("Deprecated API") puts msg puts strip_color(msg) ``` --- # Frankieforms Form Validation ## `Available rules` | Rule | Options | Description | |---|---|---| | `"required"` | — | Value must be non-nil and non-empty | | `"min_length"` | `value: n` | At least n characters | | `"max_length"` | `value: n` | At most n characters | | `"email"` | — | Must match `word@word.word` | | `"min_value"` | `value: n` | Integer value ≥ n | | `"max_value"` | `value: n` | Integer value ≤ n | | `"numeric"` | — | Must be a number (int or float) | | `"alpha"` | — | Letters only | | `"matches_pattern"` | `value: pat`, `message: msg` | Must match regex pattern | ## Functions ### `validate(form, rules)` Returns a Hash of `{field: error_message}` pairs. Empty hash = all valid. ```ruby stitch "frankieforms" form = {name: "A", email: "alice@example", age: ""} rules = { name: [{rule: "required"}, {rule: "min_length", value: 2}], email: [{rule: "required"}, {rule: "email"}], age: [{rule: "required"}, {rule: "min_value", value: 18}] } if valid?(form, rules) == false validate(form, rules).each do |field, msg| puts "#{field}: #{msg}" end end → name: must be at least 2 characters → email: must be a valid email address → age: is required ``` ### `valid?(form, rules)` Returns `true` if no errors. ```ruby stitch "frankieforms" form = {name: "Alice", email: "alice@example", age: "25"} rules = { name: [{rule: "required"}, {rule: "min_length", value: 2}], email: [{rule: "required"}, {rule: "email"}], age: [{rule: "required"}, {rule: "min_value", value: 18}] } puts valid?(form, rules) → true ``` --- # Frankietable ASCII Tables ## Functions ### `table(rows)` Render all columns. Columns inferred from first row's keys. ```ruby stitch "frankietable" rows = [ {name: "Alice", dept: "Engineering", salary: 95000}, {name: "Bob", dept: "Marketing", salary: 72000}, {name: "Carol", dept: "Finance", salary: 88000} ] puts table(rows) → +-------+-------------+--------+ → | name | dept | salary | → +-------+-------------+--------+ → | Alice | Engineering | 95000 | → | Bob | Marketing | 72000 | → | Carol | Finance | 88000 | → +-------+-------------+--------+ ``` ### `table(rows, cols)` Render specific columns in the given order. ```ruby stitch "frankietable" rows = [ {name: "Alice", dept: "Engineering", salary: 95000}, {name: "Bob", dept: "Marketing", salary: 72000}, {name: "Carol", dept: "Finance", salary: 88000} ] puts table(rows, ["name", "salary"]) → +-------+--------+ → | name | salary | → +-------+--------+ → | Alice | 95000 | → | Bob | 72000 | → | Carol | 88000 | → +-------+--------+ ``` ### `table_print(rows, cols)` Shorthand for `puts table(rows, cols)`. ```ruby stitch "frankietable" rows = [ {name: "Alice", dept: "Engineering", salary: 95000}, {name: "Bob", dept: "Marketing", salary: 72000}, {name: "Carol", dept: "Finance", salary: 88000} ] table_print(rows, ["name", "salary"]) → +-------+--------+ → | name | salary | → +-------+--------+ → | Alice | 95000 | → | Bob | 72000 | → | Carol | 88000 | → +-------+--------+ ``` --- # Frankiepager Pagination ## `Pager hash keys` | Key | Description | |---|---| | `page` | Current page (clamped to valid range) | | `per_page` | Items per page | | `total` | Total item count | | `total_pages` | Total number of pages | | `from` | First item number on this page | | `to` | Last item number on this page | | `has_prev` | True if there is a previous page | | `has_next` | True if there is a next page | | `prev_page` | Previous page number or nil | | `next_page` | Next page number or nil | | `first_page` | True if on the first page | | `last_page` | True if on the last page | ## Functions ### `paginate(opts)` Compute pagination. Opts: `total`, `page`, `per_page`. ```ruby stitch "frankiepager" pg = paginate({total: 247, page: 3, per_page: 20}) puts "Page #{pg["page"]} of #{pg["total_pages"]}" puts "Showing items #{pg["from"]}–#{pg["to"]} of #{pg["total"]}" puts "Has prev: #{pg["has_prev"]} Has next: #{pg["has_next"]}" puts "Prev page: #{pg["prev_page"]} Next page: #{pg["next_page"]}" → Page 3 of 13 → Showing items 41–60 of 247 → Has prev: true Has next: true → Prev page: 2 Next page: 4 ``` ### `page_slice(items, page, per_page)` Return the slice of a vector for the given page. ```ruby stitch "frankiepager" items = seq(1, 50) puts "Page 2 of seq(1,50) at 10/page:" puts page_slice(items, 2, 10) → Page 2 of seq(1,50) at 10/page: → [11, 12, 13, 14, 15, 16, 17, 18, 19, 20] ``` ### `page_links(pager, url_template)` Generate a vector of `{label, url, active}` hashes for navigation links. Use `{page}` in the template: `"/posts?page={page}"`. ```ruby stitch "frankiepager" pager = paginate({total: 60, page: 3, per_page: 10}) links = page_links(pager, "/posts?page={page}") links.each do |link| if link["active"] puts "[#{link["label"]}] #{link["url"]}" # current page — marked active else puts " #{link["label"]} #{link["url"]}" end end → ← Prev /posts?page=2 → 1 /posts?page=1 → 2 /posts?page=2 → [3] /posts?page=3 → 4 /posts?page=4 → 5 /posts?page=5 → 6 /posts?page=6 → Next → /posts?page=4 ``` --- ## `frankieconfig` Layered Config Sources are merged in priority order: defaults → JSON file → env vars → overrides. Higher priority wins. Type coercion is automatic — if the default is an Integer, the env var string is converted to Integer. Same for Float and Boolean. ## Functions ### `load_config(opts)` Load and merge config. Opts: `file`, `env_prefix`, `defaults`, `overrides`. ```ruby stitch "frankieconfig" config = load_config({ file: "config.json", env_prefix: "APP", defaults: {host: "localhost", port: 3000, debug: false} }) puts config["host"] # APP_HOST env → config.json → "localhost" puts config["port"] # APP_PORT env → config.json → 3000 puts config["debug"] # APP_DEBUG env → config.json → false ``` ### `config_get(config, key, fallback)` Get a key with a fallback if missing. ```ruby stitch "frankieconfig" config = load_config({ file: "config.json", env_prefix: "APP", defaults: {host: "localhost", port: 3000, debug: false} }) puts config_get(config, "username", "Frankie") ``` --- # Frankiestring Additional string functions ## `pad_left(str, n, char)` Right-align in a field of width n (space fill) ```ruby stitch "frankiestring" puts pad_left("Frankie", 12, "0") → 00000Frankie ``` ## `pad_right(str, n, char)` Left-align with custom fill character ```ruby stitch "frankiestring" puts pad_right("Frankie", 12, "0") → Frankie00000 ``` ## `truncate(str, n, suffix)` Cut to n chars, append custom suffix ```ruby stitch "frankiestring" puts truncate("Frankie", 5, "X") → FranX ``` ## `slugify(str)` URL-safe lowercase slug ```ruby stitch "frankiestring" puts slugify("Frankie's Website") → frankie-s-website ``` ## `word_wrap(str, width)` Wrap text at word boundaries ```ruby stitch "frankiestring" puts word_wrap("Frankie is a nice programming language", 5) → Frankie is a nice programming language ``` ## `indent_lines(str, n)` Prepend n spaces to every line ```ruby stitch "frankiestring" puts indent_lines("Frankie is a nice programming language", 5) → Frankie is a nice programming language ``` --- # Frankietemplate Mustache-Compatible Templates `frankietemplate` is a Mustache-compatible template engine for Frankie. Drop HTML (or any text) into a `.html` file, sprinkle in `{{ tags }}`, and call `render_file` from a route handler. No dependencies — the regex engine that powers it is part of Frankie's stdlib. ```ruby stitch "frankietemplate" app = web_app() app.get("/hello/:name") do |req| html = render_file("./views/hello.html", { name: req.params["name"], year: 2026 }) html_response(html) end app.run(3000) ``` ```html

Hello, {{ name }}!

Welcome to Frankie — it's {{ year }}.

``` --- ## How It Works `frankietemplate.fk` is a thin public API wrapper. The actual rendering engine — regex matching, escaping, section expansion — lives in `frankie_stdlib.py` and is available as soon as you `stitch "frankietemplate"`. You never interact with the internals directly; `render`, `render_file`, and `partial` are the only three functions you need. --- ## Template Syntax ### `{{ variable }}` Interpolation (HTML-escaped) Replaces the tag with the value from the data hash. The value is **HTML-escaped** — `<`, `>`, `&`, `"`, `'` are converted to their safe entity equivalents. This is the default and the safe choice for user-supplied content. ```ruby render("Hello, {{ name }}!", {name: "Alice"}) # → Hello, Alice! render("

{{ bio }}

", {bio: ""}) # →

<script>alert(1)</script>

``` Missing keys render as an empty string — no error is raised: ```ruby render("Hello, {{ name }}{{ suffix }}!", {name: "Alice"}) # → Hello, Alice! ``` --- ### `{{{ variable }}}` Raw Output (Unescaped) Triple braces output the value as-is, with no HTML escaping. Use this when the value is already trusted HTML — a rendered sub-template, a rich-text field from your own database, a pre-built HTML snippet. ```ruby body_html = "Important announcement" render("
{{{ body }}}
", {body: body_html}) # →
Important announcement
# Contrast with double braces: render("
{{ body }}
", {body: body_html}) # →
<strong>Important</strong> announcement
``` **Never use `{{{ }}}` with user-supplied content** — it will pass raw HTML straight through to the browser. --- ### `{{# section }} ... {{/ section }}` Sections A section tag renders its inner content based on the value of the key. The behaviour depends on the value's type: **Boolean `true` — render once:** ```ruby tmpl = "{{# logged_in }}Welcome back!{{/ logged_in }}" render(tmpl, {logged_in: true}) # → Welcome back! render(tmpl, {logged_in: false}) # → (empty) ``` **Vector — iterate:** Each element becomes the context for one pass of the inner block. If the elements are hashes, their keys are available directly inside the block: ```ruby tmpl = "{{# posts }}
  • {{ title }} by {{ author }}
  • {{/ posts }}" render(tmpl, { posts: [ {title: "Hello World", author: "Alice"}, {title: "Day Two", author: "Bob"} ] }) # →
  • Hello World by Alice
  • Day Two by Bob
  • ``` If the elements are plain values (strings, numbers), use the special `.` key to reference the current item: ```ruby tmpl = "{{# tags }}{{ . }}{{/ tags }}" render(tmpl, {tags: ["ruby", "frankie", "web"]}) # → rubyfrankieweb ``` **`nil` or `false` — render nothing:** ```ruby render("{{# user }}{{ name }}{{/ user }}", {user: nil}) # → (empty) ``` --- ### `{{^ inverted }} ... {{/ inverted }}` Inverted Sections The opposite of `{{# }}` — renders when the value is `false`, `nil`, or an empty vector. Use it for "no results" states and optional content. ```ruby tmpl = <<~TMPL {{# posts }}
  • {{ title }}
  • {{/ posts }} {{^ posts }}

    No posts yet.

    {{/ posts }} TMPL render(tmpl, {posts: []}) # →

    No posts yet.

    render(tmpl, {posts: [{title: "Hello"}]}) # →
  • Hello
  • ``` --- ### `{{> partial_name }}` Partials Includes another template file from `./views/partials/.html`. Partials receive the same data context as the parent template. ```html

    {{ site_name }}

    ``` ```html {{> header }}

    Welcome, {{ user_name }}!

    ``` ```ruby render_file("./views/index.html", { site_name: "My Blog", user_name: "Alice" }) ``` If a partial file is not found, the tag renders as an empty string — no error. --- ### `{{! comment }}` Comments Stripped entirely from the output. Use them for notes inside template files. ```html {{! TODO: add pagination here }}
      {{# items }}
    • {{ name }}
    • {{/ items }}
    ``` --- ## Writing Templates in `.fk` Source ### `Heredoc (recommended for multi-line)` Use a heredoc to write a multi-line template directly in your `.fk` file: ```ruby tmpl = <<~HTML

    {{ title }}

    {{ body }}

    HTML puts render(tmpl, {title: "Hello", body: "World"}) ``` **`^` lexer gotcha:** `{{^ inverted }}` uses the caret character. Inside a heredoc, the `^` is passed through correctly — but if you write an inverted section on a line that also contains other `{` characters without a space, the lexer may misread it. The safe rule: **always put a space after `{{^`**, which is valid Mustache anyway: ```ruby # Safe — space after {{^ tmpl = <<~HTML {{^ items }}

    Nothing here.

    {{/ items }} HTML # Potentially ambiguous — avoid tmpl = <<~HTML {{^items}}

    Nothing.

    {{/items}} HTML ``` ### `join` for short inline templates. For short snippets that don't warrant a heredoc, build the template as a vector of lines and join them: ```ruby tmpl = [ "
      ", "{{# items }}
    • {{ name }}
    • {{/ items }}", "
    " ].join("\n") puts render(tmpl, {items: [{name: "Alice"}, {name: "Bob"}]}) ``` ### `Template files` (recommended for HTML pages) For anything page-sized, keep templates in `./views/` and use `render_file`. Keeps your `.fk` files clean and lets your editor syntax-highlight the HTML properly: ```ruby app.get("/posts/:id") do |req| post = db.find("posts", {id: req.params["id"]}) html = render_file("./views/post.html", post) html_response(html) end ``` --- ## Functions ### `render(template, data)` Render a template string. `template` is any string containing Mustache tags. `data` is a hash — keys must be strings (use `"key"` not `key:`). ```ruby stitch "frankietemplate" html = render("

    {{ title }}

    ", {"title" => "Hello"}) puts html #

    Hello

    ``` Data keys can also be symbol keys (the lookup checks both): ```ruby html = render("

    {{ title }}

    ", {title: "Hello"}) puts html #

    Hello

    ``` --- ### `render_file(path, data)` Load a template file and render it. `path` is relative to the working directory (where `frankiec` is run from — normally the project root). Raises an error if the file does not exist. ```ruby html = render_file("./views/dashboard.html", { user: db.find("users", {id: session_user_id}), posts: db.find_all("posts", {published: true}), title: "Dashboard" }) html_response(html) ``` --- ### `partial(name)` Load a partial template by name from `./views/partials/.html`. Returns the raw file contents as a string. Normally you use `{{> name }}` tags inside template files rather than calling this directly — it is available for cases where you need to compose template strings programmatically. ```ruby header = partial("header") footer = partial("footer") page = header + content + footer html_response(page) ``` Raises an error if the partial file is not found. --- ## `Project Layout` ``` myapp/ ├── main.fk ├── stitches/ │ └── frankietemplate.fk └── views/ ├── index.html ├── post.html ├── dashboard.html └── partials/ ├── header.html ├── footer.html └── nav.html ``` `frankiec new` creates the `views/` and `views/partials/` directories automatically. --- ## Full Web Example ```ruby # main.fk stitch "frankietemplate" app = web_app() app.static("./public") app.get("/") do |req| posts = db.find_all("posts", {published: true}) html = render_file("./views/index.html", { title: "My Blog", posts: posts, count: posts.length }) html_response(html) end app.get("/posts/:id") do |req| post = db.find("posts", {id: req.params["id"].to_int}) if post == nil halt(404, "Post not found") end html = render_file("./views/post.html", post) html_response(html) end app.run(3000) ``` ```html {{> header }}

    {{ count }} posts

    {{# posts }} {{/ posts }} {{^ posts }}

    No posts yet. Check back soon!

    {{/ posts }}
    {{> footer }} ``` ```html {{> header }}

    {{ title }}

    By {{ author }} on {{ date }}

    {{{ body_html }}}
    ← Back
    {{> footer }} ``` ```html {{ title }} ``` ```html

    Built with Frankie 🧟

    ``` --- ## `Quick Reference` | Tag | Behaviour | |---|---| | `{{ key }}` | Value from data hash, HTML-escaped | | `{{{ key }}}` | Value from data hash, raw — no escaping | | `{{# key }} ... {{/ key }}` | Render if truthy; iterate if vector; scope if hash | | `{{^ key }} ... {{/ key }}` | Render if falsy, nil, or empty vector | | `{{ . }}` | Current item in a plain-value vector loop | | `{{> name }}` | Include `./views/partials/.html` | | `{{! comment }}` | Stripped — not rendered | --- # Frankiecookie ## Functions ### `set_signed_cookie(resp, name, value, secret, opts)` Write a signed cookie ### `get_signed_cookie(req, name, secret)` Read + verify a signed cookie (nil if invalid/missing) ### `delete_cookie(resp, name)` Expire a cookie immediately ### `cookie_set?(req, name)` Check if a cookie exists ## `opts` The opts hash at the end of set_signed_cookie accepts these keys: | Key | Description | |---|---| | `max_age` | Lifetime in seconds — 86400 = 1 day, omit for session cookie | | `same_site` | "Strict" / "Lax" / "None" — CSRF protection, default "Lax" | | `http_only` | Hide from JavaScript — default true | | `secure` | HTTPS only — set true in production | | `path` | Cookie scope — default "/" | ## `Full example` ```ruby stitch "frankiecookie" SECRET = "my-secret-key" app = web_app() # Write a signed cookie on login app.post("/login") do |req| username = req.json["username"] resp = html_response("

    Logged in as #{username}

    ") set_signed_cookie(resp, "user", username, SECRET, {max_age: 86400}) resp end # Read and verify it on subsequent requests app.get("/me") do |req| username = get_signed_cookie(req, "user", SECRET) if username == nil html_response("

    Not logged in

    ", 401) else html_response("

    Hello, #{username}!

    ") end end # Expire it on logout app.get("/logout") do |req| resp = html_response("

    Logged out

    ") delete_cookie(resp, "user") resp end app.run(3000) ``` ```bash ## `Test it` # Test it curl -X POST http://localhost:3000/login \ -H "Content-Type: application/json" \ -d '{"username": "Alice"}' -c cookies.txt curl http://localhost:3000/me -b cookies.txt # Hello, Alice! curl http://localhost:3000/logout -b cookies.txt -c cookies.txt curl http://localhost:3000/me -b cookies.txt # Not logged in ``` **`Remember — the value is signed not encrypted, so store a user ID and look up the rest from the database, never a password or token.`** --- # Frankieauth HTTP Basic Auth and Bearer token authentication for Frankie web apps. Zero dependencies — uses Frankie's built-in `hmac_sign` / `hmac_verify` and `base64_decode`. Introduced in **v1.15**. --- ## Functions ### `basic_auth_ok?(req, expected_user, expected_pass)` Validates an HTTP Basic Auth header against a known username/password. Returns `true` if the credentials match, `false` otherwise (including when the header is absent). ### `auth_token_create(subject, secret)` Creates a signed Bearer token for a given subject string (e.g. a username or user ID). Returns the token as a string. ### `auth_token_verify(req, secret)` Reads and verifies a Bearer token from the `Authorization` header. Returns the original subject string if valid, or `nil` if the header is missing, malformed, or the signature doesn't match. ### `bearer_required(req, secret)` Like `auth_token_verify` but short-circuits with `halt(401, "Unauthorized")` if the token is absent or invalid. Returns the subject on success — useful for protected routes. --- ## Basic Auth Example ```ruby stitch "frankieauth" app = web_app() app.use do |req, next_fn| if not basic_auth_ok?(req, "admin", env("ADMIN_PASS", "secret")) halt(401, "Unauthorized") end next_fn.(req) end app.get("/dashboard") do |req| html_response("

    Dashboard

    ") end app.run(3000) ``` ```bash # Test it curl http://localhost:3000/dashboard -u admin:secret # Dashboard curl http://localhost:3000/dashboard -u admin:wrong # 401 Unauthorized ``` --- ## Bearer Token Example ```ruby stitch "frankieauth" SECRET = env("TOKEN_SECRET", "dev-secret") app = web_app() # Login — exchange credentials for a token app.post("/login") do |req| user = req.json["username"] # In production: verify user + password against your database first token = auth_token_create(user, SECRET) json_response({token: token}) end # Protected route — token required app.get("/me") do |req| user = bearer_required(req, SECRET) json_response({user: user}) end # Optional verification (no auto-halt) app.get("/profile") do |req| user = auth_token_verify(req, SECRET) if user == nil json_response({error: "not authenticated"}, 401) else json_response({user: user, plan: "free"}) end end app.run(3000) ``` ```bash # Get a token curl -X POST http://localhost:3000/login \ -H "Content-Type: application/json" \ -d '{"username": "alice"}' # {"token": "alice:be38cbad..."} # Use the token curl http://localhost:3000/me \ -H "Authorization: Bearer alice:be38cbad..." # {"user": "alice"} # Missing token curl http://localhost:3000/me # 401 Unauthorized ``` --- ## Notes - Tokens are HMAC-SHA256 signed strings — tamper-proof but **not encrypted**. Store a user ID as the subject, not a password or sensitive value. - Tokens do not expire by default. For expiry, include a timestamp in the subject and validate it in your route handler. - `basic_auth_ok?` accepts both `Authorization` and `authorization` headers (case-insensitive). - `basic_auth_ok?` handles passwords that contain colons (splits only on the first one). --- # Frankieratelimit In-memory per-IP rate limiting middleware for Frankie web apps. No dependencies. Uses a sliding window algorithm — resets on server restart by design. Introduced in **v1.15**. --- ## Functions ### `rate_limit_check(req, next_fn, max: 60, window: 60)` Checks the request against the rate limit for the client IP (read from `X-Forwarded-For`). If the limit is exceeded it calls `halt(429, "Too Many Requests")`; otherwise it calls `next_fn.(req)` to continue the middleware chain. | Parameter | Default | Description | |---|---|---| | `req` | — | The incoming request object | | `next_fn` | — | The next middleware function, or `nil` to skip chaining | | `max` | `60` | Maximum number of requests allowed in the window | | `window` | `60` | Sliding window size in seconds | ### `rate_limit_reset(ip, window: 60)` Clears the rate limit record for a given IP and window. Useful in tests or admin tooling. --- ## Default Limit (60 req/min globally) ```ruby stitch "frankieratelimit" app = web_app() app.use do |req, next_fn| rate_limit_check(req, next_fn) end app.get("/") do |req| json_response({status: "ok"}) end app.run(3000) ``` --- ## Custom Limits per Route ```ruby stitch "frankieratelimit" app = web_app() # Strict limit on the login endpoint: 5 requests per minute app.post("/login") do |req| rate_limit_check(req, nil, max: 5, window: 60) # ... login logic here json_response({token: "..."}) end # Relaxed limit on the API: 200 requests per minute app.use do |req, next_fn| rate_limit_check(req, next_fn, max: 200, window: 60) end app.get("/api/data") do |req| json_response({data: []}) end app.run(3000) ``` --- ## Combining with `frankieauth` ```ruby stitch "frankieratelimit" stitch "frankieauth" SECRET = env("TOKEN_SECRET", "dev-secret") app = web_app() # Rate limit all requests app.use do |req, next_fn| rate_limit_check(req, next_fn, max: 100, window: 60) end # Auth on protected routes app.get("/api/me") do |req| user = bearer_required(req, SECRET) json_response({user: user}) end app.run(3000) ``` --- ## Notes - IP is read from the `X-Forwarded-For` header. If behind a load balancer or proxy, make sure this header is set correctly. - State is in-memory — all counts reset when the server restarts. For persistent or distributed rate limiting, store counts in a database or cache instead. - Passing `nil` as `next_fn` skips middleware chaining — useful when calling `rate_limit_check` directly inside a route handler rather than from `app.use`. - The sliding window counts only requests made within the last `window` seconds, so limits recover gradually rather than resetting all at once. --- # Frankiemail Send email via SMTP from any Frankie script. Zero external dependencies — uses Python's built-in `smtplib` under the hood. Introduced in **v1.16**. --- ## Functions ### `send_mail(opts)` Send an email. All parameters are keyword arguments with defaults, so you only pass what you need. | Option | Default | Description | |---|---|---| | `to` | `""` | Recipient address | | `subject` | `""` | Email subject line | | `body` | `""` | Plain-text or HTML body | | `sender` | `"frankie@localhost"` | Sender address (the From: header) | | `smtp` | `"localhost"` | SMTP server hostname | | `port` | `587` | SMTP port — `587` = STARTTLS, `465` = SSL, `25` = plain | | `user` | `""` | SMTP username (leave blank for unauthenticated) | | `password` | `""` | SMTP password | | `html` | `false` | Set `true` to send an HTML body | | `cc` | `""` | CC address | | `bcc` | `""` | BCC address | Returns `{ok: true}` on success, or `{ok: false, error: "..."}` on failure. --- ## Basic Example ```ruby stitch "frankiemail" result = send_mail( to: "alice@example.com", subject: "Hello from Frankie!", body: "This was sent by a Frankie script.", sender: env("MAIL_FROM", "bot@example.com"), smtp: env("SMTP_HOST", "smtp.gmail.com"), port: 587, user: env("SMTP_USER"), password: env("SMTP_PASS") ) if result["ok"] puts "Email sent!" else puts "Failed: #{result["error"]}" end ``` --- ## HTML Email ```ruby stitch "frankiemail" html_body = <<~HTML

    Frankie Report

    Your nightly job completed at #{now().format("%H:%M")}.

    Records processed: 1,024

    HTML send_mail( to: "reports@example.com", subject: "Nightly Report", body: html_body, html: true, smtp: env("SMTP_HOST"), user: env("SMTP_USER"), password: env("SMTP_PASS") ) ``` --- ## With CC / BCC ```ruby stitch "frankiemail" send_mail( to: "alice@example.com", cc: "manager@example.com", bcc: "audit-log@example.com", subject: "Deployment complete", body: "v1.16 deployed to production.", smtp: env("SMTP_HOST"), user: env("SMTP_USER"), password: env("SMTP_PASS") ) ``` --- ## Error Handling ```ruby stitch "frankiemail" result = send_mail( to: "ops@example.com", subject: "Alert: disk usage > 90%", body: "Please investigate immediately.", smtp: env("SMTP_HOST", "localhost"), user: env("SMTP_USER", ""), password: env("SMTP_PASS", "") ) if not result["ok"] puts "Mail error: #{result["error"]}" # Fallback: write to a local log instead file_append("mail_errors.log", "#{now()}: #{result["error"]}\n") end ``` --- ## Sending from a Script A common pattern is to run a Frankie script as a cron job and email the output: ```ruby stitch "frankiemail" db = db_open("app.db") rows = db.find_all("events") db.close lines = rows.map do |r| "#{r["created_at"]} #{r["type"]} #{r["user"]}" end send_mail( to: env("REPORT_EMAIL"), subject: "Daily event log — #{today().format("%Y-%m-%d")}", body: lines.join("\n"), smtp: env("SMTP_HOST"), user: env("SMTP_USER"), password: env("SMTP_PASS") ) ``` --- ## Notes - `port: 587` uses STARTTLS, which is compatible with Gmail, SendGrid, Mailgun, Postmark, and most hosted SMTP providers. - `port: 465` uses SSL/TLS directly. `port: 25` sends with no encryption and no auth. - For Gmail, use an **App Password** (not your account password) and ensure "Less secure app access" or OAuth2 is configured. - Set credentials via `env()` rather than hardcoding them. A `.env` file loaded with `dotenv()` works well. - `frankiemail` is a thin Frankie wrapper around the built-in `smtp_send()` stdlib function, which uses Python's `smtplib`. --- # Frankiecli Structured command-line argument parsing for Frankie scripts. Zero dependencies — pure `.fk`, built on `argv()`. Introduced in **v1.16**. --- ## Functions ### `cli_parse(args)` Parse a raw `argv()` vector into a structured hash. ``` { args: [...], # positional arguments (non-flag values) flags: {...}, # boolean flags — {verbose: true, dry_run: true} options: {...}, # named values — {output: "file.txt", port: "8080"} command: "..." # first positional arg (or nil), for subcommand CLIs } ``` Supported input formats: | Input | Result | |---|---| | `--flag` | `flags["flag"] = true` | | `--no-flag` | `flags["flag"] = false` | | `--key value` | `options["key"] = "value"` | | `--key=value` | `options["key"] = "value"` | | `-f` | `flags["f"] = true` | | `positional` | pushed to `args` | Dashes in flag/option names are converted to underscores: `--dry-run` → `flags["dry_run"]`. --- ### `cli_get(cli, key, default)` Get a named option value, or `default` if the option was not passed. ```ruby output = cli_get(cli, "output", "result.txt") port = cli_get(cli, "port", "3000") ``` --- ### `cli_flag(cli, name)` Check if a boolean flag was passed. Returns `false` if absent. ```ruby verbose = cli_flag(cli, "verbose") dry_run = cli_flag(cli, "dry-run") # normalized automatically ``` --- ### `cli_arg(cli, index, default)` Get a positional argument by index, or `default` if not enough args were given. ```ruby filename = cli_arg(cli, 0, "input.txt") target = cli_arg(cli, 1, "output.txt") ``` --- ### `cli_require(cli, key, msg)` Like `cli_get` but halts with an error message and `exit(1)` if the option is missing. ```ruby db_url = cli_require(cli, "db", "Please provide --db ") ``` --- ## Quick Start ```ruby stitch "frankiecli" cli = cli_parse(argv()) name = cli_get(cli, "name", "World") debug = cli_flag(cli, "verbose") outfile = cli_get(cli, "output", "out.txt") puts "Hello, #{name}!" puts "Debug mode: #{debug}" puts "Output: #{outfile}" ``` ```bash frankiec run hello.fk --name Alice --verbose --output report.txt # Hello, Alice! # Debug mode: true # Output: report.txt ``` --- ## Subcommand Pattern ```ruby stitch "frankiecli" cli = cli_parse(argv()) cmd = cli["command"] if cmd == "build" target = cli_get(cli, "target", "debug") puts "Building for #{target}..." elsif cmd == "deploy" env_name = cli_require(cli, "env", "Usage: deploy --env ") dry_run = cli_flag(cli, "dry-run") puts "Deploying to #{env_name}#{dry_run ? " (dry run)" : ""}..." elsif cmd == "help" or cmd == nil puts "Usage: myscript.fk [options]" puts " build --target debug|release" puts " deploy --env [--dry-run]" else puts "Unknown command: #{cmd}" exit(1) end ``` ```bash frankiec run myscript.fk deploy --env production # Deploying to production... frankiec run myscript.fk deploy --env staging --dry-run # Deploying to staging (dry run)... ``` --- ## --no-flag Negation ```ruby stitch "frankiecli" # Pass --no-color to disable colors cli = cli_parse(argv()) colored = cli_flag(cli, "color") # false if --no-color was passed if colored puts green("All good!") else puts "All good!" end ``` --- ## Full Example ```ruby stitch "frankiecli" cli = cli_parse(argv()) # Required — exits with error if missing input = cli_require(cli, "input", "Usage: report.fk --input [--output ] [--verbose]") # Optional with defaults output = cli_get(cli, "output", "report.txt") verbose = cli_flag(cli, "verbose") if verbose puts "Reading: #{input}" end rows = csv_parse(file_read(input)) puts "Rows: #{rows.length}" file_write(output, rows.map do |r| r.to_s end.join("\n")) puts "Written to #{output}" ``` --- ## Notes - All option names are normalized to `snake_case`: `--dry-run` → `options["dry_run"]`. - `cli_parse` does not call `argv()` automatically — pass `argv()` explicitly so you can also pass test arrays. - Positional arguments come before or between flags; `--key value` consumes the next token only when it doesn't start with `-`. --- # Frankiecache In-memory key/value cache with optional TTL (time-to-live). Zero dependencies — pure `.fk`, no external libraries. State resets on process restart — use the database for persistence. Introduced in **v1.16**. --- ## Functions ### `cache_set(key, value, ttl: 0)` Store a value under `key`. If `ttl > 0`, the entry expires after that many seconds. Returns the stored value. ```ruby cache_set("user:42", {name: "Alice"}) # no expiry cache_set("session:abc", {user: "Alice"}, ttl: 300) # expires in 5 min ``` --- ### `cache_get(key)` Retrieve a cached value. Returns `nil` if the key does not exist or has expired. ```ruby user = cache_get("user:42") if user == nil # cache miss — load from database end ``` --- ### `cache_set?(key)` Returns `true` if the key exists and has not expired. ```ruby if cache_set?("config") cfg = cache_get("config") end ``` --- ### `cache_delete(key)` Remove a single key from the cache. ```ruby cache_delete("user:42") ``` --- ### `cache_clear()` Remove all entries from the cache. ```ruby cache_clear() ``` --- ### `cache_size()` Return the number of live (non-expired) entries. ```ruby puts "#{cache_size()} entries in cache" ``` --- ### `cache_fetch(key, ttl: 0)` > **Note:** Block-based `cache_fetch` is not yet supported in this version of Frankie's stitch system. Use the explicit set/get pattern below instead. --- ## Quick Start ```ruby stitch "frankiecache" # Store user data for 5 minutes cache_set("user:42", {name: "Alice", role: "admin"}, ttl: 300) user = cache_get("user:42") if user != nil puts "Cache hit: #{user["name"]}" else puts "Cache miss" end puts cache_size() # 1 ``` --- ## Cache-Aside Pattern The most common caching pattern — check the cache first, load from the database on a miss, then cache the result: ```ruby stitch "frankiecache" def get_user(db, id) key = "user:#{id}" cached = cache_get(key) if cached != nil return cached end user = db.find_one("users", {id: id}) if user != nil cache_set(key, user, ttl: 60) end return user end db = db_open("app.db") user = get_user(db, 42) puts user["name"] ``` --- ## TTL-Based Rate Limiting (simple) ```ruby stitch "frankiecache" def allow_request?(ip) key = "rate:#{ip}" count = cache_get(key) if count == nil cache_set(key, 1, ttl: 60) return true end if count >= 30 return false end cache_set(key, count + 1, ttl: 60) return true end puts allow_request?("10.0.0.1") # true ``` --- ## Config Caching ```ruby stitch "frankiecache" def load_config() cached = cache_get("app_config") if cached != nil return cached end cfg = json_parse(file_read("config.json")) cache_set("app_config", cfg, ttl: 300) return cfg end config = load_config() puts config["database"]["host"] ``` --- ## Cache Stats and Inspection ```ruby stitch "frankiecache" cache_set("a", 1) cache_set("b", 2, ttl: 10) cache_set("c", 3, ttl: 10) puts "size: #{cache_size()}" # 3 puts "a exists: #{cache_set?("a")}" # true puts "x exists: #{cache_set?("x")}" # false cache_delete("b") puts "after delete: #{cache_size()}" # 2 cache_clear() puts "after clear: #{cache_size()}" # 0 ``` --- ## Notes - The cache is **process-local and in-memory** — it does not persist across restarts and is not shared between processes. - TTL is checked lazily on `cache_get` — expired entries are evicted on access, not by a background timer. - `cache_size()` counts only live (non-expired) entries by iterating and checking TTLs. - For persistent or distributed caching, use an external store (Redis, SQLite, etc.) and call it from your Frankie script directly. --- # Examples ## Showcase Projects (v1.19-v1.20) Beyond the single-file snippets below, Frankie ships six complete, playable projects — each a self-contained `.fk` program (or small pinned-stitch project) you can read in one sitting and run with one command. They install with Frankie itself, so there's nothing extra to download. Grab any of them with `frankiec examples`, which works the same way whether Frankie was installed via Homebrew, `git clone` + `install.py`, or an unpacked zip: ```bash frankiec examples # list everything bundled with this install frankiec examples snake # copies the project into the current directory cd snake && frankiec run main.fk ``` | Project | Renderer / stack | What it shows | |---|---|---| | 🧟 `zombie_chat` | WebSockets | Multi-room chat — server + web UI in one file | | ⚡ `word_reanimator` | WebSockets | Multiplayer browser hangman, shared state | | 💰 `frankie_ledger` | SQLite + stitches | Terminal expense tracker with R-style stats | | 🐍 `snake` | `frankiegame` (terminal) | The whole game engine API in ~80 lines | | 🧟 `zombie_invaders` | `frankiecanvas` (browser) | Rects, sprites, waves, beeps | | 🏓 `pong` | `frankiecanvas` (browser) | Multiplayer via `on_player_key` — two tabs, one ball | Each project bundles to a single self-contained `.py` with `frankiec bundle` — no Frankie installation required to run the result. --- ## Hello World ```ruby name = "World" puts "Hello, #{name}!" puts "Welcome to Frankie — stitched together from the finest languages." ``` ## Fizzbuzz ```ruby for i in 1..100 if i % 15 == 0 puts "FizzBuzz" elsif i % 3 == 0 puts "Fizz" elsif i % 5 == 0 puts "Buzz" else puts i end end ``` ## Fibonacci ```ruby def fibonacci(n) if n <= 1 return n end return fibonacci(n - 1) + fibonacci(n - 2) end for i in 0..10 puts "fib(#{i}) = #{fibonacci(i)}" end ``` ## Stats ```ruby data = [23, 45, 12, 67, 34, 89, 15, 56, 78, 42] puts "Mean : #{mean(data)}" puts "StdDev : #{stdev(data)}" puts "Median : #{median(data)}" # Pipe operator data |> sum |> puts # Vectorized operations v = [1, 2, 3, 4, 5] puts v * 2 # [2, 4, 6, 8, 10] ``` ## Sorting ```ruby def bubble_sort(arr) n = length(arr) i = 0 while i < n - 1 j = 0 while j < n - i - 1 if arr[j] > arr[j + 1] temp = arr[j] arr[j] = arr[j + 1] arr[j + 1] = temp end j = j + 1 end i = i + 1 end return arr end def selection_sort(arr) n = length(arr) i = 0 while i < n min_idx = i j = i + 1 while j < n if arr[j] < arr[min_idx] min_idx = j end j = j + 1 end temp = arr[i] arr[i] = arr[min_idx] arr[min_idx] = temp i = i + 1 end return arr end puts "=== Frankie Sorting Algorithms ===" puts "" data1 = [64, 34, 25, 12, 22, 11, 90] data2 = [29, 10, 14, 37, 13, 0, 99, 55] puts "Original (1): #{data1}" sorted1 = bubble_sort(data1) puts "Bubble Sort : #{sorted1}" puts "" puts "Original (2): #{data2}" sorted2 = selection_sort(data2) puts "Select Sort : #{sorted2}" puts "" puts "=== Using built-in sort ===" v = [5, 3, 8, 1, 9, 2, 7, 4, 6] puts "Unsorted: #{v}" puts "Sorted : #{v.sort}" ``` ## Leds ```ruby leds = { 0: [' _ ', '| | ', '|_| '], 1: [' ', '| ', '| ' ], 2: [' _ ', ' _| ', '|_ '], 3: ['_ ', '_| ', '_| ' ], 4: [' ', '|_| ', ' | '], 5: [' _ ', '|_ ', ' _| '], 6: [' _ ', '|_ ', '|_| '], 7: ['_ ', ' | ', ' | '], 8: [' _ ', '|_| ', '|_| '], 9: [' _ ', '|_| ', ' _| '] } print "Enter a number: " number = input("") for i in 0...3 for j in 0...length(number) print leds[to_int(number[j])][i] end puts "" end ``` ## Database ```ruby puts "╔══════════════════════════════════════════╗" puts "║ Frankie Database Demo (SQLite) ║" puts "╚══════════════════════════════════════════╝" puts "" # ── 1. Open an in-memory database ──────────────────────────────── db = db_open(":memory:") puts "── 1. Opened in-memory database ──" puts db puts "" # ── 2. Create tables ───────────────────────────────────────────── puts "── 2. Create Tables ──" db.exec("CREATE TABLE departments (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL UNIQUE)") db.exec("CREATE TABLE employees (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, age INTEGER NOT NULL, department TEXT NOT NULL, salary REAL NOT NULL)") puts "Tables created: #{db.tables}" puts "" # ── 3. Insert rows ─────────────────────────────────────────────── puts "── 3. Insert Rows ──" # Low-level exec with params (? placeholders — safe from SQL injection) db.exec("INSERT INTO departments (name) VALUES (?)", ["Engineering"]) db.exec("INSERT INTO departments (name) VALUES (?)", ["Marketing"]) db.exec("INSERT INTO departments (name) VALUES (?)", ["Finance"]) # Convenience insert with hash db.insert("employees", {name: "Alice", age: 32, department: "Engineering", salary: 95000}) db.insert("employees", {name: "Bob", age: 28, department: "Engineering", salary: 87000}) db.insert("employees", {name: "Carol", age: 35, department: "Marketing", salary: 72000}) db.insert("employees", {name: "Dave", age: 41, department: "Finance", salary: 105000}) db.insert("employees", {name: "Eve", age: 29, department: "Engineering", salary: 91000}) db.insert("employees", {name: "Frank", age: 38, department: "Marketing", salary: 68000}) db.insert("employees", {name: "Grace", age: 45, department: "Finance", salary: 118000}) db.insert("employees", {name: "Hector", age: 27, department: "Engineering", salary: 82000}) puts "Inserted #{db.count("employees")} employees" puts "Inserted #{db.count("departments")} departments" puts "" # ── 4. Query all rows ──────────────────────────────────────────── puts "── 4. All Employees ──" all = db.find_all("employees") all.each do |row| puts " [#{row["id"]}] #{row["name"]} | #{row["department"]} | age #{row["age"]} | $#{row["salary"]}" end puts "" # ── 5. Filtered queries ────────────────────────────────────────── puts "── 5. Engineering Team ──" engineers = db.find("employees", {department: "Engineering"}) engineers.each do |e| puts " #{e["name"]} (age #{e["age"]}) — $#{e["salary"]}" end puts "" # ── 6. Raw SQL queries ─────────────────────────────────────────── puts "── 6. Employees Over 35 ──" seniors = db.query("SELECT name, age, salary FROM employees WHERE age > ? ORDER BY age", [35]) seniors.each do |row| puts " #{row["name"]} | age #{row["age"]} | $#{row["salary"]}" end puts "" # ── 7. Aggregation ────────────────────────────────────────────── puts "── 7. Department Summary ──" summary = db.query("SELECT department, COUNT(*) AS headcount, AVG(salary) AS avg_salary, MAX(salary) AS top_salary FROM employees GROUP BY department ORDER BY avg_salary DESC") summary.each do |row| avg = to_int(row["avg_salary"]) puts " #{row["department"]}: #{row["headcount"]} people | avg $#{avg} | top $#{row["top_salary"]}" end puts "" # ── 8. find_one ────────────────────────────────────────────────── puts "── 8. Find One ──" alice = db.find_one("employees", {name: "Alice"}) puts "Found: #{alice["name"]} in #{alice["department"]}" missing = db.find_one("employees", {name: "Nobody"}) puts "Missing: #{missing}" puts "" # ── 9. Update ──────────────────────────────────────────────────── puts "── 9. Update ──" updated = db.update("employees", {salary: 100000}, {name: "Bob"}) puts "Updated #{updated} row(s)" bob = db.find_one("employees", {name: "Bob"}) puts "Bob's new salary: $#{bob["salary"]}" puts "" # ── 10. Transaction ────────────────────────────────────────────── puts "── 10. Transaction ──" db.transaction do db.insert("employees", {name: "Ivan", age: 31, department: "Finance", salary: 97000}) db.insert("employees", {name: "Julia", age: 26, department: "Engineering", salary: 79000}) end puts "After transaction: #{db.count("employees")} employees" puts "" # ── 11. Transaction rollback on error ──────────────────────────── puts "── 11. Transaction Rollback ──" count_before = db.count("employees") begin db.transaction do db.insert("employees", {name: "Karl", age: 33, department: "Marketing", salary: 71000}) raise "simulated error mid-transaction" db.insert("employees", {name: "Lena", age: 29, department: "Marketing", salary: 66000}) end rescue e puts "Rolled back: #{e}" end puts "Count unchanged: #{db.count("employees") == count_before}" puts "" # ── 12. Delete ─────────────────────────────────────────────────── puts "── 12. Delete ──" deleted = db.delete("employees", {name: "Hector"}) puts "Deleted #{deleted} row(s)" puts "Remaining: #{db.count("employees")} employees" puts "" # ── 13. Schema introspection ───────────────────────────────────── puts "── 13. Schema Introspection ──" puts "Tables: #{db.tables}" cols = db.columns("employees") puts "employees columns:" cols.each do |col| puts " #{col["name"]} (#{col["type"]})" end puts "" # ── 14. Frankie-style stats on query results ───────────────────── puts "── 14. Stats on Query Results ──" salaries = db.query("SELECT salary FROM employees") salary_list = salaries.map do |row| row["salary"] end puts "Salaries : #{salary_list}" puts "Mean salary: $#{to_int(mean(salary_list))}" puts "Max salary : $#{max(salary_list)}" puts "Min salary : $#{min(salary_list)}" puts "Std dev : $#{to_int(stdev(salary_list))}" puts "" # ── 15. Persistent file database ───────────────────────────────── puts "── 15. File Database ──" db2 = db_open("/tmp/frankie_demo.db") db2.exec("CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, content TEXT)") db2.insert("notes", {content: "Frankie has SQLite support!"}) db2.insert("notes", {content: "Zero external dependencies."}) notes = db2.find_all("notes") notes.each do |n| puts " Note #{n["id"]}: #{n["content"]}" end db2.close file_delete("/tmp/frankie_demo.db") puts "File DB created, used, and cleaned up." puts "" # ── Done ───────────────────────────────────────────────────────── db.close puts "Database connection closed." puts "Frankie + SQLite — alive and querying! 🧟🗄️" ``` ## Hashmaps ```ruby puts "╔══════════════════════════════════╗" puts "║ Frankie Hashmap Demo ║" puts "╚══════════════════════════════════╝" puts "" # ─── 1. Creating a Hash ─────────────────────────────────────────────────────── puts "── 1. Creating a Hash ──" person = {name: "Alice", age: 30, city: "Lima"} puts person puts "" # ─── 2. Reading Values ──────────────────────────────────────────────────────── puts "── 2. Reading Values ──" puts "Name : #{person[:name]}" puts "Age : #{person[:age]}" puts "City : #{person[:city]}" puts "" # ─── 3. Adding & Updating Keys ─────────────────────────────────────────────── puts "── 3. Adding & Updating ──" person[:job] = "Engineer" person[:age] = 31 puts "After update: #{person}" puts "" # ─── 4. Keys & Values ──────────────────────────────────────────────────────── puts "── 4. Keys & Values ──" puts "Keys : #{person.keys}" puts "Values : #{person.values}" puts "Size : #{person.size}" puts "" # ─── 5. has_key? ───────────────────────────────────────────────────────────── puts "── 5. Checking Keys ──" puts "Has :name? #{person.has_key?(:name)}" puts "Has :email? #{person.has_key?(:email)}" puts "" # ─── 6. delete ─────────────────────────────────────────────────────────────── puts "── 6. Deleting a Key ──" person.delete(:city) puts "After deleting :city: #{person}" puts "" # ─── 7. fetch with default ─────────────────────────────────────────────────── puts "── 7. Fetch with Default ──" job = person.fetch(:job, "Unknown") salary = person.fetch(:salary, 0) puts "Job : #{job}" puts "Salary : #{salary}" puts "" # ─── 8. Iterating with each ────────────────────────────────────────────────── puts "── 8. Iterating (each) ──" person.each do |key, val| puts " #{key} => #{val}" end puts "" # ─── 9. merge ──────────────────────────────────────────────────────────────── puts "── 9. Merging Hashes ──" extra = {email: "alice@example.com", country: "Peru"} full = person.merge(extra) puts "Merged: #{full}" puts "" # ─── 10. Nested Hashes ─────────────────────────────────────────────────────── puts "── 10. Nested Hashes ──" company = { name: "Frankieworks", address: {street: "Av. Larco", city: "Miraflores"}, employees: 42 } puts "Company : #{company[:name]}" puts "Street : #{company[:address][:street]}" puts "City : #{company[:address][:city]}" puts "" # ─── 11. Hash of Vectors ───────────────────────────────────────────────────── puts "── 11. Hash of Vectors ──" scores = { alice: [90, 85, 92], bob: [78, 80, 88], carol: [95, 99, 97] } scores.each do |student, s| avg = mean(s) puts " #{student}: avg = #{avg}" end puts "" # ─── 12. Building a Hash dynamically ───────────────────────────────────────── puts "── 12. Building Dynamically ──" word_count = {} words = ["frankie", "is", "fun", "frankie", "is", "fast", "frankie"] for word in words if word_count.has_key?(word) word_count[word] = word_count[word] + 1 else word_count[word] = 1 end end puts "Word counts:" word_count.each do |word, count| puts " #{word}: #{count}" end puts "" puts "Done! Frankie hashmaps are alive 🧟" ``` ## Webapp ```ruby # Run with: frankiec run examples/webapp.fk # Then visit: http://localhost:3000 app = web_app() # ── Simple HTML response ────────────────────────────────────────────────────── app.get("/") do |req| html_response("

    Hello from Frankie! 🧟

    Try /greet/world

    ") end # ── Path parameters ─────────────────────────────────────────────────────────── app.get("/greet/:name") do |req| name = req.params["name"] response("Hello, #{name}!") end # ── Query parameters ────────────────────────────────────────────────────────── # GET /search?q=frankie app.get("/search") do |req| q = req.query["q"] if q == nil return response("Please provide ?q=something") end response("You searched for: #{q}") end # ── JSON response ───────────────────────────────────────────────────────────── app.get("/api/status") do |req| json_response({status: "ok", language: "Frankie", version: "1.4"}) end # ── In-memory notes store ───────────────────────────────────────────────────── # Use a wrapper hash so handlers can mutate the list without scoping issues store = {notes: []} app.get("/notes") do |req| json_response(store["notes"]) end app.post("/notes") do |req| data = req.json if data == nil return halt(400, "Expected JSON body") end note = {id: length(store["notes"]) + 1, text: data["text"]} store["notes"].push(note) json_response(note, 201) end app.get("/notes/:id") do |req| id = to_int(req.params["id"]) found = nil store["notes"].each do |n| if n["id"] == id found = n end end if found == nil return halt(404, "Note not found") end json_response(found) end app.delete("/notes/:id") do |req| id = to_int(req.params["id"]) store["notes"] = store["notes"].select do |n| n["id"] != id end response("Deleted") end # ── Custom 404 ──────────────────────────────────────────────────────────────── app.not_found do |req| html_response("

    404

    No route for #{req.path}

    ", 404) end # ── Start ───────────────────────────────────────────────────────────────────── app.run(3000) ``` --- # Showcase The showcase is a single runnable file that demonstrates every major Frankie feature from v1.0 through v1.22. It is the fastest way to see the whole language in one place. ```bash frankiec run examples/showcase.fk # or, without a local checkout: frankiec examples showcase && frankiec run showcase.fk ``` Want the playable versions instead? Grab the standalone [showcase projects](index.md#showcase-projects-v119-v120) (Snake, Pong, Zombie Chat, and more) with `frankiec examples`. --- ## What It Covers The showcase is divided into 83 numbered sections, one per feature area. Each section is self-contained and prints its own output. | # | Section | Introduced | |---|---|---| | 1 | Error Handling — `begin / rescue / ensure` | v1.0 | | 2 | Nil Safety — `&.` operator | v1.7 | | 3 | String Templates — `template()` | v1.7 | | 4 | File System — `file_mkdir`, `dir_list`, `file_copy` | v1.7 | | 5 | Regex — `matches`, `match_all`, `sub`, `gsub`, `=~` | v1.0 | | 6 | File I/O — `file_read`, `file_write`, `file_lines`, `file_append` | v1.0 | | 7 | Collections & Iterators — `select`, `reject`, `map`, `reduce`, `each_with_object` | v1.1 | | 8 | Compound Assignment — `+=`, `-=`, `*=`, `//=`, `**=` | v1.6 | | 9 | R-style Statistics — `mean`, `stdev`, `median`, pipe `\|>` | v1.0 | | 10 | JSON & CSV | v1.3 | | 11 | SQLite Database | v1.2 | | 12 | DateTime | v1.3 | | 13 | Randomness — `rand_int`, `shuffle`, `sample` | v1.5 | | 14 | Constants & Loop Control — `next`, `break`, `break value` | v1.5 | | 15 | Mini Log Analyser — a real-world composition | v1.0 | | 16 | Lambdas — `->(x) { }`, `.call`, higher-order functions | v1.8 | | 17 | Hash Merge Operator `\|` | v1.8 | | 18 | `group_by` | v1.8 | | 19 | `each_slice` and `each_cons` | v1.8 | | 20 | Record Types — `record Point(x, y)` | v1.9 | | 21 | Hash `.dig` — safe deep access | v1.9 | | 22 | `zip()` — pair two vectors | v1.9 | | 23 | `frankiec fmt` and `frankiec docs` | v1.9 | | 24 | String & Vector `*` repetition | v1.10 | | 25 | Heredoc `<<~TEXT` | v1.10 | | 26 | `times()` standalone + `flatten(depth)` + `map_with_index` + `pp` | v1.10 | | 27 | `encode` / `decode` | v1.10 | | 28 | Implicit Return | v1.11 | | 29 | String `.replace()` | v1.11 | | 30 | String `.format(hash)` | v1.11 | | 31 | `.zip_with` — pair-wise transform | v1.11 | | 32 | Multiple Return Values | v1.11 | | 33 | String `.gsub` with Block | v1.12 | | 34 | Hash `.map_hash` | v1.12 | | 35 | `round(x, n)` | v1.12 | | 36 | Vector `.product(other)` | v1.12 | | 37 | String `.chars` | v1.12 | | 38 | `rescue FileNotFoundError` from file I/O | v1.12 | | 39 | `stitch` — package system | v1.13 | | 40 | `?` in user-defined function names | v1.13 | | 41 | Hash Destructuring — `{name, age} = user` | v1.14 | | 42 | Shape Pattern Matching — `when {role: "admin"}` | v1.14 | | 43 | `spawn` + `timeout` | v1.14 | | 44 | Ternary Operator — `x > 0 ? "pos" : "neg"` | v1.15 | | 45 | Keyword Default Params — `port: 5432` | v1.15 | | 46 | Splat Multi-Assign — `a, *rest = vec` | v1.15 | | 47 | `const` keyword | v1.15 | | 48 | `json_encode` + `base64` / `hmac` public | v1.15 | | 49 | `String#format` + path helpers + date arithmetic | v1.15 | | 50 | `shell()` + `dotenv()` | v1.16 | | 51 | `loop do...end` + `\|\|=` | v1.16 | | 52 | `transform_values` + `transform_keys` | v1.16 | | 53 | `String#scan` + `Hash#deep_merge` | v1.16 | | 54 | `frankiecli` stitch | v1.16 | | 55 | `frankiecache` stitch | v1.16 | | 56 | First-class Ranges — `.to_vec`, `.include?`, `.step` | v1.17 | | 57 | User-defined Error Types — `error` / `rescue Type => e` | v1.17 | | 58 | Namespaced Imports — `import "path" as name` | v1.17 | | 59 | Record Dot Access — `p1.x` | v1.17 | | 60 | `parallel_map` — thread-pool map | v1.17 | | 61 | TCP Sockets — `tcp_connect` / `tcp_serve` | v1.17 | | 62 | Test Stubs — `stub` / `unstub` | v1.17 | | 63 | Numeric Underscores + Scientific Notation — `1_000_000`, `2.5e-3` | v1.18 | | 64 | Set Operations — `.union` / `.intersect` / `.difference` | v1.18 | | 65 | `enum Status(pending, active, done)` | v1.18 | | 66 | `benchmark` — friendly timing | v1.18 | | 67 | WebSockets — `app.websocket` / `ws_connect` | v1.18 | | 68 | Gradual Type Annotations — `def f(x: Float) -> Float` | v1.19 | | 69 | UDP Sockets — `udp_listen`, `send_to`, `recv` | v1.19 | | 70 | TLS Clients — verified `wss://` / `tcp_connect(tls: true)` | v1.19 | | 71 | v1.19 Tooling — `--debug`, `--coverage`, `docs --html`, stitch URL installs | v1.19 | | 72 | `frankiegame` — terminal game engine, `run_game` / `max_ticks` | v1.20 | | 73 | Engine Helpers — `collide?`, `GAME_COLORS` | v1.20 | | 74 | `frankiecanvas` — same API, real HTML5-canvas pixels | v1.20 | | 75 | Image Sprites — `load_image` / `draw_image` | v1.21 | | 76 | WebAudio Synth — `synth_play`, `game_beep` | v1.21 | | 77 | `file_read_base64` — binary-safe reads | v1.21 | | 78 | 🧊 Language Freeze (historical) — The Book of Frankie | v1.21 | | 79 | Matrix Math — `matrix_identity`, `matrix_transpose`, `matrix_scale`, `matrix_multiply` | v1.22 | | 80 | Complex Numbers — `complex_new`, `complex_abs`, `complex_conj` | v1.22 | | 81 | Math Intrinsics — `sin`, `cos`, `atan2`, `exp`, `log`, `factorial`, `gcd`, `lcm`, `PI`, `E` | v1.22 | | 82 | Labeled Loops — `loop :name`, `break :name`, `next :name` | v1.22 | | 83 | 🧊 Language Freeze — The Book of Frankie | v1.22 | --- ## A Taste Here is a small excerpt from sections 7, 9, and 16 to show the feel: ```ruby # ── 7. Collections & Iterators ── data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] evens = data.select do |x| x % 2 == 0 end puts evens # [2, 4, 6, 8, 10] squared = data.map do |x| x * x end puts squared # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] total = data.reduce(0) do |acc, x| acc + x end puts total # 55 # ── 9. R-style Statistics ── nums = [23, 45, 12, 67, 34, 89, 56] puts mean(nums) # 46.57... puts stdev(nums) # 24.99... puts median(nums) # 45 nums |> sum |> puts # 326 # ── 16. Lambdas ── double = ->(x) { x * 2 } add = ->(a, b) { a + b } puts double.call(5) # 10 puts add.call(3, 4) # 7 def apply(fn, val) fn.call(val) end puts apply(double, 9) # 18 ``` --- ## Running Specific Sections The showcase runs from top to bottom as a single program. To run just one section, copy the relevant lines into a new file or into the REPL: ```bash frankiec repl ``` Then paste any section and press Enter. --- # What's New — Per Version Each version of Frankie ships a runnable `whats_new_vX.fk` example file that demonstrates every new feature introduced in that release. Every install (Homebrew, git clone, or unpacked zip) bundles the same set — grab one with `frankiec examples whats_new_v122` or run it straight from the source tree: ```bash frankiec run examples/whats_new_v122.fk ``` ## v1.22 — `whats_new_v122.fk` — "More FORTRAN" 🧮 **Theme:** One last feature pass before the freeze locks back in — leaning harder into Frankie's FORTRAN heritage. Pure Python stdlib, zero external dependencies, as always. | Feature | Summary | |---|---| | Matrix math | `+`/`-`/`/`/`%`/`**` now recurse through nested vectors, so matrices do real element-wise math instead of silently concatenating rows; `matrix_new`, `matrix_identity`, `matrix_shape`, `matrix_transpose`, `matrix_scale`, `matrix_multiply` | | Complex numbers | `complex_new(real, imag)` exposes Python's native complex type — `+`/`-`/`*`/`/`/`**` all work for free; `complex_real`/`complex_imag`/`complex_conj`/`complex_abs`; prints as `3+4i` | | Math intrinsics | `sin`/`cos`/`tan`/`asin`/`acos`/`atan`/`atan2`, `exp`/`log`/`log10`/`log2`, `factorial`/`gcd`/`lcm`, and constants `PI`/`E` | | Labeled loops | `loop`/`while`/`until`/`for` take an optional `:name` label; `break :name`/`next :name` target that exact loop from anywhere nested inside it | | `:symbol` is its own token | Previously indistinguishable from a plain string at the parser level — needed for `break :label` to be unambiguous; every existing use of `:name` as a value is unaffected | | 🧊 Language freeze moves to v1.22.0 | This was the explicitly-promised "last big addition" — only bug fixes and doc corrections from here | --- ## v1.21 — `whats_new_v121.fk` — "The Book Edition" 🧊 **Theme:** Real bitmap sprites and a proper synth API for `frankiecanvas`, a binary-safe file primitive underneath both, and a language freeze while the language gets a book written about it. Pure Python stdlib, zero external dependencies, as always. | Feature | Summary | |---|---| | `load_image(path)` + `draw_image(g, x, y, image, w:, h:)` | Real PNG/JPEG/GIF sprites in `frankiecanvas`, client-cached after the first frame; `frankiegame` gets matching calls with a `▒` placeholder for cross-engine parity | | `synth_play(g, freq:, wave:, dur:, gain:)` | Real WebAudio oscillator tones (sine/square/sawtooth/triangle) in `frankiecanvas`; `game_beep` is now a thin wrapper over it | | `file_read_base64(path)` | Binary-safe file read + Base64 in one call — what `load_image` uses internally | | `frankiec fmt` data-loss fix | Single-statement blocks with an assignment or postfix-if/unless body no longer silently collapse to `nil` | | 🧊 Language freeze | Grammar, stdlib, and stitch APIs locked while "The Book of Frankie" is written against this exact version — patch releases only until the freeze lifts | --- ## v1.20 — `whats_new_v120.fk` **Theme:** "It's Alive… and Playing" — two game engines, one shared API. Pure Python stdlib, zero external dependencies, as always. | Feature | Summary | |---|---| | `frankiegame` | Terminal game engine — raw keys via stdlib `termios`, double-buffered ANSI rendering, headless-safe for CI | | `frankiecanvas` | Browser game engine — same API, real pixels via HTML5 canvas streamed over WebSockets, multiplayer for free | | Shared engine API | `game_new`, `on_key`, `on_tick`, `draw`, `draw_sprite`, `collide?`, `run_game`, `render_frame`, `max_ticks:` for CI | | `on_player_key` (canvas-only) | Per-player input — every connected browser tab is a player | | `frankiec new --game` | Scaffold a playable starter with `frankiegame` pre-installed | | Showcase games | 🐍 `snake` (terminal), 🧟 `zombie_invaders` (browser), 🏓 `pong` (browser, multiplayer) | **Patch — v1.20.1:** arrow keys fixed in terminal games (`term_key()` now reads raw bytes); `frankiec examples [name]` to browse/copy bundled examples; official Homebrew formula (`brew install atejada/frankie/frankie`). --- ## v1.19 — `whats_new_v119.fk` **Theme:** "Under the microscope" — types, a real debugger, coverage. Pure Python stdlib, zero external dependencies, as always. | Feature | Summary | |---|---| | `def area(r: Float) -> Float` | Gradual type annotations — optional, checked statically by `check`/CI/LSP | | Stepping debugger | `(fkdb)` gains `s`/`n`/`stack`; `frankiec run --debug` breaks at line 1 | | `frankiec test --coverage` | Line coverage report + `.frankie_coverage.json`, read by the LSP | | TLS + UDP | `tcp_connect(tls: true)`, `ws_connect("wss://...")`, `udp_listen`/`udp_send` | | `frankiec docs --html` | Doc-comments rendered as styled single-page HTML | | Stitch installs from any URL | `frankiec stitch install https://.../foo.fk`, pinned in `stitch.lock` | | Showcase projects | 🧟 `zombie_chat`, ⚡ `word_reanimator`, 💰 `frankie_ledger` | --- ## v1.18 — `whats_new_v118.fk` **Theme:** "From projects to products" — edit (LSP), ship (bundle), connect (WebSockets), debug (breakpoint). Pure Python stdlib underneath, zero external dependencies, as always. | Feature | Summary | |---|---| | `frankiec lsp` | Language Server over stdio — live diagnostics, completion, hover docs in VS Code, Neovim, Helix, Zed | | `frankiec bundle` | Compile a program + all `require`/`import`/`stitch` targets into ONE self-contained `.py` — runs anywhere with Python 3.8+ | | WebSockets | `app.websocket("/ws/:room") do \|ws\| ... end` server + `ws_connect(url)` client — hand-rolled RFC 6455 | | `breakpoint` | Pause into a scoped debug REPL — `vars`, `where`, any Frankie expression; skipped when stdin isn't a tty | | `enum Status(pending, active, done)` | Named symbolic values — `Status.pending`, `.values`, `.include?`, `case/when` matching | | `benchmark "label" do ... end` | Time a block — prints `⏱ label: 12.3ms`, returns elapsed ms | | Set operations | `.union` / `.intersect` / `.difference` — order-preserving, deduplicating | | Numeric literals | Underscores `1_250_000` + scientific notation `6.022e23` | | Project-wide tooling | `frankiec check .` and `frankiec fmt --write .` recurse into directories | | Stitch lockfile | `stitch.lock` with sha256 pins — `frankiec stitch verify` / `update` | --- ## v1.17 — `whats_new_v117.fk` **Theme:** "Programs that grow" — namespacing, real static checking, typed errors, first-class ranges, easy concurrency, TCP sockets, and a stitch installer. Everything still pure Python stdlib, zero dependencies. | Feature | Summary | |---|---| | `import "path" as name` | Load a `.fk` file into its own namespace — `geo.circle_area(5)`, `geo.PI`; modules cached; `require` unchanged | | `error TypeName` | User-defined error types — `raise ValidationError, "msg"`, caught with `rescue ValidationError => e` | | `rescue Type => e` | New Ruby-style rescue binding (old `rescue Type e` form still works) | | First-class ranges | `r = 1..10` prints as `1..10`; `.to_vec`, `.include?`, `.step(n)`, `.sum`, `.first`, `.last` | | Range `case/when` | `when 90..100` tests membership — works with range values in variables too | | Record dot access | `p1.x` instead of `p1["x"]` — hash-style access still works | | `parallel_map` | `parallel_map(urls, workers: 8) do \|u\| ... end` — thread-pool map, results in input order | | TCP sockets | `tcp_connect` / `tcp_listen` / `tcp_serve` — `send_line`, `recv_line`, `peer`, threaded server loop | | `frankiec check` | Real static analysis — undefined names, wrong arg counts, unused locals; `--strict` for CI | | Cross-file tracebacks | Runtime errors point at the right file *and* line, in requires, imports and stitches | | `test` groups | `test "name", tags: ["slow"] do ... end` — filter with `--filter` / `--tag` | | `stub` / `unstub` | Swap any global function during tests — `stub("shell", ->(cmd) { fake })` | | Stitch installer | `frankiec stitch install frankiecolor [--global]`, `frankiec stitch list` | | REPL upgrades | Bare expressions echo `=> value`, `_` holds last result, `help ` shows docs | --- ## v1.16.2 — `whats_new_v116.fk` **Theme:** System Integration & Scripting Power — shell commands, environment loading, infinite loops, nil-coalescing assign, richer hash and string tools, and three new stitches for email, CLI parsing, and caching. | Feature | Summary | |---|---| | `shell(cmd)` | Run an OS command — returns `{stdout, stderr, exit_code, ok}` | | `dotenv(path)` | Load a `.env` file into the process environment — returns hash of loaded vars | | `loop do...end` | Infinite loop, exits only via `break` — cleaner than `while true` | | `\|\|=` | Nil-coalescing assign — `config \|\|= load_defaults()` | | `Hash#transform_values` | New hash with same keys, block-transformed values | | `Hash#transform_keys` | New hash with block-transformed keys, same values | | `Hash#deep_merge` | Recursive nested hash merge — unlike shallow `.merge` / `\|` | | `String#scan` | Extract all regex matches as a vector | | `frankiemail` stitch | Send email via SMTP — plain text, HTML, CC/BCC — zero deps | | `frankiecli` stitch | CLI argument parsing — flags, options, subcommands — zero deps | | `frankiecache` stitch | In-memory TTL cache — set/get/delete/clear/size — zero deps | --- ## v1.15 — `whats_new_v115.fk` **Theme:** Language Polish & Developer Ergonomics — cleaner syntax, more powerful stdlib, and two new web stitches. | Feature | Summary | |---|---| | `Ternary operator` | `x > 0 ? "pos" : "neg"` — right-associative, valid in any expression position | | `Keyword default params` | `def connect(host, port: 5432, ssl: true)` — `:` syntax now accepted alongside `=` | | `Splat in multi-assign` | `a, *rest = [1,2,3]` and `first, *mid, last = arr` — capture remaining elements | | `const` keyword | Explicit constant declaration — reassignment warns and preserves original value | | `fn.(args)` everywhere | Lambda call syntax now works in all contexts, not just web middleware | | `json_encode` | Preferred name for `json_dump`; accepts `pretty: true` | | `hmac_sign` / `hmac_verify` | Promoted from internal `_fk_*` to public stdlib — signed tokens and webhook verification | | `base64_encode` / `base64_decode` | Standard Base64 encode/decode — useful for HTTP Basic Auth headers | | `String#format` | Named placeholder substitution: `"Hello, {name}!".format({name: "Alice"})` | | `.chars` / `.bytes` | Unicode-aware character vector and byte values from a string | | Path helpers | `path_join`, `path_dirname`, `path_basename`, `path_extname`, `path_stem`, `path_absolute` | | Date arithmetic | Date objects support `+` / `-` (days) and comparison operators | | `zip_with` block | `a.zip_with(b) do \|x, y\| x + y end` — element-wise combination | | `assert_not_nil` / `assert_in` | New test assertions for nil checks and membership | | `req.query_int/float/bool` | Typed query parameter helpers with defaults | | `frankieauth` stitch | HTTP Basic Auth + Bearer token auth — zero dependencies | | `frankieratelimit` stitch | Per-IP sliding-window rate limiting — zero dependencies | | `frankiec check` | Parse without executing — useful in CI | | `frankiec new` | Scaffold a complete project layout | | `frankiec watch` | Official file watcher — re-run on save | --- ## v1.14 — `whats_new_v114.fk` **Theme:** Frankie for real web apps — concurrency, templates, signed cookies, middleware, static files, and two language upgrades that make working with data cleaner everywhere. | Feature | Summary | |---|---| | `spawn { }` | Run a block in a background thread — response goes out immediately, work continues behind the scenes | | `timeout(n) { }` | Kill a block that exceeds `n` seconds — raises `TimeoutError`, wrap in begin/rescue for graceful fallback | | `Async routes` | `app.get_async` / `app.post_async` etc. — non-blocking handlers, use `await` inside for slow I/O | | `Middleware stack` | `app.use do |req, next_fn|` — chain auth, logging, and rate-limiting; call `next_fn.(req)` to continue or return early to short-circuit | | `Static file serving` | `app.static("./public")` — serve a directory at `/`; `app.static("./assets", "/static")` for a URL prefix | | `frankietemplate` | Mustache-compatible template stitch — `{{ var }}, {{{ raw }}}, {{# section }}, {{^ inverted }}, {{> partial }}, {{! comment }}` | | `frankiecookie` | HMAC-signed cookies via Python's `hmac` stdlib — `set_signed_cookie` / `get_signed_cookie` returns `nil` if tampered | | `Hash destructuring` | `{name, age} = user` — pull symbol keys directly into variables; missing keys become `nil` | | `Shape pattern matching` | `case user when {role: "admin"}` — `when` now accepts hash literals, matches on subset of keysfrankiec new scaffold | | `Global stitch install` | `install.py` now correctly copies all stitches to `~/.frankie/stitches/` and lists each file installed | | `page_links` docs | Full web pagination example added — `paginate` + `page_slice` + `page_links` + `frankietemplate` working together | ## v1.13.1 — `whats_new_v1131.fk` **Theme:** Gap closers — no new syntax, everything real programs needed and didn't have. | Feature | Summary | |---|---| | `frankiestring` v2 | Rewritten stitch: `pad_left`, `pad_right`, `truncate`, `slugify`, `word_wrap`, `indent_lines` — replaces clunky `lfill`/`rfill` API | | `Vector .sum do \|x\|` | Block form now works — projected sum without a two-step `.map` + `sum` | | `Vector .flat_map do \|x\|` | Multi-line block bodies now parse correctly | | `assert_approx_eq(a, b, delta, msg)` | Float comparison in tests with configurable delta (default `0.001`) | | `run_tests()` | Now a public stdlib function — callable from any `.fk` file, not just `frankiec test` | | `session(req, resp)` | Cookie-backed session hash — read, mutate, `.save()`. Zero server state, single JSON cookie `_fk_session` | | `frankiec fmt` blank lines | Intentional blank lines between statement groups inside function bodies now preserved | | `frankiec fmt` multi-line threshold | Hashes/vectors whose inline form exceeds 60 chars auto-expand to one element per line | | `frankiec fmt` idempotency | Running `fmt --write` twice now produces identical output — safe for pre-commit hooks and CI | | Heredoc in `do...end` blocks | Fixed lexer bug — heredocs now work anywhere a string expression is valid | | `Hash.each do \|k, v\|` | Two-parameter block iteration confirmed and end-to-end tested | | Symbol key round-trip in `fmt` | `{host: "x"}` no longer becomes `{"host": "x"}` after formatting | --- ## v1.13 — `whats_new_v113.fk` **Theme:** Stitches — a zero-dependency, zero-registry package system. | Feature | Summary | |---|---| | `stitch "name"` keyword | Load a package by name — resolves from `./stitches/` then `~/.frankie/stitches/` | | `frankieforms` | Form field validation — `required`, `min_length`, `max_length`, `email`, `numeric`, `alpha`, `matches_pattern` | | `frankietable` | ASCII table rendering from a vector of hashes — `table(rows)` / `table(rows, cols)` | | `frankiecolor` | ANSI color helpers — `red`, `green`, `yellow`, `bold`, `success`, `error`, `warn`, `info`, `colorize`, `strip_color` | | `frankiepager` | Pagination math — `paginate(opts)`, `page_slice(items, page, per_page)`, `page_links(pager, url_template)` | | `frankieconfig` | Layered config loading: defaults → JSON file → env vars → overrides, with type coercion | | `frankiestring` | String utilities stitch (v1, superseded by v2 in v1.13.1) | | `?` in function names | `def even?(n)` now works — `?` compiled transparently to `_q` in generated Python | --- --- ## v1.12 — `whats_new_v112.fk` **Theme:** Filling stdlib gaps, fixing error handling, tooling polish. | Feature | Summary | |---|---| | `String .gsub` with block | Transform each regex match via a block — `"hello".gsub("[aeiou]") do \|m\| m.upcase end` | | `Hash .map_hash` | Transform a hash into a new hash — block returns `[new_key, new_value]` | | `round(x, n)` | Round to n decimal places — `round(3.14159, 2)` → `3.14` | | `Vector .product(other)` | Cartesian product — `[1,2].product([3,4])` → `[[1,3],[1,4],[2,3],[2,4]]` | | `String .chars` | Promoted to first-class documented method — chains into iterators | | `each_with_object` + Hash | Hash accumulator now explicitly documented and tested | | `assert_match` / `assert_nil` | Two new test runner assertions | | `rescue FileNotFoundError` | `file_read` and `file_lines` now raise the correct type | | `frankiec watch` | Re-run on save — `frankiec watch main.fk` | | `frankiec repl --no-banner` | Headless REPL for scripts and pipes | | Friendlier runtime errors | Type errors now say "Integer and String", not Python internals | --- ## v1.11 — `whats_new_v111.fk` *(in docs/13_v111_features.md)* **Theme:** Ergonomics — removing paper cuts, making the common case obvious. | Feature | Summary | |---|---| | Implicit return | Last expression in a function is returned automatically | | Inline `if` expression | `grade = if score >= 90 then "A" else "B" end` | | `String .replace(old, new)` | The method new users always reach for first | | `String .format(hash)` | `"Hello, {name}!".format({name: "Alice"})` | | `.zip_with do \|a, b\|` | Pair-wise transform two vectors in one pass | | Multiple return values | `lo, hi = min_max(data)` — destructuring from functions | | `frankiec check` boxed errors | Parse errors now use the same box as runtime errors | | REPL multi-line history | `↑` recalls a full `def...end` block | | `frankiec fmt` heredoc support | Heredoc bodies preserved verbatim during formatting | | `String .delete(chars)` | `"hello".delete("l")` → `"heo"` — documented | --- ## v1.10 — `whats_new_v110.fk` **Theme:** Expressiveness — more ways to write less. | Feature | Summary | |---|---| | `String * n` / `Vector * n` | `"ha" * 3` → `"hahaha"` · `[0] * 5` → `[0,0,0,0,0]` | | Heredoc `<<~TEXT` | Multi-line strings with auto indent-stripping and interpolation | | `times()` standalone | `times(5) do \|i\|` alongside `5.times do` | | `flatten(depth)` | Flatten exactly n levels — `flatten(1)` vs deep `flatten` | | `map_with_index` | `v.map_with_index do \|x, i\|` | | `pp` — pretty print | `pp({host: "localhost", port: 3000})` | | `encode` / `decode` | `"hi".encode` → `[104, 105]` · `[104, 105].decode` → `"hi"` | | Exit codes | `exit(0)` / `exit(1)` — propagated to shell | | `--help` flag | `frankiec run --help` etc. | --- ## v1.9 — `whats_new_v19.fk` **Theme:** Safety and tooling. | Feature | Summary | |---|---| | Hash `.dig` | `config.dig("db", "host")` — safe nested access, returns nil | | `zip()` standalone | `zip([1,2,3], ["a","b","c"])` → `[[1,"a"],[2,"b"],[3,"c"]]` | | Record types | `record Point(x, y)` — named data objects built on Hash | | `frankiec fmt` | AST-based auto-formatter with `--write` and `--check` | | `frankiec docs` | Extract `##` doc-comments to Markdown | | REPL readline + history | Arrow keys, Ctrl+R, tab completion, persistent `~/.frankie_history` | | `.env` auto-loading | `.env` in the project root is loaded automatically at startup | --- ## v1.8 — `whats_new_v18.fk` **Theme:** Functional programming and collection power. | Feature | Summary | |---|---| | Lambdas | `->(x) { x * 2 }` — storable, passable first-class functions | | Hash merge `\|` | `h1 \| h2` — right wins on conflict, chains naturally | | `group_by` | Bucket elements into a hash of arrays by block result | | `each_slice(n)` | Iterate in non-overlapping chunks | | `each_cons(n)` | Iterate with a sliding window | --- ## v1.7 — `whats_new_v17.fk` **Theme:** Safety and real-world utility. | Feature | Summary | |---|---| | Nil safety `&.` | `name&.upcase` returns nil instead of crashing | | `template(str, hash)` | `{{key}}` placeholder substitution | | File system ops | `file_mkdir`, `dir_exists`, `dir_list`, `file_copy`, `file_rename` | | `assert_raises_typed` | Test that a specific error type is raised | --- ## v1.6 — `whats_new_v16.fk` **Theme:** Control flow completeness. | Feature | Summary | |---|---| | Compound assignment | `+=`, `-=`, `*=`, `/=`, `//=`, `**=`, `%=` | | Typed rescue | `rescue ZeroDivisionError e` — catch specific error types | | `.find` / `.detect` | First element matching a block condition | | `frankiec test` | Built-in test runner | --- ## v1.5 — `whats_new_v15.fk` **Theme:** Loop control, randomness, and collection utilities. | Feature | Summary | |---|---| | `next` | Skip to next iteration — like `continue` | | `break` | Exit a loop early | | `break value` | Exit with a result — `result = loop.break n * 10` | | Constants | `UPPER_CASE` — warn on reassignment | | `rand_int`, `rand_float` | Random number functions | | `shuffle`, `sample` | Random collection operations | | `sleep(n)` | Pause execution | | `sort_by` | Sort by computed key | | `min_by`, `max_by`, `sum_by` | Aggregate by key | | `unzip` | Split vector of pairs into two vectors | --- ## v1.4 — `whats_new_v14.fk` **Theme:** Built-in web server. | Feature | Summary | |---|---| | Web server | `web_app()` — Sinatra-style routing | | Route definitions | `.get`, `.post`, `.put`, `.delete`, `.patch` | | Path parameters | `/users/:id` → `req.params["id"]` | | Query parameters | `req.query["page"]` | | JSON body | `req.json` — auto-parsed | | Before/after filters | `app.before do`, `app.after do` | | Response helpers | `html_response`, `json_response`, `redirect`, `halt` | --- ## v1.3 — `whats_new_v13.fk` **Theme:** External data and project structure. | Feature | Summary | |---|---| | JSON | `json_read`, `json_write`, `json_parse`, `json_dump` | | CSV | `csv_read`, `csv_write`, `csv_parse`, `csv_dump` | | DateTime | `now()`, `today()`, `date_parse()`, `date_from()` | | HTTP client | `http_get`, `http_post`, `http_put`, `http_delete` | | `frankiec new` | Project scaffolding | --- ## v1.2 *(no whats_new file)* **Theme:** Database and multi-file programs. | Feature | Summary | |---|---| | SQLite built-in | `db_open`, `db.query`, `db.insert`, `db.exec`, transactions | | `require` | Load other `.fk` files — each loaded at most once | --- ## v1.1 — `whats_new_v11.fk` **Theme:** Collection power. | Feature | Summary | |---|---| | `select` / `reject` | Filter a vector by a condition | | `reduce` / `inject` | Fold a vector into a single value | | `any?` / `all?` / `none?` | Boolean tests across a collection | | `each_with_object` | Iterate with a shared accumulator | | `take`, `drop`, `chunk`, `tally`, `compact` | Collection utilities | | `flat_map`, `zip` | Flattening and pairing | | `case / when` | Pattern matching on values | | Destructuring assignment | `a, b, c = [1, 2, 3]` | | New string methods | `.chomp`, `.chop`, `.center`, `.ljust`, `.rjust`, `.squeeze`, `.tr` | | `count` with block | Count elements matching a condition | --- ## v1.0 *(initial release)* The foundation: variables, strings with `#{}` interpolation, integers, floats, booleans, nil, vectors, hashes, `if/elsif/else/unless`, `while/until/for`, functions with default params, `begin/rescue/ensure`, `raise`, regex (`matches`, `match_all`, `sub`, `gsub`, `=~`), file I/O (`file_read`, `file_write`), R-style statistics (`mean`, `stdev`, `median`, `sum`), vectorised arithmetic, the pipe operator `|>`, `seq`, `linspace`, the REPL, and `frankiec run/build/check`. --- # Changelog ## v1.22.4 (2026) — Patch ### Python-keyword names no longer crash - **Python-keyword names crashed in more places.** Using a name like `pass`, `class` or `global` as a `for` loop variable, a destructuring target (`a, b = ...` / `{x, y} = hash`), a lambda parameter or a `rescue` variable generated invalid Python. These now go through the same `_py_safe()` mangling as ordinary assignments. No new syntax, no stdlib/stitch signature changes — the language freeze for The Book of Frankie stays in effect. --- ## v1.22.3 (2026) — Patch ### `frankiec fmt` no longer eats your comments - **`frankiec fmt --write` stripped every comment from a file.** The formatter is AST-based and the lexer discarded comments, so they were lost on rewrite. Comments are now recorded on the side and re-attached to the statement they belong to (full-line comments above it, trailing comments after it). Formatting is idempotent. - **`frankiec fmt` could drop parentheses and change the meaning of an expression** (e.g. `(a + b) * c`, or range bounds like `(n - 1)..m`). It now uses a precedence table and keeps the parentheses that matter. - **Stitch doc comments restored** in `frankiegame` and `frankiecanvas` (`##` comments consumed by `frankiec docs`). ### New: the Frankie Playground 🌐 Try Frankie in the browser with nothing to install. See [The Playground](../getting_started/playground.md). No new syntax, no stdlib/stitch signature changes — the language freeze for The Book of Frankie stays in effect. --- ## v1.22.2 (2026) — Patch ### Bug fixes found while writing The Book of Frankie - **`app.static("./dir")` (1-arg, root-mounted form) was shadowing every dynamic route with a 404.** When a request didn't match a static file, the dispatcher returned 404 immediately instead of falling through to check regular routes. Fixed: the 2-arg, explicit-prefix form (`app.static("/static", "./dir")`) still 404s outright since it owns that URL space exclusively, but the root-mounted 1-arg form now falls through to routes when no static file matches. - **Assigning to a keyword-shaped identifier crashed at runtime.** `import = "value"` (and compound assignment to a keyword-shaped name, e.g. `class += 1`) generated invalid Python, since `gen_assign`/`gen_compound_assign` weren't running the identifier through the same `_py_safe()` mangling used everywhere else in codegen. Fixed — both now mangle consistently. - **Homebrew tap was tagged `v1.22` instead of `v1.22.0`**, inconsistent with every other release tag and the `FRANKIE_VERSION` constant. Retagged, and the formula/README now point at the correct tarball. No new syntax, no stdlib/stitch signature changes — the language freeze for The Book of Frankie stays in effect. --- ## v1.22.0 (2026) — "More FORTRAN" 🧮 ### One last feature pass before the freeze locks back in The freeze briefly lifted from v1.21.0 for a single, deliberate, final round leaning harder into Frankie's FORTRAN heritage — real matrix math, complex numbers, math intrinsics, and labeled loops. This is the last planned feature release before the book ships; only bug fixes and doc corrections from here. --- ### New Stdlib **Matrix math** - Arithmetic (`+`, `-`, `/`, `%`, `**`) on vectors now recurses through nested vectors at every depth, so a matrix (a vector of vectors) does genuine element-wise math instead of silently concatenating rows. `[[1,2],[3,4]] + [[5,6],[7,8]]` → `[[6,8],[10,12]]`. Plain (non-nested) vector arithmetic is unchanged. - `matrix_new(rows, cols, fill = 0)`, `matrix_identity(n)`, `matrix_shape(m)`, `matrix_transpose(m)`, `matrix_scale(m, n)` (element-wise scalar multiply — `*` stays as vector-repeat, unchanged), and `matrix_multiply(m1, m2)` (real row·column multiplication, raises on shape mismatch). **Complex numbers** - `complex_new(real, imag = 0)` builds a native Python `complex` — `+`, `-`, `*`, `/`, `**` all work for free with zero changes to arithmetic codegen. `complex_real`, `complex_imag`, `complex_conj`, `complex_abs` round out the accessors. - Printed in conventional math notation (`3+4i`), not Python's electrical-engineering `3+4j`. **Math intrinsics** - `sin`, `cos`, `tan`, `asin`, `acos`, `atan`, `atan2`, `exp`, `log` (natural or any base), `log10`, `log2`, `factorial`, `gcd`, `lcm`, and the constants `PI`/`E`. **Labeled loops** - `loop`, `while`, `until`, and `for` can carry a `:name` label right after the keyword. `break :name` / `next :name` target that exact loop from anywhere nested inside it — including through other unlabeled loops in between — solving the classic "break out of two loops at once" problem without extra flag variables. - `:name` reuses Frankie's existing symbol-literal syntax, but as of this release it's tokenized separately from plain strings (previously `:name` and `"name"` produced an identical token). This is what makes `break :label` unambiguous from `break "a string value"` — see Fixes below. --- ### Fixes - **`:symbol` and `"string"` were the same token.** `:name` has always been valid Frankie syntax (used as hash values, `enum`-style constants, etc.) but the lexer collapsed it straight into a plain string token, indistinguishable from `"name"`. This surfaced while building labeled loops — `break :label` and `break "some string"` were literally unparseable-apart. Fixed by giving `:name` its own `SYMBOL` token that still parses to the exact same value everywhere it was already used, so this is invisible unless you're doing something new like labeled loops. - **`frankie_fmt.py` silently dropped loop labels.** Before this was caught, running `frankiec fmt --write` on a file using labeled loops stripped every label from `loop`/`while`/`until`/`for`/`break`/`next`, which can silently turn a correctly-terminating labeled break into an infinite loop. Fixed — the formatter now round-trips labels losslessly (verified idempotent: format → run → identical output). - **`vector.md` and `math_statistics.md` had an inaccurate example.** Docs claimed `v * 2` on a vector scales every element (`[2,4,6,8,10]`); it actually repeats the vector Python-list-style (`[1,2,3,4,5,1,2,3,4,5]`). This was already true before v1.22 — just never caught until writing the new Matrix docs alongside it. Corrected, and `matrix_scale`/manual addition are now documented as the way to get true scalar scaling. --- ### 🧊 Language Freeze The freeze moved from v1.21.0 to v1.22.0 for this one release, per Blag's explicit decision — "the last big addition" before the book ships. v1.22.0 is now the frozen version: grammar, stdlib signatures, and stitch APIs are locked again, patch releases (bug fixes, doc corrections) continue as normal. --- ## v1.21.0 (2026) — "The Book Edition" 🧊 ### Image sprites, WebAudio synth, and a language freeze --- ### New Stdlib **Image sprites in `frankiecanvas`** - `load_image(path)` reads a PNG/JPEG/GIF file and returns `{src: "data:image/...;base64,..."}`. Call it once before `run_game`, not per frame — it hits disk. - `draw_image(g, x, y, image, w: 1, h: 1)` places the image at cell `(x, y)`, sized `w × h` cells. Every connected browser decodes and caches the image the first time it's drawn; later frames just resend coordinates. - `frankiegame` (terminal) gained matching `load_image`/`draw_image` calls for API parity — since a tty can't show real pixels, `draw_image` there renders a `▒` placeholder block instead. The same function calls compile against either engine. **WebAudio synth API** - `synth_play(g, freq: 440, wave: "sine", dur: 0.08, gain: 0.06)` plays a real oscillator tone in every connected browser. `wave` is `"sine"`, `"square"`, `"sawtooth"`, or `"triangle"`. - `game_beep(g)` is now a thin wrapper over `synth_play` (520Hz square, 0.07s) — fully backward compatible. - `frankiegame` (terminal) gained `synth_play` too, mapped to the terminal bell — parameters are accepted but ignored, so cross-engine code still compiles. **`file_read_base64(path)`** - Binary-safe file read + Base64 encode in one call. `file_read` is text-mode and corrupts binary data (images, audio, zip files); `load_image` uses `file_read_base64` internally. Generally useful for embedding any binary file as text. --- ### Fixes - **Data-loss bug in `frankiec fmt`** — a single-statement block whose body was an assignment or a postfix `if`/`unless` (e.g. `game["shots"].each do |s| hit = true if collide?(...) end`) silently formatted to `do |s| nil end`, discarding the logic. `_is_stmt_only()` didn't recognize `Assign`, `PostfixIf`, and several other statement node types. Fixed by falling back to the safe multi-line block form for any statement kind that can't be inlined. If you ran `frankiec fmt --write` on code with this pattern before v1.21, it's worth a diff review. --- ### 🧊 Language Freeze v1.21 is the last planned feature release for a while — Frankie is language-frozen while "The Book of Frankie" is written against this exact version. Grammar, stdlib signatures, and stitch APIs are locked; patch releases (bug fixes, doc corrections) continue as normal, but no new syntax or behavior changes until the freeze lifts. --- ### Compatibility notes Fully backward compatible. `game_beep` behaves identically to v1.20. No existing function signatures changed — `synth_play` and `draw_image` are additive on both stitches. --- ## v1.20.1 (2026) ### Patch: Arrow keys, `frankiec examples`, Homebrew --- - **Arrow keys work in terminal games.** `term_key()` was reading from Python's buffered stdin, which swallowed the tail of arrow-key escape sequences — every arrow decoded as `esc`. It now reads raw bytes from the file descriptor. Snake finally obeys. - **`frankiec examples [name]`** — list the bundled examples and showcase games, or copy one into the current directory ready to run (`frankiec examples snake && cd snake && frankiec run main.fk`). Works for brew, git-clone, and install.py installs alike. - **Homebrew support** — official formula in `packaging/homebrew/`: `brew tap atejada/frankie && brew trust atejada/frankie && brew install frankie`. Standard stitches now also resolve from the installation directory, so brew installs work out of the box. --- ## v1.20.0 (2026) ### Theme: "It's Alive… and Playing" — two game engines, one shared API --- ### New Language Features **The shared engine API** - `game_new(width:, height:, fps:)`, `on_key`, `on_any_key`, `on_tick`, `run_game`, `stop_game`, `clear`, `draw`, `draw_sprite`, `text`, `collide?` (AABB), `render_frame`, `game_beep` - Write a game once against this API — the `stitch` line picks the renderer - Also: `max_ticks:` to bound the loop for CI-safe, headless test runs **`frankiegame` — terminal renderer** - Raw keyboard mode (no Enter needed) via stdlib `termios`; arrows map to `"up"/"down"/"left"/"right"`; `q` quits by default - Double-buffered ANSI rendering — one write per frame, flicker-free - Headless-safe: without a tty, input and rendering no-op, so test suites can play the game via `max_ticks` + `render_frame` - New stdlib TUI primitives: `term_raw_on/off`, `term_key`, `term_size`, `term_hide_cursor`/`term_show_cursor`, `term_clear`, `term_render`, `clock_ms`, `beep` **`frankiecanvas` — browser renderer** - Same API, real pixels: an HTML5 canvas page served from Frankie's own web server, draw ops streamed over WebSockets (~20–30 fps) - Key and mouse events stream back with the same key names as the terminal; mouse clicks arrive as `"click:x,y"` - `rect(g, x, y, w, h, color)`, `on_player_key` (every browser tab is a player), `players_count(g)` — multiplayer costs zero extra code, built on the v1.18 WebSocket architecture **`frankiec new --game`** - Scaffolds a playable starter (a zombie you steer with the arrows) with `frankiegame` pre-installed and lockfile-pinned **Showcase games** *(`examples/projects/`)* - 🐍 `snake/` (terminal) — the whole engine API in ~80 lines - 🧟 `zombie_invaders/` (browser) — rects, sprites, waves, beeps - 🏓 `pong/` (browser) — multiplayer via `on_player_key`, two tabs, one ball --- ### Fixes - Blocks whose single statement is an assignment (`do |g| g["x"] = 1 end`) or a postfix conditional now compile correctly (previously a codegen error) --- ## v1.19.0 (2026) ### Theme: "Under the microscope" — types, a real debugger, coverage --- ### New Language Features **Gradual type annotations** - `def area(r: Float) -> Float` — optional everywhere; un-annotated code is untouched, and annotations cost nothing at runtime - Checked statically by `frankiec check`, in CI, and live in the editor via the LSP - Type names: `Int`/`Integer`, `Float`/`Number`, `String`/`Str`, `Bool`/`Boolean`, `Vector`, `Hash`, `Lambda`, `Range`, `Nil`, `Any` - Return annotations are checked against every `return` and the implicit final expression; simple local inference follows literals, arithmetic, and calls to annotated functions - Coexists with keyword defaults: `def connect(host: String, port: 5432)` — a bare reserved type name is an annotation, anything else is still a keyword default --- ### Tooling **Full stepping debugger** - `breakpoint` grew up: `(fkdb)` now understands `s` (step into calls), `n` (next, step over), `stack` (call stack, innermost first), `vars` (clean locals, no stdlib noise), any expression, and `c` (continue) - `frankiec run --debug app.fk` breaks at the very first line — step through a program you've never read - Line-accurate everywhere via the compiler's line maps, including inside `require`d files **Test coverage — `frankiec test --coverage`** - Percentages and missing-line ranges mapped back to `.fk` source - Writes `.frankie_coverage.json` — the LSP reads it and shows uncovered lines as hints in the editor **`frankiec docs --html`** - Renders `##` doc-comments (with `@param`/`@return`/`@example`) into a styled single-page HTML matching the website's theme: `frankiec docs --html mystitch.fk --output mystitch.html` **Stitch installs from any URL** - `frankiec stitch install https://example.com/stitches/foo.fk` — pinned in `stitch.lock` with the URL recorded as its source; `verify` and `update` work exactly as with registry stitches --- ### New Stdlib **TLS clients + UDP sockets** - `ws_connect("wss://...")` — TLS WebSockets - `tcp_connect(host, port, tls: true)` — TLS TCP, certificate-verified via stdlib `ssl` - `udp_listen(port)` → socket with `.recv()` (returns `{data:, host:, port:}`) and `.send_to(host, port, msg)` - `udp_send(host, port, msg)` — fire-and-forget - Server-side TLS stays on the wish list --- ### Showcase Projects Three complete programs in `examples/projects/`, each a single `.fk` file, each shippable as one `.py` via `frankiec bundle`: - 🧟 `zombie_chat/` — multi-room WebSocket chat, server + web UI in one file - ⚡ `word_reanimator/` — multiplayer browser hangman, shared state over WebSockets - 💰 `frankie_ledger/` — terminal expense tracker: SQLite, stitches + `stitch.lock`, R-style stats --- ### Fixes - The formatter now round-trips `return x if cond` and similar postfix statements correctly (previously could collapse to `nil`) --- ## v1.18.0 (2026) ### Theme: "From projects to products" — edit, ship, connect, debug --- ### Tooling **Language Server — `frankiec lsp`** - LSP over stdio, pure Python stdlib — live diagnostics (via the v1.17 analyzer + lex/parse errors), completion (stdlib, user symbols, keywords) and hover docs (`##` doc-comments included) - VS Code extension upgraded from grammar-only to a full client; Neovim, Helix and Zed setups documented **`frankiec bundle [-o out.py]`** - Compiles a program plus every statically referenced `require`/`import`/`stitch` into ONE self-contained `.py` with the stdlib inlined - Runs anywhere with `python3 out.py` — no Frankie installation needed - Dynamic paths (computed at runtime) can't be bundled and produce a warning **Stitch lockfile** - `frankiec stitch install` writes `stitch.lock` (sha256, source, size, date) - `frankiec stitch verify` — ✓ pinned / ⚠ modified / ✗ missing, exit 1 on problems (CI-ready) - `frankiec stitch update [name]` re-fetches + re-pins **Project-wide `check` and `fmt`** - Both commands accept directories and recurse into `.fk` files: `frankiec check .`, `frankiec fmt --write .` --- ### New Language Features **WebSockets — `app.websocket` + `ws_connect`** - `app.websocket("/ws/:room") do |ws| ... end` on the built-in server — hand-rolled RFC 6455 (handshake, framing, ping/pong, close), one thread per connection, auto-close on handler return - `ws_connect("ws://host:port/path")` client; `ws.send` / `ws.recv` / `ws.close` / `ws.params` / `ws.path` / `ws.peer` **`breakpoint` — debugger-lite** - Pauses into a scoped REPL: `vars`, `where`, `exit`, `c`, or any Frankie expression evaluated against the paused scope - Skipped with a notice when stdin isn't a terminal — CI never hangs - Postfix conditions work: `breakpoint if qty > 100` **`enum Status(pending, active, done)`** - Members are their own names as strings: `Status.pending` → `"pending"` - `Status.values`, `Status.include?(x)`, iteration and `case/when` matching - Contextual keyword — `enum` stays valid as a variable name **`benchmark ["label"] do ... end`** - Times a block, prints `⏱ label: 12.3ms`, returns the elapsed ms - Works as an expression: `ms = benchmark "x" do ... end` **Numeric literals** - Underscore separators: `1_000_000`, `3.141_592` - Scientific notation: `1e6`, `2.5e-3`, `1E+9` **Set operations on vectors** - `.union(v)` / `.intersect(v)` / `.difference(v)` — order-preserving, deduplicating --- ### Fixes - Formatter: parenthesizes indexed expressions correctly — `(a | b)["x"]` no longer loses its parens on reformat - Formatter emits floats the lexer can always re-read (`1e-06` now lexes thanks to scientific-notation support) - `loop`/`spawn`/`record`/`import` etc. are now valid as the last statement of a web route handler (previously: codegen crash) --- ## v1.17.0 (2026) ### Theme: "Programs that grow" — namespacing, real checking, typed errors --- ### New Language Features **Namespaced imports — `import "lib/math" as math`** - Loads a `.fk` file into its own namespace: `math.circle_area(5)`, `math.PI` - Alias optional — `import "lib/math"` defines `math` - Modules are cached; `require` is unchanged and still merges into scope **User-defined error types — `error TypeName`** - `error TimeoutError` declares a type; `raise TimeoutError, "msg"` raises it - New Ruby-style rescue binding: `rescue TimeoutError => e` (old `rescue Type e` still works) - Typed raises auto-declare their type; generic `rescue` still catches everything - `assert_raises_typed` understands user-defined types - User types take precedence over Python builtins of the same name **First-class ranges** - Ranges print in Frankie syntax: `1..10` (not `range(1, 11)`) - `.to_vec` / `.to_a`, `.include?`, `.step(n)`, `.sum`, `.first`, `.last` - `case/when` with a range value now tests membership: `when 90..100` **Record dot access — `p.x`** - `record Point(x, y)` instances now support `p1.x` (previously `p1["x"]` only) - Same dispatch powers module constants and zero-arg methods uniformly **`test` blocks — `test "name", tags: ["slow"] do ... end`** - Named, filterable test groups for the built-in harness (contextual keyword) --- ### New Stdlib **`parallel_map(vec, workers: 4) do |x| ... end`** - Thread-pool map via `concurrent.futures` — results in input order, first worker exception re-raised. Built for I/O-bound work. **TCP sockets — `tcp_connect` / `tcp_listen` / `tcp_serve`** - `tcp_connect(host, port, timeout: 5)` → socket with `send`, `send_line`, `recv(n)`, `recv_line`, `peer`, `close` - `tcp_listen(port)` → server with `accept` / `close` - `tcp_serve(port) do |client| ... end` — threaded accept loop, auto-close **`stub(name, fn)` / `unstub(name)`** - Swap any global function (`shell`, `http_get`, ...) during tests; restore with `unstub(name)` or `unstub()` --- ### Tooling **`frankiec check` — real static analysis** - Undefined variables/functions and wrong argument counts → errors (exit 1) - Unused local variables → warnings; `--strict` fails on warnings (CI mode) - Resolves `require`/`stitch`/`import` targets; checks `#{interpolation}` too **Accurate cross-file tracebacks** - CodeGen now emits a precise py→fk line map for every compiled file - Runtime errors in `require`d files, imports and stitches point at the right file and the right line (previously: wrong line, main file only) **`frankiec test --filter --tag `** - Run a subset of `test` groups; skipped groups reported in the summary **`frankiec stitch install [--global]` / `frankiec stitch list`** - Installs stitches from the Frankie GitHub registry into `./stitches/` or `~/.frankie/stitches/` — stdlib HTTP only, zero dependencies **REPL upgrades** - Bare expressions echo their value: `fk> 2 + 3` → `=> 5` - `_` holds the last result - `help ` prints the signature + docs of any function --- ### Fixes - `raise` as the last statement of a function, lambda or block no longer crashes codegen ("Unknown expression node: RaiseStmt") - Generated f-strings avoid nested quotes — compiled output now runs on Python 3.8–3.11, not just 3.12+ - `Integer#chr`, `String#hex`, `String#oct` wired into codegen - `TimeoutError` added to the rescue type map and builtin error registry - Generic zero-arg method calls dispatch through a uniform mechanism, with a clear error message for missing fields/methods - Function-call blocks now respect the block's exact parameter count, and keyword arguments order correctly around blocks: `parallel_map(urls, workers: 4) do |u| ... end` --- ## v1.16.2 (2026) ### Patch: Multi-Line Call & Definition Support --- **Multi-line function calls now parse correctly** Function calls with the closing `)` on its own line — or with arguments spread across multiple lines — previously caused a parse error (`Unexpected token in expression: NEWLINE`). The parser now skips newlines after every opening `(`, after every `,` between arguments, and before the closing `)` in all call sites (plain calls, method calls, safe-navigation calls). ```ruby # All of these now work: result = send_mail( to: "alice@example.com", subject: "Hello", body: "Hi!" ) config = deep_configure( host, port, opts ) ``` **Multi-line function definitions also supported** The same fix applies to `def` parameter lists — parameters can now span multiple lines: ```ruby def create_user( name, email, role: "viewer" ) # ... end ``` --- ## v1.16.1 (2026) ### Patch: Bug Fixes & Compatibility --- **Regex patterns must be strings, not `/literals/`** Frankie does not have a regex literal syntax. All patterns passed to `scan`, `gsub`, `match_all`, `matches`, etc. must be plain strings with double-escaped backslashes: `"\\d+"` not `/\d+/`. The lexer rejects `/` in expression position when followed by a pattern character — fixed all stdlib docs and examples to use the string form. **`||=` applies to simple variables only** The nil-coalescing assignment operator (`||=`) works on plain variable names only. Subscript expressions such as `hash["key"] ||= value` are not supported and will cause a parse error. Use an explicit nil check instead: ```ruby if cache["user:1"] == nil cache["user:1"] = {name: "Alice"} end ``` **Tuple/parallel assignment not supported** Multi-assignment syntax (`a, b = b, a + b`) causes a parse error. Use a temporary variable: ```ruby tmp = a + b a = b b = tmp ``` **`hmac_verify(token, secret)` takes exactly 2 arguments** The subject is embedded in the token by `hmac_sign` — you do not pass it separately to `hmac_verify`. Passing 3 arguments raises a runtime error. **`.inspect` is not a Frankie method** Ruby's `.inspect` does not exist in Frankie. Use string interpolation (`"#{value}"`) or `puts value` directly. **Stitch names use the `frankie` prefix throughout** All built-in stitches are named with the full `frankie` prefix: `frankieforms`, `frankietable`, `frankiecolor`, `frankiepager`, `frankieconfig`, `frankiestring`. The abbreviated `franki` prefix is incorrect. --- ### Theme: System Integration & Scripting Power --- ### New Language Features **`loop do...end` — Infinite Loops** A clean infinite loop construct that exits only via `break`. Clearer intent than `while true`. ```ruby i = 0 loop do i += 1 break if i >= 10 end puts i # 10 ``` **`||=` — Nil-Coalescing Assignment** Assign a value only if the variable is currently `nil` or `false`. Ruby-compatible semantics. ```ruby config ||= load_defaults() cache ||= {} # Common pattern — memoized computation result ||= expensive_query() ``` --- ### New Stdlib Functions **`shell(cmd)`** — run any OS command and get structured output: `{stdout, stderr, exit_code, ok}`. **`dotenv(path = ".env")`** — parse a `.env` file and load its variables into the process environment. Returns a hash of the loaded keys. **`Hash#transform_values do |v| ... end`** — new hash with same keys, transformed values. **`Hash#transform_keys do |k| ... end`** — new hash with transformed keys, same values. **`Hash#deep_merge(other)`** — recursively merge nested hashes (unlike `.merge` / `|` which are shallow). **`String#scan(pattern)`** — extract all regex matches from a string as a vector. --- ### New Stitches **`frankiemail`** — send email via SMTP with a simple keyword-argument API. Supports plain text, HTML, CC/BCC. Uses Python's `smtplib` — zero extra dependencies. **`frankiecli`** — structured CLI argument parsing built on `argv()`. Returns flags, named options, positional args, and a first-argument subcommand. Pure Frankie, zero dependencies. **`frankiecache`** — in-memory key/value cache with optional TTL. Ideal for caching database results, config, or rate-limit counters within a running script or server. Pure Frankie, zero dependencies. --- ## v1.15.0 (2026) ### Theme: Language Polish & Developer Ergonomics --- ### New Language Features **Ternary Operator** Right-associative ternary expressions, valid in any expression position — assignments, string interpolation, function arguments, and vector literals. ```ruby label = score >= 90 ? "A" : score >= 70 ? "B" : "C" msg = n == 1 ? "one item" : "#{n} items" ``` **Keyword-Style Default Parameters** Both `=` and `:` syntax are now accepted in `def` signatures. Mixed signatures work correctly. ```ruby def connect(host, port: 5432, ssl: true, timeout: 30) puts "#{host}:#{port} ssl=#{ssl}" end connect("localhost") # localhost:5432 ssl=true connect("prod", port: 3306, ssl: false) # prod:3306 ssl=false ``` **Splat in Multi-Assign — `*rest`** Capture remaining elements with a splat variable in destructuring assignments. ```ruby a, b, *rest = [1, 2, 3, 4, 5] # rest = [3, 4, 5] first, *mid, last = [1, 2, 3, 4, 5] # mid = [2, 3, 4] head, *tail = [10, 20] # tail = [] ``` **`const` Keyword** Explicit constant declaration. Reassignment prints a runtime warning and preserves the original value. The existing ALL_CAPS auto-detection continues to work — `const` is additive. ```ruby const PI = 3.14159 const MAX_RETRIES = 3 const BASE_URL = env("BASE_URL", "http://localhost:3000") ``` **Lambda Call Syntax — `fn.(args)` Everywhere** `fn.(args)` previously only worked inside web route middleware. Now valid in all contexts. ```ruby double = ->(x) { x * 2 } puts double.(5) # 10 transforms = [->(x) { x * 2 }, ->(x) { x + 10 }] result = 5 transforms.each do |f| result = f.(result) end puts result # 20 ``` --- ### Stdlib **`json_encode`** — preferred alias for `json_dump`. Accepts `pretty: true` for formatted output. **`hmac_sign(subject, secret)` / `hmac_verify(token, secret)`** — previously internal (`_fk_hmac_*`), now public. Useful for signed tokens, webhooks, and tamper-proof values. **`base64_encode(s)` / `base64_decode(s)`** — standard Base64 encode/decode, useful for HTTP Basic Auth headers. **`String#format`** — named placeholder substitution: `"Hello, {name}!".format({name: "Alice"})`. Raises a descriptive error for missing keys. **`.chars` / `.bytes`** — `.chars` returns a vector of individual characters (Unicode-aware); `.bytes` returns byte values. **Path Helpers** — `path_join`, `path_dirname`, `path_basename`, `path_extname`, `path_stem`, `path_absolute`. **Date Arithmetic** — date objects now support `+` / `-` with integers (days) and comparison operators (`<`, `==`, etc.). **`Vector#zip_with(other) do |x, y|`** — element-wise combination with a block. Without a block, returns pairs. **`assert_not_nil(val, msg)` / `assert_in(val, collection, msg)`** — new test assertions. **`FrankieRequest` Query Helpers** — `req.query_int(key, default)`, `req.query_float(key, default)`, `req.query_bool(key, default)` for typed query parameter access. --- ### New Stitches **`frankieauth`** — HTTP Basic Auth + Bearer token authentication. Zero dependencies — uses the built-in `hmac_sign` / `hmac_verify` and `base64_decode`. Functions: `basic_auth_ok?`, `auth_token_create`, `auth_token_verify`, `bearer_required`. **`frankieratelimit`** — In-memory per-IP sliding-window rate limiting middleware. Zero dependencies. `rate_limit_check(req, next_fn, max: 60, window: 60)` and `rate_limit_reset(ip, window: 60)`. --- ### Tooling **`frankiec check`** — parse without executing; exits 0 on success, 1 on error. Useful in CI (`frankiec check src/*.fk`). **`frankiec new `** — scaffold a complete project layout: `main.fk`, `test.fk`, `lib/`, `stitches/`, `views/`, `public/`, `data/`, `.env.example`, `.gitignore`, `README.md`. **`frankiec watch` (now official)** — re-run a file on save. `frankiec watch test.fk --test` re-runs tests on every save. --- ## v1.14.0 (2026) ### Theme: Frankie for Real Web Apps --- ### New Language Features **`spawn { }` — Background Blocks** - Run any block in a background thread — returns immediately, response goes out while work continues - Works in web routes and standalone scripts - Spawned blocks receive a copy of variables at spawn time; mutations do not affect outer scope - Backed by Python's `threading.Thread` — zero dependencies **`timeout(n) { }` — Time-Bounded Execution** - Kill any block that exceeds `n` seconds — raises `TimeoutError` - Works inside `begin/rescue TimeoutError` for graceful fallback - Essential for external HTTP calls, slow database queries, and any operation that can hang - Backed by Python's `threading` with a sentinel thread — zero dependencies **Hash Destructuring — `{name, age} = user`** - Pull hash keys directly into local variables in one assignment - Missing keys evaluate to `nil` — no error - Works anywhere an assignment is valid: top level, inside functions, inside route handlers, inside loops - Bareword (symbol) keys only — matches the existing hash literal convention **Shape Pattern Matching — `case user when {role: "admin"}`** - `when` clauses now accept hash literals — matches any hash containing at least those key/value pairs - Extra keys in the subject hash are ignored (subset match) - Works with records — `record Point(x, y)` is a hash, so `when {x: 0}` is valid - Mix shape and value `when` clauses in the same `case` --- ### New Web Features **Async Routes — `app.get_async` / `app.post_async` etc.** - Non-blocking route handlers — slow I/O in one handler does not hold up others - All five HTTP methods have async variants: `get_async`, `post_async`, `put_async`, `delete_async`, `patch_async` - Use `await` inside async blocks for non-blocking calls **Middleware Stack — `app.use do |req, next_fn|`** - Chain middleware that wraps every request — auth, logging, rate-limiting, CORS - Each layer calls `next_fn.(req)` to pass control forward, or returns a response to short-circuit - Runs in registration order **Static File Serving — `app.static(dir)` / `app.static(dir, prefix)`** - Serve a directory of static files with one line - Serves HTML, CSS, JS, images, fonts, JSON automatically - Optional URL prefix: `app.static("./assets", "/static")` - Directory listing disabled by default --- ### New Stitches **`frankietemplate`** - Mustache-compatible template engine — zero dependencies, pure `.fk` - `{{ variable }}` — HTML-escaped interpolation - `{{{ variable }}}` — raw / unescaped output - `{{# section }} ... {{/ section}}` — truthy blocks and vector iteration - `{{^ inverted }} ... {{/ inverted}}` — falsy / empty blocks - `{{> partial_name }}` — include from `./views/partials/.html` - `{{! comment }}` — stripped from output - `render(template, data)` — render a string - `render_file(path, data)` — load and render a file - `partial(name)` — load a partial by name **`frankiecookie`** - HMAC-SHA256 signed cookies via Python's `hmac` + `hashlib` stdlib — zero dependencies - `set_signed_cookie(resp, name, value, secret, opts)` — write a tamper-proof cookie - `get_signed_cookie(req, name, secret)` — read and verify — returns `nil` if missing or tampered - `delete_cookie(resp, name)` — expire a cookie immediately - `cookie_set?(req, name)` — check if a cookie is present - Supports all cookie options: `path`, `max_age`, `same_site`, `http_only`, `secure` --- ### Tooling **`frankiec new` — Scaffold Updated for Stitches** - Generated project now includes a `stitches/` folder with a `README.md` explaining the stitch convention - Generated project includes a `views/partials/` folder for template projects - Generated `README.md` documents `stitch "name"` usage - Version string in `main.fk` banner updated to v1.14 **Global Stitch Install — `install.py`** - `install.py` now correctly copies all bundled stitches to `~/.frankie/stitches/` at install time - Installation output lists each stitch file copied - `frankiecookie` and `frankietemplate` included in the bundled set - `python3 install.py --uninstall` removes `~/.frankie/stitches/` and `~/.frankie/` if empty ## v1.13.1 (2026) ### Bug Fixes & Gap Closers **Parser / Compiler** - Heredoc inside `do...end` blocks — Fixed lexer bug that discarded tokens after `<<~DELIM` on the same line. Heredocs now work anywhere a string expression is valid, including inside route and iterator blocks. The only documented workaround in the language is removed. - Vector `.sum do |x| ... end` — Block form was swallowed by the internal method map before block detection. Now correctly routes to `_fk_sum_by` for projected sums. - Vector `.flat_map do |x| ... end` — Multi-line block bodies now parse correctly. - `Hash.each do |k, v|` — Two-parameter block iteration confirmed and end-to-end tested. No workaround needed. **Standard Library** - `assert_approx_eq(actual, expected, delta, msg)` — Float comparison assertion with configurable delta (default `0.001`). Replaces `assert_true(abs(a-b) < delta, ...)` boilerplate. - `run_tests()` — Now a public stdlib function callable from any `.fk` file, not just `frankiec test`. - `session(req, resp)` — Cookie-backed session helper. Read, mutate, and write back with `.save()`. Single JSON cookie (`_fk_session`), zero server-side state. - String `.ljust(n)` / `.rjust(n)` / `.center(n)` — Promoted to documented stdlib status with examples. - String `.start_with?(s)` / `.end_with?(s)` — Documented as first-class predicates. - Hash `.keys` / `.values` / `.has_key?(k)` — All three consistently documented; `.values` and `.has_key?` reference gaps closed. **Stitches** - `frankiestring` v2 — Rewritten with a clean API. Old `lfill/rfill` replaced by `pad_left(str, n, char), pad_right(str, n, char), truncate(str, n, suffix), slugify(str), word_wrap(str, width), indent_lines(str, n)`. **Tooling** - `frankiec fmt` — symbol key round-trip — Symbol keys (`host: "x"`) are preserved after formatting; `{host: "val"}` no longer becomes `{"host": "val"}`. - `frankiec fmt` — blank line preservation — Intentional blank lines between statement groups inside function bodies are now preserved. - `frankiec fmt` — multi-line threshold — Hashes and vectors whose inline form exceeds 60 characters auto-expand to one element per line. - `frankiec fmt` — idempotency — Running `fmt --write` twice now produces identical output. Safe for pre-commit hooks and CI. **REPL** - Multi-line REPL input — Fixed `_is_incomplete` edge cases: standalone `do |x|` lines now correctly hold the `...` prompt open; comment lines are skipped during depth counting. ## v1.13.0 (2026) ### New Features **Language — `stitch "name"` keyword** - New keyword for loading third-party Frankie packages by name - Resolution order: `./stitches/.fk` (project-local) → `~/.frankie/stitches/.fk` (user-global) - Friendly error when not found: tells you exactly where to put the file - Each stitch is loaded at most once — safe to call multiple times - Uses the same underlying `require` machinery — stitch files are plain `.fk` files - Establishes a clear convention: `lib/` = your code, `stitches/` = third-party packages **Language — `?` in user-defined function names** - `def even?(n)` and `def palindrome?(s)` now work correctly - `?` is compiled to `_q` in generated Python — transparent to the programmer - Applies to function definitions, calls, and assignments **Stitch — `frankieforms`** - Form field validation returning a Hash of `{field: error_message}` pairs - Rules: `required, min_length, max_length, email, min_value, max_value, numeric, alpha, matches_pattern` - `validate(form, rules)` → error hash · `valid?(form, rules)` → boolean **Stitch — `frankietable`** - ASCII table rendering from a vector of hashes - `table(rows)` — all columns · `table(rows, cols)` — specific columns in given order - Column widths auto-sized to content **Stitch — `frankiecolor`** - ANSI color and style helpers for terminal output - Color functions: `red, green, yellow, blue, cyan, magenta, white, black` - Style functions: `bold, dim, italic, underline, inverse` - Semantic helpers: `success, error, warn, info` - `colorize(str, color)` — generic · `strip_color(str)` — remove ANSI codes **Stitch — `frankiepager`** - Pagination math for web apps and CLI tools - `paginate(opts)` → full pager hash with `page, total_pages, from, to, has_prev, has_next, prev_page, next_page` - `page_slice(items, page, per_page)` — slice a vector to the current page - `page_links(pager, url_template)` — navigation link vector **Stitch — `frankieconfig`** - Layered configuration loading: defaults → JSON file → environment variables → overrides - Type coercion from env var strings to match default types (Integer, Float, Boolean) - `load_config(opts) · config_get(config, key, fallback)` ## v1.12.0 (2026) ### New Features **Standard Library — String `.gsub` with Block** - `"hello".gsub("[aeiou]") do |m| m.upcase end` → `"hEllO"` - Block form transforms each match; the block receives the matched substring and returns the replacement - The fixed-string form `gsub(pattern, replacement)` continues to work unchanged - Uses `re.sub` with a callable internally — no new dependencies **Standard Library — Hash `.map_hash do |k, v|`** - `{a: 1, b: 2}.map_hash do |k, v| [k, v * 2] end` → `{a: 2, b: 4}` - Transforms a hash into a new hash in one idiomatic step - Block must return a two-element vector `[new_key, new_value]`; any other return raises a clear runtime error - Fills the gap between `.map` (returns vector of pairs) and a true hash transform **Standard Library — `round(x, n)`** - `round(3.14159, 2)` → `3.14` - Rounds to n decimal places; n defaults to 0 - Available as a top-level function alongside `floor` and `ceil` - Wired to Python's built-in `round()` — no surprises on banker's rounding edge cases **Standard Library — `Vector .product(other)`** - `[1,2].product([3,4])` → `[[1,3],[1,4],[2,3],[2,4]]` - Cartesian product — every combination of elements from two vectors - Pure nested loop, zero dependencies - Natural companion to `.zip` and `.zip_with` — completes the combinatorics trio **Standard Library — `String .chars` (promoted)** - `.chars` was already in the method map but undocumented - Now a first-class documented method alongside `.bytes` and `.lines` - Chains naturally into iterators: `"hello".chars.select do |c| c != "l" end` **Standard Library — `Vector .each_with_object` with Hash Accumulator (documented)** - Hash accumulators already worked implicitly; now explicitly documented and tested - `[1,2,3].each_with_object({}) do |x, h| h[x] = x * x end` → `{1: 1, 2: 4, 3: 9}` **Tooling — `assert_match` and `assert_nil`** - `assert_match(value, pattern, msg)` — checks a regex match; pattern can be a regex or string - `assert_nil(value, msg)` — checks for nil; cleaner than `assert_eq(x, nil)` - Both available in `frankiec test` with the same output style as existing assertions **Tooling — `frankiec watch `** - Polls file mtime and re-runs automatically on every save - `frankiec watch test.fk --test` runs in test mode - Zero dependencies — uses `os.stat` and `time.sleep` - Ctrl-C to stop; gracefully ignores `exit()` calls in watched files **Tooling — `frankiec repl --no-banner`** - Skips the ASCII art and version header - Makes the REPL usable piped into other tools or embedded in scripts ### Bug Fixes & Improvements **Runtime — `FileNotFoundError` from File I/O** - `file_read` and `file_lines` previously raised `RuntimeError`, silently defeating `rescue FileNotFoundError` - Now raise a genuine `FileNotFoundError` with a clean message — no `[Frankie]` prefix noise - `file_copy` and `file_rename` also raise `FileNotFoundError` when the source is missing - `file_delete` and `file_exists` unchanged — returning `false` for missing files is correct for those - `rescue FileNotFoundError e` now works as expected for all file I/O **Runtime — Friendlier Error Messages** - `TypeError` now reads as `"Type mismatch — can't use '+' with Integer and String"` instead of the raw Python message - `IndexError` now reads as `"Index out of bounds — vector index does not exist"` instead of `"list index out of range"` - `FileNotFoundError` strips the raw Python `[Errno 2] No such file or directory:` prefix - The friendly dict in `frankiec.py` is now backed by three focused helper functions for easier future extension --- ## v1.11.0 (2026) ### New Features **Language — Implicit Return** - The last expression in a function body is now automatically returned — `return` is optional - Early `return` statements are still fully supported for mid-function exits - Applies to all function bodies including nested functions - Only expressions trigger implicit return; assignments, loops, and `puts` at the end still return `nil` - Zero breaking change risk: all existing programs using explicit `return` continue to work identically **Language — Inline `if` Expression** - `x = if cond then a else b end` — `if` is now usable as an expression, not just a statement - `then` keyword is optional; a newline after the condition also works - `elsif` clauses are supported: `if a then x elsif b then y else z end` - Missing `else` clause evaluates to `nil` - New `THEN` token type added to the lexer; new `IfExpr` AST node added - Avoids introducing a `?:` ternary operator that clashes with Frankie's readable style **Standard Library — String `.replace(old, new)`** - `"hello world".replace("world", "Frankie")` → `"hello Frankie"` - Replaces the first occurrence — an alias for `sub()` - The method name new users always reach for before remembering `sub`/`gsub` - `sub()`, `gsub()` continue to work as before **Standard Library — String `.format(hash)`** - `"Hello, {name}!".format({name: "Alice"})` — named `{key}` placeholder replacement - Method form of the existing `template()` function - Uses `{key}` syntax (vs `template()`'s `{{key}}` syntax) - Runtime dispatches on argument type: dict → string format; non-dict → datetime format **Standard Library — `.zip_with do |a, b|`** - `[1,2,3].zip_with([10,20,30]) do |a, b| a + b end` → `[11, 22, 33]` - Pair-wise transform two vectors in a single pass - Completes the R-style vector pipeline alongside `.zip`, `.map`, `.select` - Stops at the shorter vector, matching `.zip` behaviour **Tooling — `frankiec check` Boxed Error Output** - Parse and lex errors from `frankiec check` now use the same boxed format as runtime errors - Includes file path, line number, and source context with `──▶` pointer - Essential for editor integration — output is now machine-parseable and visually consistent - Exit codes unchanged: 0 = clean, 1 = error **Tooling — REPL Multi-line History Recall** - `↑` now recalls a complete `def...end` block as a single history entry - Previously, each line of a multi-line block was stored separately - Implementation: per-line readline entries are removed and replaced with a single joined entry - History file (`~/.frankie_history`) updated on block submission, not just on exit - Gracefully degrades on readline bindings that don't support `remove_history_item` **Tooling — `frankiec fmt` Heredoc Support** - Heredoc string bodies are now preserved verbatim during formatting - Multiline string literals are re-emitted as `<<~HEREDOC` blocks - Fixes a v1.10 regression where heredoc content could be mangled by the formatter ### Documentation - New `docs/13_v111_features.md` with full feature reference and examples - Multiple return values via destructuring documented as an official pattern - String `.delete(chars)` promoted from hidden stdlib to documented method --- ## v1.10.0 (2026) ### New Features **Language — String & Vector `*` Repetition** - `"ha" * 3` → `"hahaha"` — string repetition - `[0] * 5` → `[0, 0, 0, 0, 0]` — vector fill - `[1, 2] * 3` → `[1, 2, 1, 2, 1, 2]` — pattern repeat - Integer on either side works: `3 * "hi"` → `"hihihi"` - Implemented in `_fk_arith` — zero new syntax **Language — Heredoc `<<~TEXT`** - `<<~DELIM ... DELIM` multiline string with automatic indent-stripping - `< --help` prints a short description for that specific command - All commands covered: `run`, `repl`, `test`, `fmt`, `docs`, `build`, `check`, `new`, `version` ### Bug Fixes - `gen_string` multiline interpolation: single-line f-strings were emitted with literal embedded newlines (invalid Python syntax). Fixed by using `repr()` + string concatenation for all multiline interpolated strings. - `flatten` semantics changed to full-deep by default; use `.flatten(1)` for the old one-level behaviour. --- ## v1.9.0 (2026) ### New Features **Language — Record Types (`record`)** - `record Point(x, y)` defines a lightweight named data object - Constructor function generated automatically: `p = Point(3, 4)` - Prints as `Point(x: 3, y: 4)` — clean, readable output - Records are hashes under the hood — all hash methods, iterators, `dig`, `|`, and `.merge` work on them - New lexer token `RECORD`, new AST node `RecordDef`, new `gen_record_def` in codegen - `_fk_to_str` updated to detect `__type__` and display record notation ```ruby record Employee(name, dept, salary) emp = Employee("Alice", "Engineering", 95000) puts emp # Employee(name: Alice, dept: Engineering, salary: 95000) puts emp["dept"] # Engineering by_dept = employees.group_by do |e| e["dept"] end ``` **Standard Library — `hash.dig(key, ...)`** - Safe nested access: returns `nil` at the first missing key, never crashes - Works on hashes (string/symbol keys) and vectors (integer indices) - Chains correctly with `&.` for nil-safe navigation ```ruby config = {db: {host: "localhost", pool: {max: 10}}} puts config.dig("db", "pool", "max") # 10 puts config.dig("db", "missing") # nil (no crash) ``` **Standard Library — Standalone `zip(*vecs)`** - `zip(a, b)` function form alongside the existing `.zip` method - Accepts two or more vectors; stops at the shortest - Consistent with Frankie's R-inspired functional style ```ruby zip(["Alice", "Bob"], [95, 87]) # [["Alice", 95], ["Bob", 87]] ``` **Tooling — `frankiec fmt` (Auto-Formatter)** - New command: `frankiec fmt ` — print canonically formatted source - `--write` flag: reformat in-place - `--check` flag: exit 1 if not already formatted (CI-friendly) - Implemented in `frankie_fmt.py` — walks the AST, zero new dependencies - Canonical style: 2-space indent, single-expr blocks inlined, blank line after top-level `def` **Tooling — `frankiec docs` (Documentation Generator)** - New command: `frankiec docs ` — extract `##` doc-comments to Markdown - `--output ` flag: write to file instead of stdout - Supports `@param`, `@return`, `@example` tags - Works on directories: `frankiec docs lib/` generates docs for every `.fk` file - Implemented in `frankie_docs.py` — pure Python, zero new dependencies **REPL — readline, Tab Completion, History Persistence** - Arrow key navigation (`↑`/`↓`) and Ctrl+R reverse-search via Python's built-in `readline` - Tab completion for Frankie keywords, stdlib functions, and common method names - History saved to `~/.frankie_history` on exit; restored at next startup (max 1000 entries) - `.env` auto-loaded from the current working directory at REPL startup **Runtime — `.env` Auto-Loader** - `frankiec run` and `frankiec repl` automatically load `.env` from the current directory - Keys already set in the shell environment take precedence - Values accessible via the existing `env(key, default)` stdlib function - No crash if `.env` is absent ### Bug Fixes - `record` added as a reserved keyword — programs that used `record` as a variable name must rename it (the existing `.fk` examples in the repo have been updated) - `scaffold.py` version string updated from `v1.3` to `v1.9` --- ## v1.8.0 (2026) ### New Features **Language — Lambda / Anonymous Functions (`->`)** - Store functions as first-class values: `double = ->(x) { x * 2 }` - Call with `.call(args)`: `double.call(5)` → `10` - Single-expression bodies use brace syntax: `->(x) { x * 2 }` - Multi-statement bodies use `do...end`: `->(x) do ... end` - Default parameters are supported: `->(x, y = 1) { x + y }` - Lambdas can be stored in variables, vectors, and hashes - Lambdas can be passed to functions as arguments (higher-order functions) - Lambdas can be returned from functions - New token: `ARROW` (`->`) - New AST node: `LambdaLiteral` ```ruby double = ->(x) { x * 2 } add = ->(a, b) { a + b } puts double.call(7) # 14 puts add.call(3, 4) # 7 def apply(fn, val) return fn.call(val) end puts apply(double, 9) # 18 ``` **Language — Hash Merge Operator `|`** - `h1 | h2` merges two hashes; right-hand keys win on conflict - Returns a new hash — neither operand is modified - Chains naturally: `a | b | c` - Complements the existing `.merge(other)` method ```ruby defaults = {color: "blue", size: "medium"} overrides = {color: "red"} puts defaults | overrides # {color: red, size: medium} ``` **Standard Library — `group_by`** - `vector.group_by do |x| key end` buckets elements by block return value - Returns a hash whose values are arrays of matching elements, in original order - Pairs naturally with `.tally`, `.sort_by`, `.each`, and the new `|` operator ```ruby words = ["ant", "ape", "bear", "bee", "cat"] puts words.group_by do |w| w[0] end # {"a" => ["ant", "ape"], "b" => ["bear", "bee"], "c" => ["cat"]} ``` **Standard Library — `each_slice` and `each_cons`** - `vector.each_slice(n)` — iterate non-overlapping chunks of size `n` - `vector.each_cons(n)` — iterate all consecutive windows of size `n` (sliding window) - Both accept an optional `do |var| ... end` block; without a block, return a vector of slices/windows - Mirrors Ruby's API; natural fit for data-processing, batch operations, and rolling statistics ```ruby [1,2,3,4,5,6].each_slice(2) do |s| puts s # [1,2] [3,4] [5,6] end [10, 13, 11, 15].each_cons(2) do |w| puts w[1] - w[0] # 3 -2 4 end ``` ### Bug Fixes - **`_block_to_lambda`** — blocks whose body ends with a control-flow expression (`if`, `case`, `unless`) now correctly capture the result value instead of raising a `CodeGenError`. Affects `select`, `reject`, `sort_by`, `min_by`, `max_by`, `sum_by`, `find`, `flat_map`, and the new `group_by`. --- ## v1.7.1 (2025) ### Bug Fixes - **`N.times do`** — `def _gen_times` method definition was accidentally dropped from `compiler/codegen.py` during v1.7 development, causing an `AttributeError` at runtime. The method body was present but the `def` header was missing. - **`test_v17.fk`** — example test file used `def()` anonymous function syntax inside `assert_raises_typed` which does not exist in Frankie yet. Rewritten to use `begin/rescue` blocks instead. --- ## v1.7.0 (2025) ### New Features **Language — Nil Safety Operator `&.`** - `x&.method` — call `.method` on `x`, returning `nil` if `x` is nil (no crash) - `x&.method(args)` — nil-safe method call with arguments - `x&.property` — nil-safe property / zero-arg attribute access - Chains naturally: `a&.b&.c` — short-circuits at the first nil - Works with any value: strings, hashes, vectors, custom objects - No language keywords added — `&.` is a single new operator token ```ruby user = {name: "Alice"} missing = nil puts user["name"]&.upcase # ALICE puts missing&.upcase # nil (no crash) puts missing&.upcase&.reverse # nil (chain short-circuits) ``` **Standard Library — `template(str, hash)`** - Replace `{{key}}` placeholders in a string with values from a hash - Clean alternative to `sprintf` / `#{}` when keys are dynamic or templates are stored externally - Raises `KeyError` if a placeholder key is missing from the hash ```ruby msg = template("Hello, {{name}}! Age: {{age}}.", {name: "Alice", age: 30}) puts msg # Hello, Alice! Age: 30. ``` **Standard Library — File System Operations** - `file_rename(src, dst)` — rename or move a file - `file_copy(src, dst)` — copy a file (preserving metadata); returns `dst` - `file_mkdir(path)` — create a directory; creates intermediate dirs by default (like `mkdir -p`) - `file_mkdir(path, false)` — create a single directory only (no parents) - `dir_exists(path)` — return `true` if path is an existing directory - `dir_list(path)` — return a sorted vector of filenames in a directory (default: `"."`) - All use Python's built-in `os` / `shutil` — zero external dependencies ```ruby file_mkdir("/tmp/myapp/data") puts dir_exists("/tmp/myapp/data") # true file_write("/tmp/myapp/data/a.txt", "hello") file_copy("/tmp/myapp/data/a.txt", "/tmp/myapp/data/b.txt") file_rename("/tmp/myapp/data/b.txt", "/tmp/myapp/data/c.txt") puts dir_list("/tmp/myapp/data") # [a.txt, c.txt] ``` **Standard Library — `assert_raises_typed(fn, type, msg)`** - Extends the test runner to assert that a specific error *type* was raised - `type` can be a string (`"ZeroDivisionError"`) or a Python exception class - Fails with a clear message if no error is raised, or if the wrong type is raised - Supported type names mirror typed `rescue`: `RuntimeError`, `TypeError`, `ValueError`, `ZeroDivisionError`, `IndexError`, `KeyError`, `IOError`, `FileNotFoundError`, `OverflowError`, `NameError`, `AttributeError`, `Exception` / `Error` ```ruby assert_raises_typed(def() x = 1 // 0 end, "ZeroDivisionError", "division by zero raises correctly") assert_raises_typed(def() file_read("/no/such/file.txt") end, "RuntimeError", "missing file raises RuntimeError") ``` ### Bug Fixes - `&.` operator correctly short-circuits chains — once a nil is encountered, remaining method calls in the chain are skipped without raising errors --- ## v1.6.0 (2025) ### New Features **Language — Compound Assignment Operators** - `+=` — add and assign: `x += 5` - `-=` — subtract and assign: `x -= 3` - `*=` — multiply and assign: `x *= 2` - `/=` — divide and assign (float): `x /= 4` - `//=` — integer-divide and assign (Fortran): `x //= 3` - `**=` — exponentiate and assign (Fortran): `x **= 2` - `%=` — modulo and assign: `x %= 7` - All operators also work on vector elements: `v[i] += 1` **Language — Typed Rescue Clauses** - `rescue TypeError e` — catch only `TypeError` errors - `rescue ZeroDivisionError e` — catch only division by zero - Multiple `rescue` clauses on one `begin...end` block, checked in order - Full list of supported types: `RuntimeError`, `TypeError`, `ValueError`, `ZeroDivisionError`, `IndexError`, `KeyError`, `IOError`, `FileNotFoundError`, `OverflowError`, `NameError`, `AttributeError`, `StopIteration`, `Exception` / `Error` (catch-all aliases) - Untyped `rescue e` remains valid and catches everything **Standard Library — `.find` / `.detect`** - `.find do |x| ... end` — return the first element for which the block is true, or `nil` - `.detect do |x| ... end` — alias for `.find` - Works on any vector, including vectors of hashes - Chains naturally with `.select`, `.map`, `.sort_by`, etc. **Tooling — `frankiec test`** - `frankiec test` — run `test.fk` in the current directory - `frankiec test ` — run a named test file - Built-in assertions (no imports needed): - `assert_true(cond, msg)` — pass if condition is truthy - `assert_eq(actual, expected, msg)` — pass if values are equal - `assert_neq(actual, expected, msg)` — pass if values differ - `assert_raises(fn, msg)` — pass if calling `fn` raises any error - Live `✓` / `✗` output per assertion - Summary line with pass count, fail count, and elapsed time - Exits with code 1 if any assertion fails (CI-friendly) ### Bug Fixes - `_fk_test_suite` singleton now uses a fresh isolated copy per `frankiec test` run, preventing state leakage between multiple test invocations in the same process --- ## v1.5.0 (2025) ### New Features **Language — Loop Control** - `next` — skip to the next iteration (like `continue` in other languages); supports postfix `next if cond` - `break` — exit a loop early; supports postfix `break if cond` - `break value` — exit a loop and store a result in `_fk_break_val`; supports postfix form **Language — Constants** - `UPPER_CASE = value` — UPPER_SNAKE_CASE identifiers are treated as constants - Reassignment prints a warning and preserves the original value - Works with any type: integers, floats, strings, vectors, hashes **Standard Library — Randomness** - `random()` — random Float in [0.0, 1.0) - `rand(n)` — random Integer in [0, n) - `rand_int(a, b)` — random Integer in [a, b] (both inclusive) - `rand_float(a, b)` — random Float in [a, b) - `shuffle(vec)` — return a shuffled copy of a vector - `sample(vec, n)` — return n randomly chosen elements (no repeats) - `rand_seed(n)` — seed the RNG for reproducible results **Standard Library — Sorting** - `.sort_by do |x| key end` — sort a vector by any computed key - `.min_by do |x| key end` — element with the smallest key - `.max_by do |x| key end` — element with the largest key - `.sum_by do |x| val end` — sum the values the block returns **Standard Library — Other** - `sleep(n)` — pause execution for n seconds (float supported) - `unzip(vec)` — inverse of zip: vector of pairs → vector of columns - `format(fmt, ...)` — alias for `sprintf` ### Bug Fixes - Block parameters named `p` (e.g. `do |p|`) now parse correctly — `p` was always tokenised as the debug-print keyword, preventing it from being used as a loop variable - `p[...]` and `p.method` now correctly treated as variable access rather than a debug-print call - `break if cond` and `next if cond` (postfix forms) parse without errors --- ## v1.4.0 (2025) ### New Features **Web Server** (built-in `http.server` — zero deps) - `web_app()` — create a new Frankie web application - `app.get(path) do |req| end` — register a GET route - `app.post(path) do |req| end` — register a POST route - `app.put(path) do |req| end` — register a PUT route - `app.delete(path) do |req| end` — register a DELETE route - `app.patch(path) do |req| end` — register a PATCH route - `app.before do |req| end` — before-filter (runs before every matched route) - `app.after do |req, res| end` — after-filter (runs after every matched route) - `app.not_found do |req| end` — custom 404 handler - `app.run(port)` / `app.run(port, host)` — start the server (blocking, multi-threaded) - Path parameters with `:name` segments: `"/users/:id"` → `req.params["id"]` - Query string access: `req.query["page"]` - JSON body parsing: `req.json` — returns parsed hash/vector or nil - Form body parsing: `req.form` — returns decoded hash - `response(body, status, headers)` — plain-text response - `html_response(body, status)` — HTML response - `json_response(data, status)` — JSON response (auto-serializes hashes and vectors) - `redirect(location, status)` — redirect response (default 302) - `halt(status, body)` — error response shortcut - Returning a plain string from a handler auto-wraps as `200 text/plain` - Returning a hash or vector auto-wraps as `200 application/json` - Full request object: `.method`, `.path`, `.params`, `.query`, `.headers`, `.body`, `.json`, `.form` - See `docs/09_web.md` and `examples/webapp.fk` for full reference and demo ### Bug Fixes - `raise expr if cond` (postfix `if` on `raise`) now parsed correctly — was leaving the `if` clause unconsumed, causing `rescue` to be seen as an unexpected token in `begin/rescue` blocks - `data |> sum |> puts` — `puts` and `print` now accepted as bare pipe targets (previously raised an unexpected token error) --- ## v1.3.0 (2025) ### New Features **Language** - Default parameter values: `def greet(name, msg="Hello", punct="!")` - Keyword-named parameters (e.g. `times`, `each`) now usable as variable/param names - Triple-quoted multi-line strings: `"""..."""` and `'''...'''` with interpolation **JSON** (built-in `json` module — zero deps) - `json_parse(str)` — parse JSON string → Frankie value - `json_dump(obj, pretty)` — serialize to JSON string - `json_read(path)` — read and parse JSON file - `json_write(path, obj, pretty)` — serialize and write JSON file **CSV** (built-in `csv` module — zero deps) - `csv_parse(text, headers)` — parse CSV text → vector of hashes - `csv_dump(data, headers)` — serialize vector of hashes → CSV string - `csv_read(path, headers)` — read and parse CSV file - `csv_write(path, data, headers)` — write CSV file **DateTime** (built-in `datetime` module — zero deps) - `now()` — current date and time - `today()` — today's date at midnight - `date_from(year, month, day, hour, minute, second)` — construct a date - `date_parse(str, fmt)` — parse a date string (default fmt: `%Y-%m-%d`) - `.year`, `.month`, `.day`, `.hour`, `.minute`, `.second` — accessors - `.format(fmt)` — format with `strftime` directives - `.add_days(n)`, `.add_hours(n)`, `.add_minutes(n)` — arithmetic - `.diff_days(other)`, `.diff_seconds(other)` — differences - `.weekday()`, `.weekday_name()` — day of week - `.is_before(other)`, `.is_after(other)` — comparison - `.timestamp()` — Unix timestamp **HTTP** (built-in `urllib` — zero deps) - `http_get(url, headers)` — GET request - `http_post(url, data, headers)` — POST request (auto JSON-encodes dicts) - `http_put(url, data, headers)` — PUT request - `http_delete(url, headers)` — DELETE request - Response: `.status`, `.body`, `.headers`, `.json()`, `.ok()` - `url_encode(hash)` — encode params as query string - `url_decode(str)` — decode query string → hash **Tooling** - `frankiec new ` — scaffold a new project with `main.fk`, `test.fk`, `lib/`, `data/`, `README.md`, `.gitignore` - Better error messages — compile and runtime errors now show a boxed display with source context and line pointer (──▶) - Syntax highlighting for **VS Code** (`.tmLanguage.json` + `package.json` + `language-configuration.json`) - Syntax highlighting for **Vim/Neovim** (`frankie.vim`) - Syntax highlighting for **Sublime Text / TextMate** (`frankie.tmLanguage.json`) - All editor files in `editors/` ### Bug Fixes - Fixed `print` output disappearing when running from a different working directory - `times`, `each`, `map` keywords can now be used as parameter and variable names - Template placeholders in `frankiec new` use `.replace()` to avoid `str.format()` key conflicts --- ## v1.2.0 (2025) ### New Features **Database Access (SQLite)** - `db_open(path)` — open or create a SQLite database; `":memory:"` for in-memory - `db.exec(sql, params)` — run DDL/DML with `?` placeholders; returns row count - `db.query(sql, params)` — SELECT → vector of hashes keyed by column name - `db.query_one(sql, params)` — SELECT → first row as hash or nil - `db.insert(table, hash)` — insert a hash of column→value; returns new row id - `db.insert_many(table, rows)` — bulk insert a vector of hashes - `db.find_all(table)` — all rows as vector of hashes - `db.find(table, where)` — filtered rows (where is a hash, conditions ANDed) - `db.find_one(table, where)` — first matching row or nil - `db.update(table, data, where)` — update matching rows; returns count - `db.delete(table, where)` — delete matching rows; returns count - `db.count(table)` / `db.count(table, where)` — row counts - `db.last_id` — rowid of last INSERT - `db.tables` — list of table names in the database - `db.columns(table)` — column info as vector of hashes - `db.transaction do...end` — atomic block; rolls back on any error - `db.begin` / `db.commit` / `db.rollback` — explicit transaction control - `db.close` — close the connection - Zero external dependencies — uses Python's built-in `sqlite3` **Multi-line Strings** - Triple-quoted strings `"""..."""` and `'''...'''` spanning multiple lines - String interpolation `#{}` works inside triple-double-quoted strings - Perfect for embedding multi-line SQL, templates, or long text ### Bug Fixes - `isinstance(obj, FrankieDB)` cross-namespace failure — fixed with duck typing (`hasattr` checks instead) so DB objects work correctly inside `exec()` globals - `db.delete(table, where)` was intercepted by string/hash delete handler — now correctly dispatches based on argument count (2 args = DB call) - `.count("sub")` on a DB object was routing to `_fk_str_count` — fixed via `_fk_count_dispatch` with duck typing - Transaction `BEGIN`/`COMMIT`/`ROLLBACK` now uses explicit `isolation_level=None` with an `_in_tx` flag for correct per-operation autocommit and block rollback --- ## v1.1.0 (2025) ### New Features **Iterators & Collections** - `.select do |x|` — filter elements where block is true - `.reject do |x|` — filter elements where block is false - `.reduce(init) do |acc, x|` — fold to a single value (also `.inject`) - `.each_with_object(init) do |x, obj|` — iterate with shared accumulator - `.any? do |x|` — true if any element matches - `.all? do |x|` — true if all elements match - `.none? do |x|` — true if no elements match - `.count do |x|` — count matching elements (or `.count("sub")` for strings) - `.flat_map do |x|` — map then flatten one level - `.take(n)` — first n elements - `.drop(n)` — all but first n elements - `.tally` — count occurrences → Hash - `.compact` — remove nil values - `.chunk(n)` — split into sub-vectors of size n - `.zip(other)` — zip two vectors together **Control Flow** - `case/when/else/end` — pattern matching on values or conditions - Bare `case` (no subject) — uses truthy when-clauses **Destructuring Assignment** - `a, b, c = [1, 2, 3]` — unpack vector into named variables - Pads with `nil` if vector is shorter than target count **String Methods (new)** - `.chars` — vector of individual characters - `.bytes` — vector of byte values - `.lines` — vector of lines - `.chomp` — remove trailing newline - `.chop` — remove last character - `.count("sub")` — count substring occurrences - `.center(w, pad)` — center in field - `.ljust(w, pad)` — left-justify in field - `.rjust(w, pad)` — right-justify in field - `.squeeze` — collapse consecutive duplicates - `.tr(from, to)` — translate characters - `.each_char do |c|` — iterate over characters - `.each_line do |l|` — iterate over lines - `.lstrip` / `.rstrip` — directional whitespace trim **REPL (Interactive Mode)** - `frankiec repl` — starts the interactive REPL - `frankiec` with no arguments also launches the REPL - Multi-line block detection — automatically waits for `end` - `vars` — show all user-defined variables and functions - `clear` — reset the session - `load ` — load a file into the current session - `help` — show available commands - Persistent state across expressions in a session ### Bug Fixes - `do...while` body was accidentally consuming the `while` keyword - Postfix `if`/`unless` now works after `puts` (not just expressions) - `matches()` and all regex functions had flipped argument order — fixed to `(string, pattern)` - `s[-5..-1]` negative range ends now parse as `(-5)..(-1)` correctly - `[x, x * 2]` vector literal with multiplication was mis-parsed as destructuring — fixed with backtracking - `gen_pipe` method lost its `def` header during code insertion — restored - `count` method now correctly dispatches: `.count("sub")` for strings, `.count do` for filtering, `.count` for length ### Compiler Version - Version header in generated files updated to v1.1 --- ## v1.0.0 (2025) ### Initial Release **Core language** - 7 data types: Integer, Float, String, Boolean, Nil, Vector, Hash - Full arithmetic: `+`, `-`, `*`, `/`, `//`, `%`, `**` - String interpolation with `#{}` - Ranges: `1..10` (inclusive), `1...10` (exclusive) - Conditionals: `if/elsif/else/end`, `unless/end` - Postfix `if`/`unless` - Loops: `while`, `until`, `do...while`, `for...in` - Iterators: `.times`, `.each`, `.each_with_index`, `.map` - Functions with `def...end` and explicit `return` - Named arguments: `func(x, sep: "-")` - Pipe operator `|>` - Destructuring (v1.1) **Collections** - Vectors with R-style vectorized arithmetic - Hashes with symbol and integer keys, nil-safe access - Full method suites for both types **Standard Library** - Math: `sqrt`, `abs`, `floor`, `ceil`, `min`, `max` - Statistics: `sum`, `mean`, `median`, `stdev`, `variance` - Sequences: `seq`, `linspace`, `rep`, `clamp` - String formatting: `sprintf`, `paste` - Regex: `matches`, `match`, `match_all`, `sub`, `gsub`, `=~`, `regex()` - File I/O: `file_read`, `file_write`, `file_append`, `file_lines`, `file_exists`, `file_delete` - Type conversion: `to_int`, `to_float`, `to_str` - Type checking: `is_integer`, `is_float`, `is_string`, `is_vector`, `is_nil`, `is_bool` - System: `exit`, `argv`, `env` **Error handling** - `begin/rescue/ensure/end` - `raise` **Multi-file** - `require "filename"` — load another `.fk` file once **Tooling** - `frankiec run` — run a program - `frankiec build` — compile to Python source - `frankiec check` — syntax check - `frankiec version` - `python3 install.py` — install `frankiec` to `frankie/bin/` --- # Full Stdlib Index Every function, method, and operator available in Frankie v1.22.4. All are available without any import. --- ## Math & Arithmetic | Function | Description | |---|---| | `abs(x)` | Absolute value | | `sqrt(x)` | Square root — always returns Float | | `floor(x)` | Round down to nearest integer | | `ceil(x)` | Round up to nearest integer | | `round(x, n)` | Round to n decimal places (default 0) | | `clamp(x, lo, hi)` | Constrain x between lo and hi | | `min(a, b)` | Smaller of two values | | `min(vec)` | Smallest element of a vector | | `max(a, b)` | Larger of two values | | `max(vec)` | Largest element of a vector | | `sum(vec)` | Sum of all elements | | `mean(vec)` | Arithmetic mean | | `median(vec)` | Middle value (average of two middles for even length) | | `stdev(vec)` | Sample standard deviation (n-1) | | `variance(vec)` | Sample variance | | `+` `-` `*` `/` | Arithmetic operators — `/` always returns Float | | `//` | Integer (floor) division — Fortran heritage | | `%` | Modulo | | `**` | Exponentiation — Fortran heritage | | `sin(x)` `cos(x)` `tan(x)` | Trigonometric functions, radians (v1.22) | | `asin(x)` `acos(x)` `atan(x)` `atan2(y, x)` | Inverse trig (v1.22) | | `exp(x)` | e^x (v1.22) | | `log(x, base = nil)` | Logarithm — natural by default (v1.22) | | `log10(x)` `log2(x)` | Base-10 / base-2 logarithm (v1.22) | | `PI` `E` | Constants (v1.22) | | `factorial(n)` | n! — raises for negative input (v1.22) | | `gcd(a, b)` `lcm(a, b)` | Number theory (v1.22) | --- ## Matrix Math *(v1.22)* | Function | Description | |---|---| | `matrix_new(rows, cols, fill = 0)` | Build a filled matrix | | `matrix_identity(n)` | n×n identity matrix | | `matrix_shape(m)` | `[rows, cols]` | | `matrix_transpose(m)` | Swap rows and columns | | `matrix_scale(m, n)` | Multiply every element by `n` | | `matrix_multiply(m1, m2)` | Real row·column matrix multiplication — raises on shape mismatch | | `+` `-` `/` `%` `**` | Element-wise on nested vectors (matrices) at any depth | --- ## Complex Numbers *(v1.22)* | Function | Description | |---|---| | `complex_new(real, imag = 0)` | Build a complex number | | `complex_real(c)` | Real part | | `complex_imag(c)` | Imaginary part | | `complex_conj(c)` | Complex conjugate | | `complex_abs(c)` | Magnitude | | `+` `-` `*` `/` `**` | Native arithmetic — printed as `3+4i` | --- ## Sequences & Vectors | Function | Description | |---|---| | `seq(start, stop, step)` | Numeric sequence — `seq(1,5)` → `[1,2,3,4,5]` | | `linspace(start, stop, n)` | Exactly n evenly-spaced values | | `vec(range)` | Vector from range — `vec(1..10)` | | `rep(x, n)` | Repeat a value n times — `rep(0, 3)` → `[0,0,0]` | | `unzip(vec)` | Split vector of pairs → two vectors | | `zip(a, b)` | Pair two vectors → vector of pairs | --- ## String Functions | Function | Description | |---|---| | `sub(str, pat, rep)` | Replace first regex match | | `gsub(str, pat, rep)` | Replace all regex matches | | `match(str, pat)` | First match object or nil | | `match_all(str, pat)` | All matches as a vector of strings | | `matches(str, pat)` | True if pattern matches anywhere | | `regex(pat, flags)` | Compile a pattern with flags (`"i"`, `"m"`, `"s"`) | | `template(str, hash)` | `{{key}}` placeholder substitution | | `sprintf(fmt, ...)` | C-style format string | | `paste(..., sep:)` | Join values with separator | | `format(fmt, ...)` | Alias for sprintf | --- ## String Methods | Method | Description | |---|---| | `.upcase` | Uppercase | | `.downcase` | Lowercase | | `.length` | Character count | | `.reverse` | Reversed string | | `.strip` | Remove leading/trailing whitespace | | `.lstrip` | Remove leading whitespace | | `.rstrip` | Remove trailing whitespace | | `.chomp` | Remove trailing newline | | `.chop` | Remove last character | | `.chars` | Vector of characters | | `.bytes` | Vector of byte integers | | `.lines` | Vector of lines (newlines stripped) | | `.ord` | ASCII/Unicode code point of first character | | `.encode` | String → vector of byte integers | | `.decode` | Vector of byte integers → string | | `.split(sep)` | Split by separator → Vector | | `.join(sep)` | Join vector elements with separator | | `.include?(s)` | True if s is a substring | | `.start_with?(s)` | True if string starts with s | | `.end_with?(s)` | True if string ends with s | | `.count(sub)` | Count occurrences of sub | | `.empty?` | True if length is 0 | | `.nil?` | Always false for a string | | `.match(pat)` | First match object or nil | | `.match_all(pat)` | All matches as vector of strings | | `.matches?(pat)` | True if pattern matches anywhere | | `.replace(old, new)` | Replace first occurrence (alias for sub) | | `.sub(pat, rep)` | Replace first regex match | | `.gsub(pat, rep)` | Replace all regex matches | | `.gsub(pat) do \|m\|` | Replace all matches — block transforms each | | `.delete(chars)` | Remove all occurrences of any char in set | | `.squeeze` | Collapse consecutive duplicate chars | | `.tr(from, to)` | Translate characters position-by-position | | `.center(w, pad)` | Center in field of width w | | `.ljust(w, pad)` | Left-justify in field of width w | | `.rjust(w, pad)` | Right-justify in field of width w | | `.to_i` | Parse as integer | | `.to_f` | Parse as float | | `.to_s` | Return self | | `.format(hash)` | `{key}` placeholder substitution | | `.each_char do \|c\|` | Iterate over characters | | `.each_line do \|l\|` | Iterate over lines | | `[i]` | Character at index (negatives ok) | | `[a..b]` | Inclusive slice | | `[a...b]` | Exclusive slice | | `* n` | Repeat string n times | | `=~` | Position of first match or nil | | `.scan(pattern)` | All regex matches as vector (v1.16) | --- ## Vector Methods | Method | Description | |---|---| | `.length` / `.size` | Number of elements | | `.first` | First element or nil | | `.last` | Last element or nil | | `.empty?` | True if no elements | | `.include?(x)` | True if x is an element | | `.count` | Number of elements | | `.count do \|x\|` | Count elements satisfying block | | `.tally` | Count occurrences → Hash | | `.push(x)` | Append element, return vector | | `.pop()` | Remove and return last element | | `.delete(x)` | Remove first occurrence of x, return vector | | `.sort` | Sorted copy | | `.sort_by do \|x\|` | Sort by computed key | | `.reverse` | Reversed copy | | `.uniq` | Deduplicated copy (first occurrence wins) | | `.flatten` | Deep flatten all levels | | `.flatten(n)` | Flatten exactly n levels | | `.compact` | Remove all nil values | | `.take(n)` | First n elements | | `.drop(n)` | All but first n elements | | `.sum` | Sum of all elements | | `.min` | Minimum element | | `.max` | Maximum element | | `.mean` | Arithmetic mean | | `.map do \|x\|` | Transform each element → new vector | | `.map_with_index do \|x, i\|` | Map with element and index | | `.flat_map do \|x\|` | Map then flatten one level | | `.select do \|x\|` | Keep elements where block is true | | `.reject do \|x\|` | Keep elements where block is false | | `.find do \|x\|` | First element where block is true | | `.detect do \|x\|` | Alias for find | | `.reduce(init) do \|acc, x\|` | Fold into a single value | | `.inject(init) do \|acc, x\|` | Alias for reduce | | `.each do \|x\|` | Iterate for side effects | | `.each_with_index do \|x, i\|` | Iterate with index | | `.each_with_object(init) do \|x, obj\|` | Iterate with shared accumulator | | `.each_slice(n) do \|s\|` | Iterate in non-overlapping chunks | | `.each_cons(n) do \|w\|` | Iterate with sliding window | | `.any? do \|x\|` | True if any element satisfies block | | `.all? do \|x\|` | True if all elements satisfy block | | `.none? do \|x\|` | True if no elements satisfy block | | `.min_by do \|x\|` | Element with smallest key value | | `.max_by do \|x\|` | Element with largest key value | | `.sum_by do \|x\|` | Sum of block results | | `.sort_by do \|x\|` | Sort by computed key | | `.group_by do \|x\|` | Bucket into hash of arrays | | `.chunk(n)` | Split into sub-vectors of size n | | `.zip(other)` | Pair elements with another vector | | `.zip_with(other) do \|a, b\|` | Zip and transform each pair | | `.product(other)` | Cartesian product | | `.join(sep)` | Join elements as string with separator | | `.encode` | Vector of byte ints → string | | `.decode` | Vector of byte ints → string (explicit) | | `.dig(i1, i2, ...)` | Safe nested access — returns nil | | `[i]` | Element at index (negatives ok) | | `[a..b]` | Inclusive slice | | `[i] =` | Index assignment | | `* n` | Repeat vector n times | --- ## Hash Methods | Method | Description | |---|---| | `h[key]` | Get value — nil if missing | | `h[key] =` | Set value | | `.keys` | Vector of all keys | | `.values` | Vector of all values | | `.size` / `.count` | Number of pairs | | `.has_key?(k)` | True if key exists | | `.empty?` | True if no pairs | | `.fetch(key, default)` | Get with explicit default | | `.dig(k1, k2, ...)` | Safe nested access — nil at any missing level | | `.delete(key)` | Remove key, return modified hash | | `.merge(other)` | New merged hash — right wins on conflict | | `.merge_bang(other)` | Merge in place | | `h1 \| h2` | Merge operator — right wins on conflict | | `.store(key, val)` | Method form of `h[key]=` | | `.to_a` | Convert to vector of `[key, value]` pairs | | `.each do \|k, v\|` | Iterate pairs | | `.each_pair do \|k, v\|` | Alias for each | | `.each_with_object(init) do \|pair, obj\|` | Iterate with accumulator | | `.map do \|k, v\|` | Transform pairs → vector | | `.map_hash do \|k, v\|` | Transform pairs → new hash | | `.select do \|k, v\|` | Keep pairs where block is true → new hash | | `.reject do \|k, v\|` | Keep pairs where block is false → new hash | | `.find do \|k, v\|` | First pair where block is true | | `.any? do \|k, v\|` | True if any pair satisfies block | | `.all? do \|k, v\|` | True if all pairs satisfy block | | `.none? do \|k, v\|` | True if no pair satisfies block | | `.count do \|k, v\|` | Count pairs satisfying block | | `.sort_by do \|k, v\|` | Sort pairs by key → vector | | `.min_by do \|k, v\|` | Pair with smallest key value | | `.max_by do \|k, v\|` | Pair with largest key value | | `.group_by do \|k, v\|` | Bucket pairs by block result | | `.transform_values do \|v\|` | New hash — same keys, block-transformed values (v1.16) | | `.transform_keys do \|k\|` | New hash — block-transformed keys, same values (v1.16) | | `.deep_merge(other)` | Recursively merge nested hashes (v1.16) | --- ## Integer Methods | Method | Description | |---|---| | `.to_f` | Convert to Float | | `.to_s` | Convert to String | | `.to_i` | Return self | | `.times do \|i\|` | Repeat block n times, i from 0 to n-1 | --- ## Float Methods | Method | Description | |---|---| | `.to_i` | Truncate to Integer (toward zero) | | `.to_s` | Convert to String | | `.to_f` | Return self | --- ## File I/O | Function | Description | |---|---| | `file_read(path)` | Read entire file as string — raises `FileNotFoundError` | | `file_read_base64(path)` | Read binary file, Base64-encoded — raises `FileNotFoundError` (v1.21) | | `file_lines(path)` | Read file as vector of lines — raises `FileNotFoundError` | | `file_write(path, str)` | Write string to file (overwrites) | | `file_append(path, str)` | Append string to file | | `file_exists(path)` | True if file exists | | `file_delete(path)` | Delete file — returns false if missing | | `file_copy(src, dst)` | Copy file — raises `FileNotFoundError` if src missing | | `file_rename(src, dst)` | Rename/move file — raises `FileNotFoundError` if src missing | | `file_open(path, mode)` | Open file handle (`"r"`, `"w"`, `"a"`) | | `file_mkdir(path)` | Create directory and all parents | | `dir_exists(path)` | True if directory exists | | `dir_list(path)` | Sorted vector of filenames in directory | | `path_join(*parts)` | Join path segments with OS separator (v1.15) | | `path_dirname(path)` | Parent directory of a path (v1.15) | | `path_basename(path)` | Filename component of a path (v1.15) | | `path_extname(path)` | File extension including the dot (v1.15) | | `path_stem(path)` | Filename without the extension (v1.15) | | `path_absolute(path)` | Resolve to absolute path (v1.15) | ### File Handle Methods | Method | Description | |---|---| | `.read` | Read full contents as string | | `.write(str)` | Write string | | `.close` | Close the handle | --- ## JSON & CSV | Function | Description | |---|---| | `json_read(path)` | Read and parse JSON file | | `json_write(path, data)` | Write data as JSON file | | `json_write(path, data, true)` | Write pretty-printed JSON | | `json_parse(str)` | Parse JSON string → value | | `json_encode(data)` | Serialise value → JSON string — preferred name (v1.15) | | `json_encode(data, pretty: true)` | Pretty-printed JSON string | | `json_dump(data)` | Alias for `json_encode` — kept for compatibility | | `json_dump(data, true)` | Pretty-printed JSON string | | `csv_read(path)` | Read CSV → vector of hashes | | `csv_read(path, false)` | Read CSV → vector of vectors | | `csv_write(path, data)` | Write vector of hashes to CSV | | `csv_write(path, data, headers)` | Write with explicit column order | | `csv_parse(str)` | Parse CSV string → vector of hashes | | `csv_dump(data)` | Serialise → CSV string | --- ## DateTime | Function / Method | Description | |---|---| | `now()` | Current date and time | | `today()` | Today at midnight | | `date_parse(str, fmt)` | Parse string — default fmt `"%Y-%m-%d"` | | `date_from(y, m, d, h, min, s)` | Build from components | | `.year` `.month` `.day` | Date components | | `.hour` `.minute` `.second` | Time components | | `.format(fmt)` | Format with strftime codes | | `.add_days(n)` | Add n days (negative subtracts) | | `.add_hours(n)` | Add n hours | | `.add_minutes(n)` | Add n minutes | | `.diff_days(other)` | Days between two dates | | `.diff_seconds(other)` | Seconds between two datetimes | | `.weekday` | 0=Monday … 6=Sunday | | `.is_before(other)` | True if earlier | | `.is_after(other)` | True if later | | `.timestamp` | Unix timestamp as Float | | `date + n` | Add n days — returns new date (v1.15) | | `date - n` | Subtract n days — returns new date (v1.15) | | `date_a - date_b` | Difference in days as integer (v1.15) | | `<` `>` `<=` `>=` `==` | Date comparison operators (v1.15) | --- ## HTTP Client | Function | Description | |---|---| | `http_get(url)` | GET request | | `http_get(url, headers)` | GET with custom headers | | `http_post(url, data)` | POST — hash sends as JSON | | `http_post(url, data, headers)` | POST with custom headers | | `http_put(url, data)` | PUT request | | `http_put(url, data, headers)` | PUT with custom headers | | `http_delete(url)` | DELETE request | | `http_delete(url, headers)` | DELETE with custom headers | | `url_encode(hash)` | Hash → URL query string | | `url_decode(str)` | Query string → Hash | ### HTTPResponse Properties | Property / Method | Description | |---|---| | `.status` | HTTP status code | | `.body` | Raw response body string | | `.headers` | Response headers hash | | `.json()` | Parse body as JSON | | `.ok()` | True if 2xx status | --- ## Database (SQLite) | Function / Method | Description | |---|---| | `db_open(path)` | Open or create SQLite database | | `.exec(sql, params)` | Execute statement — returns row count | | `.query(sql, params)` | SELECT → vector of hashes | | `.query_one(sql, params)` | SELECT → first row as hash or nil | | `.insert(table, hash)` | Insert row from hash — returns last id | | `.insert_many(table, rows)` | Insert vector of hashes | | `.find(table, where)` | SELECT with where hash → vector of hashes | | `.find_one(table, where)` | SELECT first match → hash or nil | | `.update(table, data, where)` | UPDATE rows — returns count | | `.delete(table, where)` | DELETE rows — returns count | | `.count(table)` | COUNT rows in table | | `.tables` | Vector of table names | | `.columns(table)` | Vector of column names | | `.last_id` | Last inserted row id | | `.begin` | Begin transaction | | `.commit` | Commit transaction | | `.rollback` | Rollback transaction | | `.close` | Close connection | --- ## Web Server | Function / Method | Description | |---|---| | `web_app()` | Create a new web application | | `.get(path) do \|req\|` | Register GET route | | `.post(path) do \|req\|` | Register POST route | | `.put(path) do \|req\|` | Register PUT route | | `.delete(path) do \|req\|` | Register DELETE route | | `.patch(path) do \|req\|` | Register PATCH route | | `.before do \|req\|` | Before filter — runs before every route | | `.after do \|req\|` | After filter — runs after every route | | `.not_found do \|req\|` | Custom 404 handler | | `.run(port)` | Start server on port | | `response(body, status, headers)` | Build a response | | `json_response(data, status)` | JSON response | | `html_response(body, status)` | HTML response | | `redirect(location, status)` | Redirect response | | `halt(status, body)` | Abort with status | ### FrankieRequest Properties | Property | Description | |---|---| | `.path` | URL path | | `.method` | HTTP method string | | `.params` | Path parameters hash | | `.query` | Query string parameters hash | | `.form` | Form body parameters hash | | `.json` | Parsed JSON body | | `.body` | Raw request body string | | `.headers` | Request headers hash | | `.cookies` | Incoming cookies hash | | `.query_int(key, default)` | Query param as Integer (v1.15) | | `.query_float(key, default)` | Query param as Float (v1.15) | | `.query_bool(key, default)` | Query param as Boolean (v1.15) | --- ## Random | Function | Description | |---|---| | `rand_int(a, b)` | Random integer a..b inclusive | | `rand_float(a, b)` | Random float in [a, b) | | `rand()` | Random float in [0.0, 1.0) | | `rand(n)` | Random integer in [0, n) | | `rand_seed(n)` | Fix seed for reproducibility | | `shuffle(vec)` | Randomly reordered copy of vector | | `sample(vec, n)` | n randomly chosen elements (no repeats) | --- ## Testing | Function | Description | |---|---| | `assert_eq(actual, expected, msg)` | Pass if actual == expected | | `assert_neq(actual, expected, msg)` | Pass if actual != expected | | `assert_true(value, msg)` | Pass if value is truthy | | `assert_nil(value, msg)` | Pass if value is nil | | `assert_not_nil(value, msg)` | Pass if value is not nil (v1.15) | | `assert_in(value, collection, msg)` | Pass if collection includes value (v1.15) | | `assert_approx_eq(a, b, delta, msg)` | Pass if `\|a - b\| <= delta` — default 0.001 (v1.13.1) | | `assert_match(value, pattern, msg)` | Pass if pattern matches anywhere in value | | `assert_raises(fn, msg)` | Pass if fn raises any error | | `assert_raises_typed(fn, type, msg)` | Pass if fn raises that specific error type | | `run_tests()` | Run all assertions and print results | | `test "name", tags: ["slow"] do ... end` | Named, filterable test group (v1.17) | | `stub(name, fn)` | Replace a global function during tests (v1.17) | | `unstub(name)` / `unstub()` | Restore one / all stubbed functions (v1.17) | | `frankiec test --coverage` | Report line coverage; writes `.frankie_coverage.json` (v1.19) | --- ## Encoding & Signing *(v1.15)* | Function | Description | | --- | --- | | `base64_encode(str)` | Encode string to Base64 | | `base64_decode(str)` | Decode Base64 string | | `hmac_sign(subject, secret)` | Create a signed token using HMAC-SHA256 | | `hmac_verify(token, secret)` | Verify token — returns subject or `nil` | --- ## Type Checking & Conversion | Function | Description | |---|---| | `is_integer(x)` | True if x is an Integer | | `is_float(x)` | True if x is a Float | | `is_string(x)` | True if x is a String | | `is_vector(x)` | True if x is a Vector | | `is_nil(x)` | True if x is nil | | `is_bool(x)` | True if x is Boolean | | `to_int(x)` | Convert to Integer | | `to_float(x)` | Convert to Float | | `to_str(x)` | Convert to String | --- ## Input & Output | Function | Description | |---|---| | `puts(val)` | Print with newline | | `print(val)` | Print without newline | | `pp(val)` | Pretty-print with type annotation | | `input(prompt)` | Read line from stdin as string | | `input_int(prompt)` | Read line from stdin as integer | | `input_float(prompt)` | Read line from stdin as float | --- ## System | Function | Description | |---|---| | `exit(code)` | Exit with given code (default 0) | | `argv()` | Command-line arguments as vector | | `env(key, default)` | Read environment variable | | `sleep(seconds)` | Pause execution | | `times(n) do \|i\|` | Repeat block n times — standalone form | | `require(path)` | Load another .fk file (once only) | | `import "path" as name` | Load a .fk file into its own namespace (v1.17) | | `stitch(name)` | Load a stitch package from `./stitches/` or `~/.frankie/stitches/` | | `shell(cmd)` | Run OS command — returns `{stdout, stderr, exit_code, ok}` (v1.16) | | `dotenv(path)` | Load `.env` file into process environment — returns hash of loaded vars (v1.16) | --- ## Concurrency & Networking *(v1.17)* | Function | Description | |---|---| | `parallel_map(vec, workers: 4) do \|x\| ... end` | Thread-pool map — results in input order | | `tcp_connect(host, port, timeout: nil, tls: false)` | Open a TCP connection — `tls: true` for TLS (v1.19) | | `tcp_listen(port, host: "0.0.0.0")` | Listen on a port; `.accept()` returns a client socket | | `tcp_serve(port) do \|client\| ... end` | Threaded accept loop, auto-closes clients | | `sock.send(s)` / `sock.send_line(s)` | Send a string (newline appended by `send_line`) | | `sock.recv(n)` / `sock.recv_line()` | Receive a string — `nil` when peer closes | | `sock.peer()` / `sock.close()` | Remote `"host:port"` / close the connection | | `udp_listen(port, host: "0.0.0.0")` | Bind a UDP socket (v1.19) | | `udp_send(host, port, msg)` | Fire-and-forget datagram (v1.19) | | `sock.recv(n)` / `sock.send_to(host, port, msg)` | UDP receive/send — `recv` returns `{data:, host:, port:}` (v1.19) | --- ## Range Methods *(v1.17)* | Method | Description | |---|---| | `(1..10).to_vec` / `.to_a` | Convert to a vector | | `(1..10).include?(x)` | Membership test | | `(1..10).step(n)` | Stride: `(1..10).step(3)` → `[1, 4, 7, 10]` | | `(1..10).sum` | Sum of the range | | `(1..10).first` / `.last` | Endpoints | | `when 90..100` | Range membership in `case/when` | --- ## Modules & Errors *(v1.17)* | Syntax | Description | |---|---| | `import "lib/math" as math` | Load a `.fk` file into its own namespace | | `error TypeName` | Declare a user-defined error type | | `raise TypeName, "msg"` | Raise a typed error | | `rescue TypeName => e` | Catch a typed error (Ruby-style binding) | --- ## WebSockets *(v1.18)* | Function | Description | |---|---| | `app.websocket("/ws/:room") do \|ws\| ... end` | WebSocket route on the built-in server | | `ws_connect(url, timeout: nil)` | Client connection (`ws://` and `wss://` — TLS since v1.19) | | `ws.send(msg)` / `ws.recv()` | Text messages — `recv` returns `nil` on close | | `ws.close()` / `ws.params` / `ws.path` / `ws.peer` | Lifecycle + route metadata | --- ## Debugging & Benchmarking *(v1.18)* | Syntax | Description | |---|---| | `breakpoint` | Pause into a scoped debug REPL (skipped when not a tty) | | `breakpoint if cond` | Conditional breakpoint | | `frankiec run --debug app.fk` | Break at the first line automatically (v1.19) | | `(fkdb) s` / `n` / `stack` | Step in / step over / show call stack (v1.19) | | `benchmark ["label"] do ... end` | Time a block — returns elapsed ms | --- ## Labeled Loops *(v1.22)* | Syntax | Description | |---|---| | `loop :name do ... end` | Label a `loop` | | `while :name cond ... end` | Label a `while` | | `until :name cond ... end` | Label an `until` | | `for :name x in xs ... end` | Label a `for` — the label comes before the loop variable | | `break :name` | Exit the labeled loop, from anywhere nested inside it | | `next :name` | Skip to the next iteration of the labeled loop, from anywhere nested inside it | --- ## Type Annotations *(v1.19)* | Syntax | Description | |---|---| | `def area(r: Float) -> Float` | Parameter and return type annotations — optional, checked statically | | `Int`/`Integer`, `Float`/`Number`, `String`/`Str`, `Bool`/`Boolean` | Core type names (with aliases) | | `Vector`, `Hash`, `Lambda`, `Range`, `Nil`, `Any` | Remaining type names — `Any` matches anything | --- ## Enums & Set Operations *(v1.18)* | Syntax | Description | |---|---| | `enum Status(pending, active, done)` | Named symbolic values — members are their own names as strings | | `Status.values` / `Status.include?(x)` | All members / membership test | | `vec.union(v)` | Order-preserving union, deduplicating | | `vec.intersect(v)` | Elements present in both vectors | | `vec.difference(v)` | Elements not present in the argument | --- ## Numeric Literals *(v1.18)* | Syntax | Description | |---|---| | `1_000_000`, `3.141_592` | Underscore separators | | `1e6`, `2.5e-3`, `1E+9` | Scientific notation | --- ## Game Engines *(v1.20)* Loaded via `stitch "frankiegame"` (terminal) or `stitch "frankiecanvas"` (browser) — same API, nothing enters the global namespace until you stitch one in. Full reference: [frankiegame](../stitches/frankiegame.md), [frankiecanvas](../stitches/frankiecanvas.md). | Function | Description | |---|---| | `game_new(width:, height:, fps:, ...)` | Create the game state hash | | `on_key(g, key) do \|game\| ... end` | Handle one key | | `on_any_key(g) do \|game, key\| ... end` | Handle every key press | | `on_tick(g) do \|game\| ... end` | Called once per frame | | `clear(g)` / `draw(g, x, y, s, color: nil)` / `text(g, x, y, s, color: nil)` | Frame buffer + glyph drawing | | `draw_sprite(g, x, y, sprite, color: nil)` | Multi-line sprite, transparent spaces | | `load_image(path)` | Load a PNG/JPEG/GIF — real pixels on frankiecanvas, path-only placeholder on frankiegame (v1.21) | | `draw_image(g, x, y, image, w: 1, h: 1)` | Draw a loaded image — `▒` placeholder block on frankiegame (v1.21) | | `synth_play(g, freq:, wave:, dur:, gain:)` | WebAudio oscillator tone on frankiecanvas, terminal bell on frankiegame (v1.21) | | `collide?(x1, y1, w1, h1, x2, y2, w2, h2)` | AABB collision test | | `game_beep(g)` / `stop_game(g)` / `run_game(g)` | Sound (now a `synth_play` wrapper) / end loop / enter blocking loop | | `render_frame(g)` | Buffer as a string (headless tests) | | `rect(g, x, y, w, h, color)` | Filled rectangle — `frankiecanvas` only | | `on_player_key(g) do \|game, player, key\| ... end` | Per-player input — `frankiecanvas` only | | `players_count(g)` | Connected browser count — `frankiecanvas` only | --- ## Tooling Additions *(v1.19–v1.20.1)* | Command | Description | |---|---| | `frankiec run --debug app.fk` | Break at the first line automatically (v1.19) | | `frankiec test --coverage` | Report line coverage, writes `.frankie_coverage.json` (v1.19) | | `frankiec docs --html` | Render doc-comments as styled single-page HTML (v1.19) | | `frankiec stitch install ` | Install a stitch from any URL, not just the registry (v1.19) | | `frankiec new --game ` | Scaffold a playable starter game (v1.20) | | `frankiec examples [name]` | List bundled examples, or copy one into the current directory (v1.20.1) | | `brew install atejada/frankie/frankie` | Homebrew install (v1.20.1) | --- ## 🧊 Language Freeze *(v1.22)* Frankie is language-frozen as of v1.22.0 while "The Book of Frankie" is written against this exact version. Grammar, stdlib signatures, and stitch APIs are locked for the duration — patch releases (bug fixes, doc corrections) continue, but no new syntax or behavior changes until the freeze lifts. The freeze briefly lifted from v1.21.0 to v1.22.0 for one deliberate, final feature pass leaning into Frankie's FORTRAN heritage — Matrix math, Complex numbers, math intrinsics, and labeled loops — before locking again. No further feature releases are planned before the book ships. --- ## Operators Reference | Operator | Description | |---|---| | `+` `-` `*` `/` | Arithmetic | | `//` | Integer (floor) division | | `%` | Modulo | | `**` | Exponentiation | | `==` `!=` `<` `<=` `>` `>=` | Comparison | | `and` `or` `not` | Logical | | `=~` | Regex match — returns position or nil | | `\|>` | Pipe — pass left as argument to right | | `&.` | Nil-safe navigation — returns nil instead of crashing | | `\|` | Hash merge — right wins on conflict | | `..` | Inclusive range | | `...` | Exclusive range | | `+=` `-=` `*=` `/=` `//=` `**=` `%=` | Compound assignment | | `\|\|=` | Nil-coalescing assignment — assign only if nil or false (v1.16) | | `#{}` | String interpolation |