Metadata-Version: 2.4
Name: chemql-python
Version: 1.8.0
Summary: A chemistry-focused query language and REPL
Author-email: Mohammad Rakibul Islam <rakibulofficial1017@gmail.com>
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: prompt_toolkit>=3.0
Requires-Dist: rich>=13.7
Requires-Dist: pandas>=2.0
Requires-Dist: openpyxl>=3.1
Requires-Dist: xlrd>=2.0
Provides-Extra: test
Requires-Dist: pytest>=8.0; extra == "test"
Dynamic: license-file

# ChemQL & CodecQL

> A Python-embedded query language and terminal toolchain for chemistry data — with a purpose-built editor, package manager, and standard library.

ChemQL is a small language for querying, computing with, and simulating chemistry data (elements, molecules, reactions), layered on a Python runtime. It ships with an interactive REPL, a terminal editor (CodecQL), a desktop editor (CodecQLX), a type system (structs, records, enums), namespaces, modules, a macro/preprocessor system, a package manager, and a standard library.

- **Distribution name:** `chemql-python`
- **Import / CLI name:** `chemql`
- **Language version:** `1.8.0` (per `chemql.__version__`)
- **Editor version:** `codecql 0.1.2`
- **GUI Editor version:** `CodecQLX 1.1.1`
- **Author:** Mohammad Rakibul Islam
- **Minimum Python:** **3.12+** (verified with `vermin`)
- **Registry:** `https://chemqlreg.pythonanywhere.com/`

> ⚠️ **Safety:** ChemQL executes embedded Python (`[ ... ]`, `[[[ ... ]]]`) and real shell commands (`` ` ... ` ``, ` ``` ` blocks) with the permissions of the running process. Only run code and packages you trust.

---

## Contents

1. [Install](#install)
2. [Quick start](#quick-start)
3. [Function values — `fn{...}`](#function-values--fn)
4. [Symbolic algebra](#symbolic-algebra)
5. [Core commands](#core-commands)
6. [Query syntax](#query-syntax)
7. [Chemistry features](#chemistry-features)
8. [Data analysis and visualization](#data-analysis-and-visualization)
9. [Type system](#type-system)
10. [Namespaces & visibility](#namespaces--visibility)
11. [Modules](#modules)
12. [Functions, arguments, macros](#functions-arguments-macros)
13. [Control flow](#control-flow)
14. [Error handling](#error-handling)
15. [Python integration](#python-integration)
16. [Shell integration](#shell-integration)
17. [CodecQL — the terminal editor](#codecql--the-terminal-editor)
18. [CodecQLX — the desktop editor](#codecqlx--the-desktop-editor)
19. [Standard library](#standard-library)
20. [Built-in functions](#built-in-functions)
21. [Package manager](#package-manager)
22. [License and attribution](#license-and-attribution)

---

## Install

```bash
pip install chemql-python
```

Upgrade:

```bash
pip install --upgrade chemql-python
```

Dependencies: `rich`, `pandas`, `openpyxl`, `xlrd`, `prompt_toolkit`.

---

## Quick start

```text
$ chemql
Type help or ? for help
>>> search elements name like "Hydrogen"
H (Hydrogen)
>>> search molecules molecular_weight < 20 sort molecular_weight
H2 (Hydrogen)
>>> balance H2 + O2 -> H2O
2 H2 + O2 -> 2 H2O
>>> let water = {{ findmol "Water" }}
>>> water.smiles
O
>>> findmol "caffeine" return name formula molecular_weight
```

Non-interactive:

```bash
chemql -c 'search elements symbol = "Fe" return name symbol number'
chemql -f script.cql
chemql -f script.cql -o out.txt       # ANSI-stripped output to a file
chemql --no-ansi
chemql --suppress-warnings
```

Open a file in the bundled editor:

```bash
chemql edit script.cql
```

---

## Function values — `fn{...}`

`fn{params -> body}` creates a first-class function value. Parameters are comma-separated names; the body is any expression. Add `{args}` immediately after to call it in-place.

```chemql
// Immediate call
fn{x -> x * 2}{5}                       // 10

// Assign and call later
let double = fn{x -> x * 2}
double{5}                                // 10

// Multi-argument
fn{a, b -> a + b}{3, 4}                 // 7

// Curried — chain argument groups
fn{a -> fn{b -> a + b}}{1}{2}           // 3

// String juxtaposition — "text"name concatenates without +
fn{name -> "Hello "name}{20}            // Hello 20
fn{name -> "Hello "name}{"Alice"}       // Hello Alice
```

String juxtaposition joins a quoted string directly with any plain name or dotted path that follows it. Keywords (`if`, `and`, `in`, ...) are left alone.

```chemql
let who = "Bob"
"Hi "who                                 // Hi Bob
"a" if 1 else "b"                        // a  (keyword `if`, not joined)
"x" in "xyz"                             // True
```

When a call uses an unknown name as a lambda header, the error message suggests the fix:

```chemql
greet{name -> "Hello "name}
// Error: Unknown function `greet`.
// Did you mean `fn{name -> "Hello "name}` or `let greet = fn{name -> "Hello "name}`?
```

### Higher-order use

```chemql
let square = fn{x -> x * x}
load fp
fp::map{square, [1, 2, 3, 4]}           // [1, 4, 9, 16]
fp::filter{fn{x -> x > 2}, [1, 2, 3, 4]}
fp::reduce{fn{a, b -> a + b}, [1, 2, 3, 4]}
fp::iterate{fn{x -> x * 2}, 1, 6}       // [1, 2, 4, 8, 16, 32]

let slope = fn{f -> sym_diff{f, "x"}}
slope{"x^3 + 2x"}                        // 3x^2 + 2
```

---

## Symbolic algebra

`algebra <maths>` (alias `sym`) hands the rest of the line to the built-in symbolic engine. The text is read as pure maths, so LaTeX such as `\frac{x}{y}` is not rewritten by ChemQL. Symbolic variables are separate from ChemQL `let` variables.

```chemql
algebra let a = 3
algebra diff x: x^3 + a*x          // 3x^2 + 3
algebra integrate x from 0 to 3: x^2
algebra solve x^2 - 4 = 0
algebra solve x + y = 3; x - y = 1
algebra factor x: x^3 - x
algebra f(x) = x^2 + 1
algebra f(3)                        // 10
algebra let A = \begin{matrix}1 & 2 \\ 3 & 4\end{matrix}
algebra det(A)
algebra inv(A)
algebra plot x from -5 to 5: sin(x)
algebra table x=0..5 step 1: x^2
algebra gcd 12, 18
algebra factorint 360
algebra set precision 50
algebra vars
algebra reset
algebra help
```

The same operations are available as brace functions that work inside `fn{...}`, `fp::map`, and anywhere else a ChemQL value is expected:

| Function | Signature | Example |
|---|---|---|
| `sym_eval` | `{expr, values?}` | `sym_eval{"(x^2-1)/(x-1)"}` → `x + 1` |
| `sym_diff` | `{expr, var?, order?}` | `sym_diff{"x^4", "x", 2}` → `12x^2` |
| `sym_integrate` | `{expr, var?, lower?, upper?}` | `sym_integrate{"x^2", "x", 0, 3}` → `9` |
| `sym_solve` | `{eq, ...}` | `sym_solve{"x + y = 3", "x - y = 1"}` |
| `sym_factor` | `{expr, var?}` | `sym_factor{"x^3 - x", "x"}` → `x(x-1)(x+1)` |
| `sym_table` | `{expr, var, start, stop, step?}` | `sym_table{"x^2", "x", 0, 3}` |
| `sym_let` | `{name, expr}` | `sym_let{"a", "2x+1"}` |
| `sym_define` | `{signature, body}` | `sym_define{"f(x)", "x^2+1"}` |
| `sym_set` | `{"precision"\|"mode", value}` | `sym_set{"precision", 50}` |
| `sym_vars` | `{}` | list symbolic variables |
| `sym_reset` | `{}` | forget all symbolic state |

Pass ChemQL values into symbolic expressions with `${...}`:

```chemql
let n = 5
sym_eval{"x^2 + ${n}"}              // x^2 + 5
```

Combine with lambdas:

```chemql
let slope = fn{f -> sym_diff{f, "x"}}
slope{"x^3 + 2x"}                   // 3x^2 + 2

load fp
fp::map{fn{expr -> sym_diff{expr, "x"}}, ["x^2", "x^3", "sin(x)"]}
```

LaTeX environments (`\begin{...}`) must be written on one line. `algebra plot` is blocked by `--sandbox`.

---

## Core commands

| Command | Purpose |
|---|---|
| `search [first\|last\|all] <source> <conditions> [ops] [return fields]` | Query a data source |
| `source <elements\|molecules\|reactions>` | Set the default source |
| `findel <name-or-symbol> [return ...]` | Element lookup |
| `findmol <name-or-formula> [return ...]` | Molecule lookup (local → PubChem → ChemSpider → NIST) |
| `findre <name-or-id> [return ...]` | Reaction lookup (local → Rhea → Chempirical) |
| `balance <reactants> ->\|<-> <products>` | Balance a chemical equation |
| `react <coefficients><molecules>` | Match a stored reaction under current conditions |
| `set temperature\|pressure\|catalysts <value>` | Set reaction conditions |
| `add\|remove catalyst "<name>"` | Modify the catalyst list |
| `conditions` | Show current T / P / catalysts |
| `algebra <maths>` / `sym <maths>` | Symbolic algebra |
| `let <name> = <expr>` / `unset <name>` / `variables` | Bind, remove, list variables |
| `define NAME <value>` / `@NAME` | Object-like macro |
| `define NAME{} ... enddefine` / `@NAME{...}` | Function-like macro |
| `definitions` / `macros` / `remove definition\|macro NAME` | Inspect / remove |
| `func NAME ... endfunc` | Define a function |
| `static func Type.method ... endfunc` | Static method |
| `struct` / `record` / `enum` ... `end*` | Define types |
| `namespace NAME ... endnamespace` | Group declarations |
| `load <pkg> [as <alias>]` | Load a package |
| `load <member> from <pkg> [as <alias>]` | Import one name |
| `help [topic]` / `?` | Help |
| `dump [all\|good\|bad] [queries\|results] FILE` | Export history |
| `view` | Open periodic-table viewer |
| `clear` / `version` / `exit` | Misc |

---

## Query syntax

**Sources:** `elements`, `molecules`, `reactions`.

**Operators:**

| Operator | Meaning |
|---|---|
| `=` `!=` `>` `<` `>=` `<=` | Comparison |
| `like` | Case-insensitive wildcard match |
| `like!` | Case-sensitive wildcard match |
| `likep` | Regex match |
| `has` | Nested containment |
| `and` `or` `not` `( )` | Boolean logic |

**`like` wildcards:**

| Token | Matches |
|---|---|
| `*` | Any characters |
| `%` | Digits only |
| `&` | Letters only |
| `_` | Any single character |
| `#` | A single digit |
| `?` | A single letter |
| `\` | Escape |

**Result operations:** `sort FIELD [asc|desc]`, `limit N`, `count`, `return FIELD ...`, `union`, `intersection`.

```chemql
search elements number > 10 and number < 20 return name symbol
search molecules molecular_weight < 50 sort molecular_weight limit 10
search reactions reversible = true return name equation source
search elements name like "H*"
```

---

## Chemistry features

### Data

```chemql
findel "iron"
findel Fe
findmol "caffeine"
findmol "C8H10N4O2"
findre "combustion"
element{Fe, "melting_point"}
molar_mass{"H2O"}                    // 18.015
empirical_formula{"C6H12O6"}         // CH2O
count_atoms{"H2SO4"}                 // {"H":2,"S":1,"O":4}
```

### External lookups

`findmol` tries local data, then PubChem, ChemSpider, and NIST in sequence. `findre` tries local data, then Rhea and Chempirical. Network access is blocked in `--sandbox` mode.

### Balancing

```chemql
balance H2 + O2 -> H2O
balance Fe + O2 -> Fe2O3
balance CH4 + O2 -> CO2 + H2O
```

### Reaction simulation

```chemql
set temperature 400
set pressure 10
add catalyst "V2O5"
react 2SO2 + O2 -> 2SO3
conditions
```

### Chemistry built-ins

| Function | Purpose |
|---|---|
| `element{symbol, field?}` | Element data |
| `molar_mass{formula}` | Molar mass in g/mol |
| `empirical_formula{formula}` | Empirical formula |
| `count_atoms{formula}` | Atom counts as a dict |

---

## Data analysis and visualization

### Chart types

`chart` accepts: `bar`, `line`, `scatter`, `histogram`, `pie`, `donut`, `area`, `box`, `heatmap`, `radar`, `bubble`, `waterfall`, `treemap`, `funnel`, `gantt`, `candlestick`, `sankey`, `sunburst`, `parallel`.

```chemql
let temps = [20, 25, 30, 35, 40]
let yield_vals = [0.4, 0.6, 0.75, 0.7, 0.55]
chart{"line", temps, yield_vals}
```

### Plot from scripts

```chemql
load csv{"data.csv"}
plot{x, y, title="My Chart", xlabel="Time (s)", ylabel="Signal"}
heatmap{matrix, colormap="viridis"}
```

### Spreadsheet / GUI dashboard

```chemql
run_spreadsheet_gui{}
```

---

## Type system

### Structs — mutable, methods, inheritance

```chemql
struct Animal
    public name
    public sound

    func speak{}
        return self.name + " says " + self.sound
    endfunc
endstruct

let dog = Animal{"Rex", "Woof"}
dog.speak{}
dog.name = "Buddy"

struct Dog extends Animal
    public breed

    func speak{}
        return self.name + " (" + self.breed + ") barks"
    endfunc
endstruct

let d = Dog{"Rex", "Woof", "Labrador"}
d.speak{}
```

### Records — immutable, positional, trailing defaults

```chemql
record Point{x, y}
let p = Point{3, 4}
p.x                                  // 3

record Config{host, port=8080}
let c = Config{"localhost"}
c.port                               // 8080
```

### Enums — named singletons with payloads

```chemql
enum Color{Red, Green, Blue}
let c = Color.Red
c == Color.Red                       // True

enum Shape{Circle{radius}, Rect{w, h}}
let s = Shape.Circle{5}
s.radius                             // 5
```

### Summary

| Feature | Mutable | Inheritance | Positional | Payload |
|---|---|---|---|---|
| `struct` | yes | yes | yes | — |
| `record` | no | — | yes | — |
| `enum` | no | — | — | yes |

---

## Namespaces & visibility

```chemql
namespace geometry
    public func area{r}
        return 3.14159 * r * r
    endfunc

    private func _helper{}
        return 42
    endfunc
endnamespace

geometry::area{5}
```

`public` members are accessible from outside; `private` members are not. Use `load member from pkg` to bring a name into the current scope.

---

## Modules

A `.cql` file is a module. Load it with:

```chemql
load "mymodule.cql"
```

Or install a package and load it:

```bash
chemql install mypackage
```

```chemql
load mypackage
mypackage::some_func{"arg"}
```

---

## Functions, arguments, macros

```chemql
func greet{name, age=10}
    let value = str{name}
    return value, age, arguments
endfunc

greet{"Jacob"}                       // ("Jacob", 10, ["Jacob", 10])
greet{age=30, name="Jacob"}          // ("Jacob", 30, ["Jacob", 30])
```

Declare parameters inside `{}` after the function name. Parameters can be required, have a default (`age=10`), or be optional (`age?`, equivalent to `age=None`). Calls may pass values positionally or by name.

`arguments` is a per-call list in declared parameter order. `kwarguments` contains explicitly supplied keyword arguments.

```chemql
func describe{name, age?}
    if age is None
        return "I am " + str{name}
    endif
    return "I am " + str{name} + " and I am " + str{age}
endfunc

describe{name="Jacob"}               // "I am Jacob"
```

### Passing functions as arguments

Any `func` and any `fn{...}` value can be passed to another function:

```chemql
func apply_twice{f, x}
    return f{f{x}}
endfunc

apply_twice{fn{x -> x * 2}, 3}      // 12

func transform{data, mapper, filterer}
    return fp::filter{filterer, fp::map{mapper, data}}
endfunc

transform{[1,2,3,4,5], fn{x -> x*x}, fn{x -> x > 5}}
```

### Definitions (object-like)

```chemql
define MAX 9
@MAX * 9          // 81
print("2@MAX")    // "29"
```

### Macros (function-like)

```chemql
define CLAMP{}
\1 if \1 > 0 else 0
enddefine

@CLAMP{-5}        // 0
@CLAMP{3}         // 3
```

---

## Control flow

```chemql
if x > 10
    let y = "big"
elif x > 5
    let y = "medium"
else
    let y = "small"
endif

for i in range(3)
    print(i)
endfor

while i < 5
    let i = i + 1
endwhile
```

- `break` / `continue` / `skip` (alias for continue)
- Bracketed Python-style blocks also accepted: `[for ...]  ... [endblock]`

---

## Error handling

```chemql
risk
    signal "Something went wrong"
fix
    let handled = error
cleanup
    let finished = true
endrisk
```

- `signal "msg"` raises a recoverable ChemQL signal
- `warn "msg"` sets `warnings` and prints (suppress with `--suppress-warnings`)
- `error` holds the last error type (or `None` after success)

---

## Python integration

Inline expression:

```chemql
[1 + 2 * 3]              // 7
[x * 2]
```

Multiline Python block:

```chemql
[[[
for x in range(3):
    print(x)
]]]
```

Embedded queries inside Python:

```chemql
let m = [len({{ search molecules molecular_weight < 20 }})]
```

---

## Shell integration

Inline:

```chemql
`echo hello`
let files = `ls -1`
```

Multiline:

````chemql
```bash
echo "Hello from shell"
ls -la
```
````

Shell blocks are disabled in `--sandbox` mode.

---

## CodecQL — the terminal editor

### Starting CodecQL

```bash
chemql edit                     # blank buffer
chemql edit script.cql          # open a file
chemql edit script.cql -r       # read-only
```

### Key bindings

| Key | Action |
|---|---|
| `Ctrl+S` | Save |
| `Ctrl+Q` | Quit |
| `Ctrl+R` | Run current file |
| `Ctrl+F` | Find |
| `Ctrl+H` | Find and replace |
| `Ctrl+G` | Go to line |
| `Ctrl+A` | Select all |
| `Ctrl+C` / `Ctrl+V` / `Ctrl+X` | Copy / Paste / Cut |
| `Ctrl+Z` / `Ctrl+Y` | Undo / Redo |
| `Alt+Up/Down` | Move line up/down |
| `Tab` | Indent / accept suggestion |
| `Shift+Tab` | Dedent |
| `F5` | Run |
| `F6` | Run selection |

### Search

`Ctrl+F` opens an inline search bar. `Ctrl+H` opens find-and-replace. Both support plain text and regex (`/pattern/` syntax).

### Syntax highlighting

Highlighting rules live in `highlighting.json` in the ChemQL config directory. The following keyword groups are highlighted: commands (`balance`, `algebra`, `sym`, `react`, `findel`, `findmol`, `findre`, `load`, ...), control flow (`if`, `for`, `while`, `endif`, ...), type keywords (`struct`, `record`, `enum`, ...), and all standard library package names (`fp`, `iter`, `predicates`, `pipeline`, `state`, `events`, `async`, `math`, `text`, `collections`, ...).

### Inline suggestions

CodecQL shows completions as you type. `Tab` accepts the highlighted suggestion; `Esc` dismisses it. The engine knows about commands, keywords, variables in scope, and loaded package members.

### Configuration: `highlighting.json`

```json
{
  "keywords": { "color": "cyan" },
  "strings":  { "color": "green" },
  "comments": { "color": "bright_black" },
  "numbers":  { "color": "yellow" }
}
```

### CodecQL known limitations

- No LSP or external formatter integration
- Terminal emulator must support 256 colors or true color for best results
- Very large files (> 50 000 lines) may be slow to load

---

## CodecQLX — the desktop editor

CodecQLX is the cross-platform GUI editor for ChemQL, wrapping CodecQL in a native window with a menu bar, file tabs, and an integrated terminal.

### Starting CodecQLX

```bash
chemql gui                      # launch the GUI
chemql gui script.cql           # open a file
```

### Features

- Syntax-highlighted editor (uses the same `highlighting.json` as CodecQL)
- File tabs; reopen recent files from **File → Recent**
- Integrated terminal; runs `chemql` automatically
- Split-pane output view
- Settings dialog for font size, theme, and auto-save interval
- **Run** toolbar button, also bound to `F5`

### Keyboard shortcuts

| Shortcut | Action |
|---|---|
| `Ctrl+N` | New file |
| `Ctrl+O` | Open |
| `Ctrl+S` | Save |
| `Ctrl+Shift+S` | Save as |
| `Ctrl+W` | Close tab |
| `F5` | Run |
| `Ctrl+F` | Find |
| `Ctrl+H` | Replace |

---

## Standard library

Load with `load <pkg>`; call as `<pkg>::name{...}`. Use `help{stdlib}` to list all packages, `help{fp}` for a category, and `help{fp::map}` for a single function.

### Core packages

| Package | Purpose |
|---|---|
| `math` | Constants, trigonometry, logarithms, number theory |
| `math::statistics` | Mean, median, mode, variance, std dev, quantiles |
| `math::calculus` | Numerical differentiation and integration |
| `math::probability` | Combinatorics and distributions |
| `math::linalg` | Vectors, matrices, norms |
| `math::inference` | Hypothesis tests, confidence intervals |
| `text` | String transforms, splitting/joining, regex helpers |
| `collections` | Uniqueness, flattening, pairing, frequency counts |
| `sequences` | Slicing, windowing, zipping |
| `maps` | Dict merging, inversion, filtering |
| `tables` | Tabular data manipulation |
| `datetime` | Dates, timestamps, local/UTC time, date arithmetic |
| `json` | JSON encode/decode helpers |
| `random` | Pseudo-random numbers and sequence sampling |
| `decimal` | Base-10 decimal arithmetic and quantization |
| `fractions` | Exact rational numbers and fraction arithmetic |
| `pathlib` | Path inspection and UTF-8 text file operations |

### `fp` — Functional programming

Requires `fn{...}`. Load with `load fp`.

```chemql
load fp

// Transform
fp::map{fn{x -> x * 2}, [1, 2, 3]}              // [2, 4, 6]
fp::filter{fn{x -> x > 2}, [1, 2, 3, 4]}        // [3, 4]
fp::reject{fn{x -> x > 2}, [1, 2, 3, 4]}        // [1, 2]
fp::flat_map{fn{x -> [x, x*2]}, [1, 2, 3]}      // [1, 2, 2, 4, 3, 6]
fp::zip_with{fn{a, b -> a + b}, [1,2,3], [4,5,6]}
fp::zip_into{fn{a, b -> a * b}, [[1,2,3],[4,5,6]]}
fp::apply_map{fn{a, b -> a + b}, [[1,4],[2,5],[3,6]]}

// Accumulate
fp::reduce{fn{a, b -> a + b}, [1, 2, 3, 4]}     // 10
fp::scan{fn{a, b -> a + b}, [1, 2, 3, 4]}       // [1, 3, 6, 10]

// Group and count
fp::group_by{fn{x -> x % 2}, [1, 2, 3, 4, 5]}  // {"1":[1,3,5],"0":[2,4]}
fp::count_by{fn{x -> x % 2}, [1, 2, 3, 4, 5]}
fp::partition{fn{x -> x > 2}, [1, 2, 3, 4]}    // [[3,4],[1,2]]

// Search
fp::find{fn{x -> x > 3}, [1, 2, 3, 4, 5]}      // 4
fp::find_index{fn{x -> x > 3}, [1, 2, 3, 4, 5]}
fp::sort_by{fn{x -> -x}, [3, 1, 4, 1, 5]}      // [5,4,3,1,1]
fp::min_by{fn{x -> abs(x)}, [-5, 3, -1, 4]}    // -1
fp::max_by{fn{x -> abs(x)}, [-5, 3, -1, 4]}    // -5

// Test
fp::all{fn{x -> x > 0}, [1, 2, 3]}             // True
fp::any{fn{x -> x > 4}, [1, 2, 3, 4, 5]}
fp::none{fn{x -> x > 10}, [1, 2, 3]}
fp::take_while{fn{x -> x < 4}, [1, 2, 3, 4, 5]}
fp::drop_while{fn{x -> x < 3}, [1, 2, 3, 4, 5]}

// Sequence building
fp::iterate{fn{x -> x * 2}, 1, 5}               // [1, 2, 4, 8, 16]
fp::pipe{3, [fn{x -> x+1}, fn{x -> x*2}]}       // 8

// Combinators
let double_then_inc = fp::compose{fn{x -> x+1}, fn{x -> x*2}}
double_then_inc{3}                               // 7

let fast_sq = fp::memoize{fn{x -> x * x}}
fast_sq{7}                                       // 49 (cached across calls)

let flip_sub = fp::flip{fn{a, b -> a - b}}
flip_sub{10, 3}                                  // -7  (arguments reversed)

let const42 = fp::constantly{42}
const42{1, 2, 3}                                 // 42  (ignores its arguments)

fp::identity{99}                                 // 99
fp::apply{fn{a, b, c -> a+b+c}, [1, 2, 3]}     // 6
fp::juxt{[fn{x->x+1}, fn{x->x*2}], 3}          // [4, 6]
fp::each{fn{x -> print(x)}, [1, 2, 3]}
```

### `iter` — Iteration

Lazy-style iteration; all output is a plain list. Load with `load iter`.

```chemql
load iter

// Generating sequences
iter::generate{fn{x -> x*2}, 1, 6}              // [1, 2, 4, 8, 16, 32]
iter::generate_while{fn{x -> x*2}, 1, fn{x -> x < 50}}
iter::tabulate{fn{i -> i*i}, 5}                 // [0, 1, 4, 9, 16]
iter::unfold{fn{n -> [n, n+1] if n < 5 else None}, 0, 10}
iter::cycle{[1, 2, 3], 7}                       // [1,2,3,1,2,3,1]
iter::apply_n{fn{x -> x+1}, 0, 5}              // 5

// Reshaping
iter::enumerate_list{["a","b","c"]}              // [[0,"a"],[1,"b"],[2,"c"]]
iter::zip_map{["a","b","c"], [1,2,3]}            // {"a":1,"b":2,"c":3}
iter::chain{[[1,2],[3,4],[5]]}                   // [1,2,3,4,5]
iter::distinct_by{fn{x -> x % 3}, [1,2,3,4,5,6]}
iter::split_by{fn{x -> x == 0}, [1,2,0,3,4,0,5]}

// Windowed operations
iter::window_map{fn{w -> w[0]+w[1]}, [1,2,3,4], 2}
iter::sliding_reduce{fn{a,b -> a+b}, [1,2,3,4,5], 3}
iter::batch_map{fn{b -> sum(b)}, [1,2,3,4,5,6], 2}

// Compression
iter::run_length{[1,1,2,3,3,3]}                 // [[1,2],[2,1],[3,3]]
iter::run_length_decode{[[1,2],[2,1],[3,3]]}     // [1,1,2,3,3,3]

// Side effects without changing values
iter::tee{fn{x -> print(x)}, [1,2,3]}
```

### `predicates` — Predicate combinators

Build reusable filter functions that compose cleanly. Load with `load predicates`.

```chemql
load predicates
load fp

// Comparison predicates
fp::filter{predicates::greater_than{3}, [1, 2, 3, 4, 5]}
fp::filter{predicates::less_than{3}, [1, 2, 3, 4, 5]}
fp::filter{predicates::between{2, 4}, [1, 2, 3, 4, 5]}
fp::filter{predicates::equals{3}, [1, 2, 3, 4, 5]}

// String predicates
fp::filter{predicates::has_prefix{"he"}, ["hello","world","hey"]}
fp::filter{predicates::has_suffix{".py"}, ["foo.py","bar.js"]}
fp::filter{predicates::contains{"ell"}, ["hello","world"]}
fp::filter{predicates::matches{"[0-9]+"}, ["abc","123","4x"]}

// Collection predicates
fp::filter{predicates::is_in{[1, 3, 5]}, [1, 2, 3, 4, 5]}
fp::filter{predicates::not_in{[1, 3, 5]}, [1, 2, 3, 4, 5]}
fp::filter{predicates::length_at_least{3}, ["a","ab","abc","abcd"]}
fp::filter{predicates::has_key{"name"}, [{"name":"Bob"},{"age":5}]}

// Dict field predicates
fp::filter{predicates::key_satisfies{"age", predicates::greater_than{18}},
           [{"age":15},{"age":25},{"age":30}]}

// Type predicates
fp::filter{predicates::is_type{"int"}, [1, "a", 2.0, True]}
fp::filter{predicates::is_not_none{}, [1, None, 2, None, 3]}

// Logical combinators
let adult = predicates::greater_or_equal{18}
let teen  = predicates::between{13, 17}
let minor = predicates::not_pred{adult}
let teenager_or_older = predicates::or_pred{teen, adult}
let all_checks = predicates::all_pred{[predicates::greater_than{0}, predicates::less_than{100}]}

fp::filter{minor, [10, 15, 18, 25]}
fp::filter{all_checks, [-1, 0, 50, 100, 101]}
```

All builders: `equals`, `not_equals`, `greater_than`, `greater_or_equal`, `less_than`, `less_or_equal`, `between`, `is_in`, `not_in`, `has_prefix`, `has_suffix`, `contains`, `matches`, `is_type`, `is_none`, `is_not_none`, `is_truthy`, `is_falsy`, `has_key`, `length_equals`, `length_at_least`, `length_at_most`, `not_pred`, `and_pred`, `or_pred`, `all_pred`, `any_pred`, `key_satisfies`.

### `pipeline` — Data pipelines

Build and run named multi-step transformations. Load with `load pipeline`.

```chemql
load pipeline

// Define steps: pipeline::step{name, fn}
let clean   = pipeline::step{"strip",   fn{s -> s.strip()}}
let upper   = pipeline::step{"upper",   fn{s -> s.upper()}}
let exclaim = pipeline::step{"exclaim", fn{s -> s+"!"}}
let steps   = [clean, upper, exclaim]

// Run
pipeline::run{steps, "  hello  "}              // "HELLO!"
pipeline::run_each{steps, ["  hi  "," world "]}
pipeline::run_traced{steps, "  hello  "}       // {result, trace:[{step,output},...]}

// Build up pipelines
let steps2 = pipeline::append_step{steps, "length", fn{s -> len(s)}}
let steps3 = pipeline::prepend_step{steps, "lower", fn{s -> s.lower()}}
let all    = pipeline::concat_pipelines{steps, steps2}
pipeline::step_names{steps}                    // ["strip","upper","exclaim"]

// Branching and looping
pipeline::run_conditional{fn{x -> x > 0}, positive_steps, negative_steps, value}
pipeline::run_while{fn{x -> x < 100}, steps, 1}
pipeline::run_until{fn{x -> x > 1000}, steps, 1}

// Same data through several pipelines at once
pipeline::run_parallel{[steps, steps2], "  hello  "}
```

`run_traced` returns `{result, trace}` where `trace` is a list of `{step, output}` dicts, one per step. If a step raises an error it records `{step, error}` and stops.

### `state` — Mutable state

Atoms (single values) and stores (key-value dicts), both thread-safe, with optional validators and change watchers. Load with `load state`.

```chemql
load state

// Atom — a single mutable value
let counter = state::atom{0}
state::deref{counter}                           // 0
state::swap{counter, fn{x -> x + 1}}           // 1
state::swap{counter, fn{x -> x + 1}}           // 2
state::reset_atom{counter, 10}                 // 10
state::deref{counter}                           // 10

// Validator — new value must satisfy the predicate
let positive = state::atom{0, fn{x -> x >= 0}}
state::reset_atom{positive, 5}                 // 5
state::reset_atom{positive, -1}                // Error: failed validator

// Watch for changes
state::watch{counter, fn{old, new -> print("changed: "old" -> "new)}}
state::unwatch{counter, handler}

// Store — key-value dictionary
let init = {"host": "localhost", "port": 8080}
let cfg = state::store{init}
state::store_get{cfg, "host"}                  // "localhost"
state::store_set{cfg, "debug", True}
state::store_update{cfg, {"port": 9000, "timeout": 30}}
state::store_delete{cfg, "debug"}
state::store_all{cfg}                          // full snapshot as a dict

// Computed value derived from several atoms (call to recompute)
let x = state::atom{3}
let y = state::atom{4}
state::computed{fn{a, b -> a + b}, [x, y]}    // 7
```

> **Note on dict literals:** pass the initial dict for a store through a variable — `let d = {...}` then `state::store{d}` — rather than `state::store{{"key": "val"}}`, which triggers ChemQL's template syntax.

### `events` — Event bus

In-process publish/subscribe. Load with `load events`.

```chemql
load events
load state

let last_temp = state::atom{None}

// Subscribe
events::subscribe{"temperature.changed", fn{t -> state::reset_atom{last_temp, t}}}

// One-shot handler
events::once{"startup", fn{data -> print("started: "data)}}

// Publish
events::publish{"temperature.changed", 42.5}
state::deref{last_temp}                        // 42.5

// Batch publish: each item is [event] or [event, data]
events::publish_many{[["a.fired"], ["b.fired", 99]]}

// Inspect
events::subscribers{"temperature.changed"}    // 1
events::log{10}                               // last 10 events [{event, data}]
events::clear_log{}
events::unsubscribe{"temperature.changed"}    // remove all handlers for event
events::unsubscribe{"temperature.changed", handler}  // remove one handler
events::reset{}                               // clear everything
```

### `async` — Concurrent execution

Runs functions in a thread pool. All functions must be zero-argument (`fn{-> expr}`) for `run_all` and `race`; `parallel_map` and `parallel_filter` supply the argument automatically. Load with `load async`.

```chemql
load async

// Parallel map and filter
async::parallel_map{fn{x -> x * 2}, [1, 2, 3, 4]}           // [2, 4, 6, 8]
async::parallel_filter{fn{x -> x % 2 == 0}, [1,2,3,4,5,6]}  // [2,4,6]
async::parallel_all{fn{x -> x > 0}, [1, 2, 3]}
async::parallel_any{fn{x -> x > 4}, [1, 2, 3, 4, 5]}

// Run several tasks at once
async::run_all{[fn{-> fetch_a{}}, fn{-> fetch_b{}}, fn{-> fetch_c{}}]}

// Race to the first result
async::race{[fn{-> slow_a{}}, fn{-> fast_b{}}]}

// Timeout guard
async::with_timeout{fn{-> long_task{}}, 5.0}

// Measure elapsed time
let result = async::timed{fn{-> heavy_computation{}}}
result[0]                                      // return value
result[1]                                      // elapsed seconds

// Map with index exposed
async::parallel_map_indexed{fn{i, x -> str{i}+": "+str{x}}, ["a","b","c"]}
```

---

## Built-in functions

### General

`abs round min max sum len type str int float bool upper lower contains replace split join first last unique sort reversed`

### File I/O

`read_text read_lines read_json read_csv write_text write_csv write_json file_exists list_files`

### Chemistry

`element count_atoms molar_mass empirical_formula`

### Symbolic algebra (brace-call form)

`sym_eval sym_diff sym_integrate sym_solve sym_factor sym_table sym_let sym_define sym_set sym_vars sym_reset`

### Help

```chemql
help{}                // overview by category
help{fp}              // all fp functions
help{fp::map}         // one function
help{algebra}         // algebra command reference
help{stdlib}          // all packages
help{struct}          // type system
```

---

## Package manager

```bash
chemql install <name> [--version V]
chemql upgrade <name> [--version V]
chemql uninstall <name>
chemql list
chemql search <query>
chemql info <name>
chemql build            # requires cqlpackage.json / cqlpackage.toml
chemql upload           # publish to the registry
chemql init [name] [-d dir]
```

Inside the REPL: `install <name> [--version V]`.

Package layout:

```
~/.chemql/packages/<name>/<version>/
```

---

## License and attribution

[MIT License](https://github.com/rakibulofficial1017/ChemQL/blob/main/LICENSE)

Created by [Mohammad Rakibul Islam](https://github.com/rakibulofficial1017).  
Source code: [rakibulofficial1017/ChemQL](https://github.com/rakibulofficial1017/ChemQL).

---

For the command reference that matches your installed build, type `help` inside ChemQL.
