Language Reference

Every built-in function, special form, and macro in the mino language. Organized by category with usage examples from the test suite. Coming from Clojure?

Arithmetic

+

Returns the sum of the arguments. Throws on long overflow; use +' to auto-promote to bigint.

(+ 1 2)
3
(+ 1 2.5)
3.5
(+ (dec' max-int) 1)
max-int

-

Returns the difference of the arguments. With one arg, returns the negation. Throws on long overflow; use -' to auto-promote.

(- 10 3 2)
5
(- 7)
-7
(- tag-min 1)
tag-min-minus-1

*

Returns the product of the arguments. Throws on long overflow; use *' to auto-promote.

(* 2 3 4)
24
(* max-int 1)
max-int
(* 2 (quot (- tag-max 1) 2))
(- tag-max 1)

/

Returns the quotient of the arguments.

(/ 10 4)
5/2
(double (/ 10 4))
2.5
(/ 4 2)
2

mod

Returns the modulus of dividing num by div. Truncates toward negative infinity.

(mod 10 3)
1
(mod -10 3)
2
(mod 5.5 2.0)
1.5

rem

Returns the remainder of dividing num by div.

(rem 10 3)
1
(rem -10 3)
-1
(rem 4 2)
0

quot

Returns the quotient of dividing num by div, truncated toward zero.

(quot 10 3)
3
(quot -10 3)
-3
(* 2 (quot (- tag-max 1) 2))
(- tag-max 1)

inc

Returns x plus 1. Throws on long overflow; use inc' to auto-promote.

(inc 5)
6
(inc tag-max)
tag-max-plus-1
(type (inc tag-max))
:int

dec

Returns x minus 1. Throws on long overflow; use dec' to auto-promote.

(dec 5)
4
(dec tag-min)
tag-min-minus-1
(type (dec tag-min))
:int

+'

Returns the sum of the arguments. Auto-promotes to bigint on long overflow; use + to throw on overflow.

(+' max-int 1)
9223372036854775808N
(+' 1 max-int)
9223372036854775808N
(+' min-int -1)
-9223372036854775809N

-'

Returns the difference of the arguments. With one arg, returns the negation. Auto-promotes to bigint on long overflow.

(-' min-int 1)
-9223372036854775809N
(-' max-int -1)
9223372036854775808N
(-' min-int)
9223372036854775808N

*'

Returns the product of the arguments. Auto-promotes to bigint on long overflow.

(*' max-int 2)
18446744073709551614N
(*' -1 min-int)
9223372036854775808N
(*' min-int -1)
9223372036854775808N

inc'

Returns x plus 1. Auto-promotes to bigint on long overflow.

(inc' max-int)
9223372036854775808N
(inc' 9223372036854775807)
9223372036854775808N

dec'

Returns x minus 1. Auto-promotes to bigint on long overflow.

(dec' min-int)
-9223372036854775809N
(+ (dec' max-int) 1)
max-int
(dec' -9223372036854775808)
-9223372036854775809N

Comparison

=

Returns true if all arguments are equal.

(take 4 (iterate #(if (= % :foo) 42 :foo) :foo))
'(:foo 42 :foo 42)
(loop [n 100 acc 0]
(if (= n 0)
  acc
  (recur (- n 1) (+ acc n))))
5050

<

Returns true if nums are in monotonically increasing order.

(loop [a 1]
(if (< a 3)
  (recur (inc a))
  a))
3
(cond (< 3 2) (+ 1 2) true :result true (throw (ex-info "boom" {})))
:result
(loop* [i 0] (if (< i 5) (recur (inc i)) i))
5

<=

Returns true if nums are in monotonically non-decreasing order.

(letfn [(factorial [n]
         (if (<= n 1) 1 (* n (factorial (dec n)))))]
(factorial 5))
120
(loop [n 5 acc 1]
(if (<= n 1) acc (recur (- n 1) (* acc n))))
120
(loop [n 5 acc 1]
(if (<= n 1) acc (recur (- n 1) (* acc n))))
120

>

Returns true if nums are in monotonically decreasing order.

(cond (> 3 2) (+ 1 2) true :result true (throw (ex-info "boom" {})))
3
((every-pred even? number? #(> % 0)))
true
((every-pred even? number? #(> % 0)) 2 4 6 8 10)
true

>=

Returns true if nums are in monotonically non-increasing order.

(reduce (fn [a x] (if (>= x 10) (reduced a) (+ a x)))
0 v)
45

not=

Returns true if the arguments are not equal.

compare

Returns a negative, zero, or positive integer comparing x and y.

(compare 1 2)
-1
(compare 5 5)
0
(compare 10 3)
1

Math

math-floor

Returns the largest integer not greater than n.

(math-floor 3.7)
3.0
(math-floor 3.0)
3.0
(math-floor -3.2)
-4.0

math-ceil

Returns the smallest integer not less than n.

(math-ceil 3.2)
4.0
(math-ceil 3.0)
3.0
(math-ceil -3.2)
-3.0

math-round

Returns the closest integer to n.

(math-round 3.5)
4.0
(math-round 3.4)
3.0
(math-round -3.5)
-4.0

math-sqrt

Returns the square root of n.

(math-sqrt 16)
4.0
(math-sqrt 0)
0.0
(math-sqrt 1)
1.0

math-pow

Returns base raised to the power of exp.

(math-pow 2 10)
1024.0
(math-pow 5 0)
1.0
(math-pow 2 3)
8.0

math-log

Returns the natural logarithm of n.

(math-log 1)
0.0

math-exp

Returns e raised to the power of n.

(math-exp 0)
1.0

math-sin

Returns the sine of n (in radians).

(math-sin 0)
0.0

math-cos

Returns the cosine of n (in radians).

(math-cos 0)
1.0

math-tan

Returns the tangent of n (in radians).

(math-tan 0)
0.0

math-atan2

Returns the angle in radians between the positive x-axis and the point (x, y).

(math-atan2 0 1)
0.0

Bitwise

bit-and

Returns the bitwise AND of the arguments.

(bit-and 12 10)
8

bit-or

Returns the bitwise OR of the arguments.

(bit-or 12 10)
14

bit-xor

Returns the bitwise XOR of the arguments.

(bit-xor 12 10)
6

bit-not

Returns the bitwise complement of n.

(bit-not 0)
-1

bit-shift-left

Returns n shifted left by count bits.

(bit-shift-left 1 4)
16
(bit-shift-left 1 0)
1
(bit-shift-left 1 63)
-9223372036854775808

bit-shift-right

Returns n arithmetically shifted right by count bits.

(bit-shift-right 16 2)
4
(bit-shift-right 1 0)
1
(bit-shift-right 1 63)
0

List

car

Returns the first element of a cons cell.

(car '(1 2 3))
1
(car (source-form '__sq))
'def

cdr

Returns the rest of a cons cell.

(cdr '(1 2 3))
'(2 3)

cons

Returns a new list with x prepended to coll.

(apply (fn [a b & rest] (vec (cons a (cons b rest)))) [1 2 3 4 5])
[1 2 3 4 5]
(cons 1 '(2 3))
'(1 2 3)
(get m (cons 0 (cons 1 (cons 2 nil))))
:found

list

Returns a list of the supplied arguments; () with no args.

(vec (list 0 1 2 3))
[0 1 2 3]
(list 1 2 'a)
'(1 2 a)
(list true false)
'(true false)

Collection

count

Returns the number of items in a collection.

(count bs)
2
(count bs)
2
(count bs)
4

nth

Returns the item at index n in a collection.

(nth (byte-array [9 8 7]) 1)
8
(nth (byte-array [9 8 7]) 99 :missing)
:missing
(meta (nth y 1))
xm

first

Returns the first item in a collection, or nil if empty.

(first (byte-array [9 8 7]))
9
(loop [a []
     b [1 2 3]]
(if (seq b)
  (recur (conj a (* 2 (first b)))
         (next b))
  a))
[2 4 6]
(loop [a ()
     b [1 2 3]]
(if (seq b)
  (recur (conj a (* 2 (first b)))
         (next b))
  a))
[6 4 2]

rest

Returns all but the first item in a collection.

(vec (rest (byte-array [9 8 7])))
[8 7]
(rest [10 20 30])
'(20 30)
(rest nil)
'()

vector

Returns a new vector containing the arguments.

(vector 1 2 3)
[1 2 3]
(#(vector %1 (vec %&)) 1 2 3)
[1 [2 3]]
(into {} (map #(vector % (* % %))) [1 2 3])
{1 1 2 4 3 9}

hash-map

Returns a new hash map with the given key-value pairs.

(hash-map :a 1 :b 2)
{:a 1 :b 2}

assoc

Returns a new map with the given key-value pairs added.

(meta (reduce #(assoc %1 %2 (inc %2)) x (range 1000)))
xm
(meta (assoc x 1 "one"))
xm
(keys (assoc {:z 1 :a 2 :m 3} :a 99))
'(:z :a :m)

dissoc

Returns a map with the given keys removed.

(meta (-> x (dissoc :foo) (dissoc :bar)))
xm
(dissoc {:a 1 :b 2 :c 3} :b)
{:a 1 :c 3}
(dissoc {:a 1 :b 2 :c 3} :a :c)
{:b 2}

get

Returns the value mapped to key in a collection, or not-found.

(get result :mino/message)
"boom"
(get data :n)
42
(get data :tag)
:test

conj

Returns a new collection with items added.

(loop [a []
     b [1 2 3]]
(if (seq b)
  (recur (conj a (* 2 (first b)))
         (next b))
  a))
[2 4 6]
(loop [a ()
     b [1 2 3]]
(if (seq b)
  (recur (conj a (* 2 (first b)))
         (next b))
  a))
[6 4 2]
(meta (reduce #(conj %1 %2) x (range 1000)))
xm

update

Updates the value at key k in map m by applying f to the old value and any args.

(update {:a [1]} :a conj 2)
{:a [1 2]}
(update [0] 0 inc)
[1]
(update {:a 1} :b identity)
{:a 1 :b nil}

keys

Returns a sequence of the keys in a map.

(keys {:z 1 :a 2 :m 3 :b 4})
'(:z :a :m :b)
(keys (assoc {:z 1 :a 2 :m 3} :a 99))
'(:z :a :m)
(keys (assoc {:z 1 :a 2} :b 3 :c 4))
'(:z :a :b :c)

vals

Returns a sequence of the values in a map.

(vals {:a 1 :b 2})
'(1 2)
(set (vals entries))
#{1 3}
(vals [[:a 1] [:b 2]])
'(1 2)

hash

Returns the hash code of the value.

(hash (byte-array [1 2 3]))
(hash (byte-array [1 2 3]))
(hash large2)
(hash flat)
(hash (dissoc m :z))
(hash m)

Sets

hash-set

Returns a new hash set containing the arguments.

(hash-set 1 2 3)
#{1 2 3}

set?

Returns true if x is a set (including sorted-set).

contains?

Returns true if the collection contains the key.

disj

Returns a set with the given keys removed.

(meta (-> x (disj 1) (disj 2) (disj 3)))
xm
(disj #{1 2 3} 2)
#{1 3}
(disj #{1 2 3 4} 2 4)
#{1 3}

Atoms

atom

Creates an atom with the given initial value.

(deref (atom 42))
42
@(atom 42)
42
(type (atom 1))
:atom

deref

Returns the current value of a reference (atom, delay, etc.).

(deref p 50 :timeout)
:timeout
(deref p 500 :timeout)
:ok
(deref p 0 :timeout)
:delivered

reset!

Sets the value of an atom to newval and returns newval.

(try (throw "x")
(catch e "caught")
(finally (reset! a 1)))
"caught"
(try
(try (throw "x") (finally (reset! a 1)))
(catch e "got-it"))
"got-it"
(reset! a 42)
42

swap!

Atomically applies f to the current value of the atom and any additional args.

(let [a (atom 0)]
(dotimes [n 3] (swap! a inc))
@a)
3
(let [a (atom [])]
(dotimes [n 3] (swap! a conj n))
@a)
[0 1 2]
(let [a (atom [])]
(dotimes [n 0] (swap! a conj n))
@a)
[]

atom?

Returns true if x is an atom.

(atom? 42)
false
(atom? [1 2 3])
false
(atom? nil)
false

Sequences

map

Returns a lazy sequence of applying f to each item in coll. When called with multiple collections, maps f across them in parallel. When called with no collection, returns a transducer.

(map inc (byte-array [1 2 3]))
[2 3 4]
(map (fn [s] (s 0)) '(inc dec zero?))
'(nil nil nil)
(sequence (map inc) (range 10))
(range 1 11)

filter

Returns a lazy sequence of items in coll for which pred returns truthy. When called with no collection, returns a transducer.

(filter even? (byte-array [1 2 3 4 5]))
[2 4]
(eduction (map inc) (filter even?) (map str) (range 5))
["2" "4"]
(some->> [1 2 3] (map inc) (filter even?))
'(2 4)

reduce

Reduces coll using f. With 2 args, uses the first element as init. With 3 args, uses init explicitly. Consults CollReduce: a user type or :default override on coll-reduce takes precedence over the built-in seq-driven reduction.

(reduce + (byte-array [1 2 3 4]))
10
(reduce * 1 (byte-array [1 2 3 4]))
24
(reduce + (byte-array 0))
0

take

Returns a lazy sequence of the first n items in coll. When called with no collection, returns a transducer.

(take 4 (iterate #(if (= % :foo) 42 :foo) :foo))
'(:foo 42 :foo 42)
(take 10 (iterate #(quot % 2) 256))
'(256 128 64 32 16 8 4 2 1 0)
(into [] (take 3) (next (iterate inc 0)))
[1 2 3]

drop

Returns a lazy sequence of all but the first n items in coll. When called with no collection, returns a transducer.

(pr-str (drop 0 [1 2 3 4]))
"(1 2 3 4)"
(pr-str (drop -1 [1 2 3 4]))
"(1 2 3 4)"
(pr-str (drop 2 [1 2 3 4]))
"(3 4)"

range

Returns a lazy sequence of nums from start (inclusive) to end (exclusive), by step. With no args, returns an infinite sequence from 0.

(mapv (fn [f] (f)) (mapv outer (range 10)))
[0 1 2 3 4 5 6 7 8 9]
(vec (range 4))
[0 1 2 3]
(meta (reduce #(assoc %1 %2 (inc %2)) x (range 1000)))
xm

repeat

Returns a lazy sequence of xs. With two args, returns n repetitions of x. Per Clojure, n is truncated toward zero before counting (so 3.14 and 3.99 both yield three repetitions). Booleans coerce as if via `(if n 1 0)` to mirror the JVM behavior on non-:clj dialects.

(drop 1 (repeat 2 :a))
'(:a)
(drop 2 (repeat 2 :a))
()
(drop 3 (repeat 2 :a))
()

concat

Returns a lazy sequence of the concatenation of the given collections.

(into [] (concat [1 2] "ab"))
[1 2 \a \b]
(concat [1 2] [3 4])
'(1 2 3 4)
(concat [1] [2] [3])
'(1 2 3)

into

Adds all items from from into to. With a transducer, transforms items first.

(into [] (byte-array [10 20 30]))
[10 20 30]
(into #{} (byte-array [1 2 3 1 2]))
#{1 2 3}
(meta (into x y))
xm

apply

Applies f to the arguments, with the last argument spread as a sequence.

(apply (fn [x y] [x y]) [1 2])
[1 2]
(apply (fn [a b & rest] (vec (cons a (cons b rest)))) [1 2 3 4 5])
[1 2 3 4 5]
(apply mapv vector [[:a :b :c] [:d :e :f] [:g :h :i]])
[[:a :d :g] [:b :e :h] [:c :f :i]]

reverse

Returns a sequence of the items in coll in reverse order.

(reverse (list 1 2 3))
'(3 2 1)
(reverse [1 2 3])
'(3 2 1)
(reverse nil)
'()

sort

Returns a sorted sequence of the items in coll.

(cond->> [4 3 2 1] true (sort <))
'(1 2 3 4)
(sort [3 1 4 1 5])
'(1 1 3 4 5)
(sort ["c" "a" "b"])
'("a" "b" "c")

Predicates

cons?

Returns true if x is a list (cons cell).

nil?

Returns true if x is nil.

(try (throw nil) (catch e (nil? (ex-data e))))
true

string?

Returns true if x is a string.

number?

Returns true if x is a number (int or float).

(postwalk (fn [x] (if (number? x) (inc x) x)) '(1 (2 3)))
'(2 (3 4))

keyword?

Returns true if x is a keyword.

symbol?

Returns true if x is a symbol.

vector?

Returns true if x is a vector.

map?

Returns true if x is a map (including sorted-map).

set?

Returns true if x is a set (including sorted-set).

fn?

Returns true if x is callable as a function (fn or prim).

empty?

Returns true if coll has no items.

seq?

Returns true if x is a cons cell or lazy-seq.

Utility

not

Returns true if x is logical false, false otherwise.

(not true)
false
(not false)
true
(not nil)
true

not=

Returns true if the arguments are not equal.

identity

Returns its argument.

(identity 42)
42

some

Returns the first truthy value of (pred x) for any x in coll, else nil.

(some pos? [1])
true
(some pos? [1 2])
true
(some pos? [-1])
nil

every?

Returns true if (pred x) is truthy for every x in coll.

(every? pos? [1])
true
(every? pos? [1 2])
true
(every? pos? [1 2 3 4 5])
true

rand

Returns a random float between 0 inclusive and 1 exclusive, or between 0 and n.

eval

Evaluates the given form.

(with-in-str "(+ 10 20)" (eval (read)))
30
(eval '(+ 1 2))
3
(eval (read-string "(* 3 4)"))
12

Reflection

type

Returns a keyword indicating the type of the value.

(type (+' max-int 1))
:bigint
(type (*' max-int 2))
:bigint
(type (+ 1 2))
:int

name

Returns the name string of a symbol, keyword, or string.

(name :/)
"/"
(name      'abc/def)
"def"
(name      'abc)
"abc"

symbol

Returns a symbol with the given name.

(str (symbol "Foo."))
"Foo."
(symbol "abc" "def")
'abc/def
(symbol "abc.def" "ghi")
'abc.def/ghi

keyword

Returns a keyword with the given name.

(keyword "abc" "def")
:abc/def
(keyword 'abc/def)
:abc/def
(keyword "abc.def" "ghi")
:abc.def/ghi

Strings

str

Returns the string representation of the arguments concatenated.

(str \A)
"A"
(str \a \b \c)
"abc"
(str \space)
" "

pr-str

Returns a readable string representation of the arguments.

(pr-str (byte-array [65 66 67]))
"#bytes \"414243\""
(pr-str (byte-array 0))
"#bytes \"\""
(pr-str (byte-array [255]))
"#bytes \"ff\""

format

Returns a formatted string using a format specifier and arguments.

(format "%d" 42)
"42"
(format "%s" "hello")
"hello"
(format "%%")
"%"

subs

Returns a substring from start (inclusive) to end (exclusive).

(subs (str (random-uuid)) 14 15)
"4"
(subs "hello" 1 3)
"el"
(subs "hello" 2)
"llo"

char-at

Returns the character at the given index as a string.

(char-at "hello" 0)
"h"
(char-at "hello" 4)
"o"

read-string

Reads one form from the string.

(read-string "\\A")
\A
(read-string "\\space")
\space
(read-string "\\newline")
\newline

Regex

re-find

Find the first match. (re-find pattern text) returns a string (no groups) or [whole g1 g2 ...] (groups). (re-find m) advances a matcher. Capability: :regex

(re-find #"[0-9]+" "abc123def")
"123"
(re-find #"hel+" "hello")
"hell"
(re-find (re-pattern "abc") "xabcy")
"abc"

re-matches

Like re-find but anchored to the whole string. Returns a string (no groups) or [whole g1 g2 ...] (groups), or nil. Capability: :regex

(re-matches "(.+)/(.+)" "a/b")
["a/b" "a" "b"]
(re-matches "\\d+" "12345")
"12345"
(re-matches "\\d+" "123abc")
nil

Type coercion

int

Coerces x to an int (32-bit integer). Throws on out-of-range values, NaN, or infinity. Returns the value as a MINO_INT (mino has only one integer tier); only the contract narrows.

(int 3.7)
3
(int 5)
5
(int \space)
32

float

Coerces x to a 32-bit float (returns a MINO_FLOAT32). Throws on out-of-float32-range, +/-Infinity. NaN passes through. Underflow rounds toward zero.

(float 5.0)
(float 5)
(double (float 5))
5.0

Exceptions

throw

Throws an exception with the given value.

(when false (throw (ex-info "boom" {})))
nil
(when-not true (throw (ex-info "boom" {})))
nil
(if-let [a false] (throw (ex-info "boom" {})))
nil

last-error

Returns the last error as a diagnostic map, or nil.

error?

Returns true if the value is a diagnostic map.

Modules

require

Loads and evaluates a mino source file.

(eval (read-string
"(do (require '[clojure [set :refer [union]]]) (union #{1 2 3} #{2 3 4}))"))
#{1 2 3 4}
(eval (read-string "(do (ns foo) (def x 1) (ns bar) (def x 2) (in-ns 'baz) (def x 3) (require 'foo 'bar) [foo/x bar/x x])"))
[1 2 3]
(eval (read-string "(do (ns foo) (def x 1) (ns bar) (def x 2) (in-ns 'baz) (def x 3) (require (symbol \"foo\") (symbol \"bar\")) [foo/x bar/x x])"))
[1 2 3]

Macros

macroexpand

Repeatedly expands a macro form until it is no longer a macro call.

(macroexpand '(do-template [x y] (+ y x) 2 4 3 5))
'(do (+ 4 2) (+ 5 3))
(eval (read-string "(do (eval (macroexpand '(ns foo (:require [clojure.string :as str])))) `str/x)"))
'clojure.string/x

macroexpand-1

Expands a macro form once.

gensym

Returns a new symbol with a unique name.

Other

*1

*2

*3

*agent*

*assert*

Controls assertion compilation. When false, `assert` is a no-op. Defaults to true.

*command-line-args*

*compile-files*

*compile-path*

*data-readers*

*default-data-reader-fn*

*e

*err*

*file*

*flush-on-newline*

When true (the default), the I/O sink behind `*out*` is flushed automatically after any write that contains a newline. When false, the sink stays buffered so consecutive writes coalesce.

*in*

*math-context*

Precision/rounding-mode for bigdec division. nil means exact-or- throw (mirrors java.math.BigDecimal.divide without MathContext). When set, the value is a map of {:precision N :rounding-mode K} where N is a positive integer and K is one of: :half-up (default), :down, :up, :floor, :ceiling, :half-down, :half-even, :unnecessary. :unnecessary throws when rounding would change the value (mirrors JVM's ArithmeticException). Resolved by mino_bigdec_div on each call.

*out*

*print-dup*

When true, the printer emits forms a reader can reconstruct exactly. mino's built-in record / collection / scalar prints are already reader-roundtrip-compatible, so the flag is currently an information channel for user-installed print-method implementations that branch on dup vs. non-dup output. Default false.

*print-length*

Maximum number of items printed in a single collection (vector, list, map, set, chunk, chunked-cons). nil means no limit (the default). The remainder is replaced with `...`. Resolved once per top-level pr / prn / print / println / pr-str call; nested collections share the same limit.

*print-level*

Maximum nesting depth printed. A collection found at depth >= this limit is replaced with `#`. nil means no limit (the default). Resolved once per top-level pr / print call.

*print-meta*

When true, every value carrying non-nil metadata is printed with its meta map prefixed as `^{...} `. When false (the default), meta is silent. Resolved once per top-level pr / print call.

*print-namespace-maps*

When true, a map whose keys are keywords (or symbols) sharing a common non-empty namespace is printed as `#:ns{:k1 v1, :k2 v2}` instead of `{:ns/k1 v1, :ns/k2 v2}`. Default false.

*print-readably*

When true (the default), strings are emitted with their quote characters and characters with their escape form so the printed output round-trips through the reader. When false, strings and characters print their underlying bytes — pr/prn behave like print/println. Resolved once per top-level pr / print call.

*source-path*

*unchecked-math*

*warn-on-reflection*

-empty-queue

Internal: return an empty PersistentQueue. Public surface is clojure.lang.PersistentQueue/EMPTY (a bound var) plus conj.

-lock-first

-lock-next

-thread-bound?

(-thread-bound? var) — true iff the var has a thread-local binding on the current dyn-stack. Clojure-level thread-bound? wraps this and is variadic.

-var-root-bound?

Return true if the var has a root binding. Internal helper backing the variadic Clojure-level bound?.

==

Returns true if nums are numerically equal, treating ints and floats uniformly.

Boolean/FALSE

Boolean/TRUE

Boolean/parseBoolean

Parses "true" (case-insensitive) to true; everything else to false.

Byte/MAX_VALUE

Byte/MIN_VALUE

Character/toString

JVM Character.toString; routes to mino's str.

(Character/toString \a)
"a"

CollReduce

CollReduce--coll-reduce

Datafiable

Datafiable--datafy

Double/MAX_VALUE

Double/MIN_VALUE

Double/NEGATIVE_INFINITY

Double/NaN

Double/POSITIVE_INFINITY

Double/isInfinite

True when the argument is +inf or -inf.

Double/isNaN

True when the argument is NaN.

Double/parseDouble

Parses a floating-point string. JVM Double static.

(Double/parseDouble "3.14")
3.14

Float/MAX_VALUE

Float/MIN_VALUE

Float/NEGATIVE_INFINITY

Float/NaN

Float/POSITIVE_INFINITY

Float/parseFloat

Alias for Double/parseDouble; mino has one float tier.

IKVReduce

IKVReduce--kv-reduce

Integer/MAX_VALUE

Integer/MIN_VALUE

Integer/parseInt

Alias for Long/parseLong; mino has one integer tier.

(Integer/parseInt "7")
7

Long/MAX_VALUE

Long/MIN_VALUE

Long/parseLong

Parses an integer string. JVM Long static.

(Long/parseLong "42")
42
(Long/parseLong "FF" 16)
255

Math/E

Math/PI

Math/abs

Absolute value (preserves int/double type).

(Math/abs -1.0)
1.0
(Math/abs -5)
5

Math/atan

Arctangent.

Math/atan2

Two-argument arctangent.

Math/ceil

Ceiling (rounds toward positive infinity).

(Math/ceil  2.3)
3.0

Math/cos

Cosine (radians).

Math/exp

e^x.

Math/floor

Floor (rounds toward negative infinity).

(Math/floor 2.7)
2.0

Math/log

Natural log.

Math/log10

Base-10 log.

Math/max

Numeric maximum of two values.

(Math/max 1 2)
2

Math/min

Numeric minimum of two values.

(Math/min 1 2)
1

Math/pow

Exponentiation.

(Math/pow 2 3)
8.0

Math/round

Round to nearest long.

(Math/round 2.7)
3

Math/sin

Sine (radians).

(Math/sin 0)
0.0

Math/sqrt

Square root.

(Math/sqrt 16)
4.0

Math/tan

Tangent (radians).

NaN?

Returns true if x is NaN.

Navigable

Navigable--nav

Short/MAX_VALUE

Short/MIN_VALUE

String/valueOf

JVM String.valueOf; routes to mino's str.

(String/valueOf 42)
"42"
(String/valueOf "abc")
"abc"

System/currentTimeMillis

Epoch millis from the host clock.

System/exit

Exits the host process with the given status code.

System/getProperty

JVM system-properties lookup. mino has no JVM properties table; throws :mino/unsupported.

System/getenv

Reads an environment variable from the host process.

System/nanoTime

Monotonic nanosecond counter from the host clock.

Thread/sleep

Suspends the current thread for the given number of milliseconds.

(Thread/sleep 1)
nil

abs

Returns the absolute value of x. Matches JVM Math/abs 2's-complement semantics: (abs Long/MIN_VALUE) returns Long/MIN_VALUE rather than overflowing, since the true absolute value is unrepresentable in a signed 64-bit int.

(abs -5)
5
(abs -1)
1
(abs 1)
1

add-load-path!

Appends a directory to the runtime's extra-load-paths list (consulted by `require` after project paths). Returns nil; idempotent.

add-tap

Registers f as a tap target. Each call to tap> invokes every registered tap with the tapped value. Returns nil.

add-watch

Adds a watch function to an atom, called on state changes.

(add-watch a :w (fn [k r o n] nil))
a

agent

Creates an asynchronous agent holding the given initial state. Mutate via send / send-off; read via @agent. The action runs on a per-state worker thread; await blocks until queued actions complete. Capability: :agent

agent-error

Returns the exception captured by the agent's most recent failed action or watch, or nil if the agent is in a clean state. Capability: :agent

agent?

Returns true if x is an agent. Capability: :agent

aget

Reads slot `index` from a host array or a bytes value. On a bytes value, returns the byte at that index as an unsigned int (0..255).

(aget bs 0)
0x12
(aget bs 1)
0x34
(aget bs 0)
0x12

alength

Returns the slot count of a host array or the byte length of a bytes value.

(alength b)
5

alias

Add an alias to a namespace.

(eval (read-string "(do (alias (symbol \"c\") (symbol \"clojure.core\")) (c/and true 1))"))
1
(eval (read-string "(do (alias 'set1 'clojure.set) (alias 'set2 'clojure.set) (set2/difference (set1/union #{1 2 3} #{4 5 6}) #{4 5 6}))"))
#{1 3 2}

all-ns

Return a vector of all known namespace symbols.

all-some?

alloc-profile-dump!

Dump the top-N allocation call sites to stderr. Defaults to 30; pass 0 for all.

alloc-profile-enabled?

Returns true if this binary was built with -DMINO_ALLOC_PROFILE=1.

alloc-profile-reset!

Zero the per-callsite allocation counters. No-op in non-profile builds.

alter

Sets ref to (apply f current-value args). Must be in dosync. Returns the new value. Capability: :stm

alter-meta!

Atomically applies f to the metadata of a reference.

alter-var-root

Apply a function to a var's root and store the result.

ancestors

Returns all ancestors of tag in the hierarchy.

(ancestors h :square)
#{:shape}
(ancestors h :square)
#{:rect :shape}
(ancestors h :d)
#{:a :b :c}

any?

Returns true for any argument.

aset

Mutates the host array at index, storing val. Returns val. The host-array tier is the only path that exposes in-place mutation outside MINO_ATOM / MINO_VOLATILE. Throws :mino/state on a MINO_BYTES value -- the immutable bytes tier rejects in-place writes.

assoc!

Associates key with val in a transient map or vector.

assoc-in

Associates a value in a nested associative structure at the given key path.

(assoc-in {} [:a :b] 42)
{:a {:b 42}}
(assoc-in {:a {:b 1}} [:a :b] 2)
{:a {:b 2}}

associative?

Returns true if x supports assoc (maps and vectors).

async-sched-enqueue*

Enqueue a callback on the async scheduler run queue. Capability: :async

async-schedule-timer*

Schedule a callback to fire after ms milliseconds. Capability: :async

await

Blocks the calling thread until every named agent's queued actions have finished. Throws MST002 if called from inside an agent action body (would self-deadlock). Capability: :agent

await-for

Like await with a millisecond timeout. Returns true if every named agent reached zero in-flight actions before the deadline, false on timeout. Capability: :agent

bigdec

Coerces a value to an arbitrary-precision decimal. Capability: :bignum

bigint

Coerces a value to an arbitrary-precision integer. Accepts int, bigint, float (truncated toward zero), or a base-10 string. Capability: :bignum

(bigint 1.7)
1N
(bigint -1.7)
-1N
(bigint 1)
1N

bigint?

Returns true if x is an arbitrary-precision integer. Capability: :bignum

biginteger

Alias of bigint. Coerces a value to an arbitrary-precision integer. Capability: :bignum

(biginteger 7)
(bigint 7)

bit-and-not

Returns the bitwise AND of x and the complement of y.

(bit-and-not 7 1)
6

bit-clear

Returns x with bit n cleared.

(bit-clear 15 1)
13
(bit-clear 13 1)
13
(bit-clear 8 3)
0

bit-flip

Returns x with bit n flipped.

(bit-flip 15 1)
13
(bit-flip 13 1)
15
(bit-flip 8 3)
0

bit-set

Returns x with bit n set.

(bit-set 15 1)
15
(bit-set 13 1)
15
(bit-set 0 3)
8

bit-test

Returns true if bit n of x is set.

bits

Pack a sequence of [value & options] segments into an immutable MINO_BYTES value. Options: :size (bits), :type (:int/:uint/:float/:bytes), :endian (:big/:little), :signed? (true/false). Bit-aligned totals leave a 1..7 bit_tail; the result satisfies bitstring? but not necessarily bytes?.

bits-get

Read a bit field out of a bytes value. Required: :offset and :size. Optional: :type (:int/:uint/:float/:bytes), :endian, :signed?. For :type :bytes returns a MINO_BYTES slice; for :float returns a double; otherwise returns an integer.

(bits-get bs :offset 0 :size 16)
0x1234
(bits-get bs :offset 0 :size 16 :endian :little)
0x1234
(bits-get bs :offset 0 :size 8)
0xff

bits-let-seg-size

Compute the static bit count of one segment from its option map. Returns :rest when the segment has :type :bytes without :size, otherwise an integer. Throws on a malformed segment.

bitstring?

Returns true if x is any mino bytes value -- byte-aligned or bit-aligned. bytes? is the byte-aligned subset.

boolean

Coerces x to a boolean value.

(boolean 1)
true
(boolean nil)
false
(boolean (:splicing? v2))
(boolean (:splicing? v1))

boolean-array

Creates a host-style boolean array. Fills with false on size; copies elements from a collection.

boolean?

Returns true if x is true or false.

bound-fn*

Returns a function which installs the same bindings in effect as in the thread at the time bound-fn* was called and then invokes f.

bound?

Returns true if all of the vars provided as arguments have any bindings — either a root binding or a thread-local binding.

bounded-count

Returns the count of coll, but stops counting at n.

(bounded-count 10 [1 2 3 4 5])
5
(bounded-count 10 (range))
10
(bounded-count 10 (take 3 (range)))
3

butlast

Returns a seq of all but the last item in coll.

(butlast [1 2 3])
'(1 2)
(butlast [1])
nil

byte

Coerces x to a byte (8-bit integer). Throws on out-of-range values, NaN, or infinity. Returns the value as a long since mino has only one integer tier.

byte-array

Creates a host-style byte array. Zero-fills on size argument; copies elements from a collection.

(byte-array [1 2 3])
(byte-array [1 2 3])
(hash (byte-array [1 2 3]))
(hash (byte-array [1 2 3]))
(seq (byte-array [65 66 67]))
[65 66 67]

bytes?

Returns true if x is a byte-aligned mino bytes value (the immutable binary-data type returned by byte-array).

cat

A transducer that concatenates the contents of each input.

chan-buf-add

Direct buffer push: (chan-buf-add ch val). Used by xform rf. Capability: :async

chan-buf-count

Number of buffered values. Capability: :async

chan-buf-full?

True if buffer is full (or unbuffered/promise-set). Capability: :async

chan-close

Close channel: (chan-close ch). Capability: :async

chan-closed?

True if channel is closed. Capability: :async

chan-flush-buf-to-takers

Wake every parked taker with a buffered value handoff. Capability: :async

chan-get-ex-handler

Read installed ex-handler, or nil if none. Capability: :async

chan-get-xform

Read installed transducer rf, or nil if none. Capability: :async

chan-has-pending-putter?

True if any non-committed putter is parked. Capability: :async

chan-has-pending-taker?

True if any non-committed taker is parked. Capability: :async

chan-instance?

True if x is a channel (MINO_CHAN tag). Public chan? lives in clojure.core.async to avoid shadowing on :refer :all. Capability: :async

chan-new

Construct a channel: (chan-new buf-kind buf-cap xform ex-handler). Capability: :async

chan-offer

Non-blocking put: (chan-offer ch val). Returns true/false. Capability: :async

chan-poll

Non-blocking take: (chan-poll ch). Returns value or nil. Capability: :async

chan-put

Async put: (chan-put ch val cb-or-nil). Capability: :async

chan-put-alts

alts-flavoured put: (chan-put-alts ch val cb flag). Capability: :async

chan-set-xform

Install transducer rf: (chan-set-xform ch rf ex-handler). Capability: :async

chan-take

Async take: (chan-take ch cb-or-nil). Capability: :async

chan-take-alts

alts-flavoured take: (chan-take-alts ch cb flag). Capability: :async

char

Coerces x to a character: integer codepoint (0..0x10FFFF) becomes the Unicode scalar value, character is identity. Throws on out-of-range values, non-integer types.

(char 65)
\A
(char 97)
\a
(char 48)
\0

char-array

Creates a host-style char array. Nul-fills on size argument; copies elements from a collection.

char?

Returns true if x is a one-character string.

chunk

Seals chunk-buffer buf so no further appends are accepted, and returns the chunk.

chunk-append

Appends elem to chunk-buffer buf and returns buf. Throws if buf is full or already sealed.

chunk-buffer

Returns a fresh chunk-buffer of the given capacity. Append values with chunk-append, then seal with chunk.

chunk-cons

Returns a chunked seq prepending the given chunk to the seq more.

chunk-first

Returns the chunk at the head of a chunked seq.

chunk-next

Returns the rest of a chunked seq as a seq, or nil if empty.

chunk-rest

Returns the rest of a chunked seq after the head chunk, or () if none.

chunked-seq?

Returns true if x is a chunked seq.

clojure-version

coll-reduce

coll?

Returns true if x is a collection.

commute

Sets ref to (apply f current-value args). Like alter but does not participate in read-set validation -- two transactions commuting on the same ref do not conflict. The fn is replayed against the latest committed value at commit time. Must be in dosync. Capability: :stm

comp

Returns a function that is the composition of the given functions.

(transduce (comp (take 1) (take 1)) conj [:a])
[:a]
(transduce (comp (take 1) (take 1) (take 1)) conj [:a])
[:a]
(transduce (comp (take 1) (take 1) (take 1) (take 1)) conj [:a])
[:a]

comparator

Returns a comparator function from a two-arg predicate.

((comparator <) 1 2)
-1
((comparator <) 2 1)
1
((comparator <) 1 1)
0

compare-and-set!

Atomically sets the atom to new-val if its current value equals expected. Returns true on swap, false otherwise.

complement

Returns a function that returns the logical opposite of f.

((complement nil?) 42)
true
((complement nil?) nil)
false

completing

Returns a reducing function with a completion step.

conj!

Conjoins val onto a transient vector, map, or set.

constantly

Returns a function that always returns x.

((constantly 42) :a :b)
42

counted?

Returns true if (count x) is a constant-time operation. Per Clojure this is the Counted protocol -- vectors, maps, sets, and sorted variants. Strings are not Counted on the JVM (their count walks java.lang.CharSequence).

create-multimethod

create-ns

Ensure the namespace exists and return its symbol.

cycle

Returns a lazy infinite sequence of repetitions of the items in coll.

(take 5 (cycle [1 2]))
'(1 2 1 2 1)

datafy

(datafy 42)
42
(datafy "hello")
"hello"
(datafy [1 2 3])
[1 2 3]

decimal?

Returns true if x is an arbitrary-precision decimal. Capability: :bignum

dedupe

Returns a lazy sequence removing consecutive duplicates. When called with no collection, returns a transducer.

(into [] (dedupe [1 1 2 3 3 3 4 4 1]))
[1 2 3 4 1]
(transduce (dedupe) conj [] [1 1 2 2 3 1])
[1 2 3 1]

defrecord*

Runtime constructor for record types. Takes ns name fields-vector and returns the MINO_TYPE value, idempotent across calls.

defrecord-bind-fields-in-method

Wraps a protocol method body so the record's field names are visible as locals bound to (get this :field). Matches Clojure defrecord's contract: in (defrecord R [a b] IFoo (bar [this] a)), `a` resolves to (:a this) inside the method body. Returns the method form unchanged if it doesn't look like a method spec (`(symbol [vec] body...)`), so protocol-name separators inside specs pass through. Bypasses wrapping when there are no fields. Skips binding for fields whose name shadows the method's first param (i.e. the dispatching `this` slot). Order of bindings inside the let preserves the field declaration order so later fields can reference earlier ones if a user shadows intentionally.

delay?

Returns true if x is a delay.

deliver

Deliver a value to a promise. Returns the promise on success, nil if already realized.

denominator

Returns the denominator of a rational number. Capability: :bignum

(denominator 1/2)
2
(denominator -3/4)
4
(denominator 1/3)
3

deref-delay

Forces evaluation of a delay and returns its value.

derive

Establishes a parent/child relationship between child and parent in a hierarchy.

descendants

Returns all descendants of tag in the hierarchy.

(descendants h :shape)
#{:square}
(descendants h :shape)
#{:square :rect}
(descendants h :rect)
#{:square}

destructure

Takes a binding-pairs vector [lhs1 rhs1 lhs2 rhs2 ...] and returns a flat vector of [name init ...] suitable as a let binding form.

directory?

Returns true if the path is a directory. Capability: :fs

disj!

Removes key from a transient set.

dissoc!

Removes key from a transient map.

distinct

Returns a lazy sequence of the distinct items in coll. When called with no collection, returns a transducer.

(sequence (distinct) [])
[]
(sequence (distinct) (range 10))
(range 10)
(sequence (distinct) (repeat 10 0))
[0]

distinct?

Returns true if no two of the arguments are equal.

doall

Forces realization of a lazy sequence. Returns coll.

(count (doall (map inc [1 2 3])))
3

dorun

Forces realization of a lazy sequence. Returns nil.

dosync*

Runs a zero-arg thunk inside an STM transaction. The `dosync` macro expands to (dosync* (fn [] body...)). Capability: :stm

double

Coerces x to a 64-bit double (returns a MINO_FLOAT). Identity on existing doubles.

(double (/ 10 4))
2.5
(double (float 5))
5.0
(letfn [(double [x] (* 2 x))]
(double 5))
10

double-array

Creates a host-style double array. Zero-fills (0.0) on size; copies elements from a collection.

double?

Returns true if x is a 64-bit double (mino's `:float` tier). Distinct from `float?`, which also returns true for the 32-bit `:float32` tier produced by `(float x)`. Matches JVM Clojure where `double?` is `(instance? Double x)`.

drain!

Drain the async run queue once. Capability: :async

drain-loop!

Drain until done-thunk returns truthy or no progress. Capability: :async

drop-last

Returns a lazy sequence of all but the last n items in coll.

(into [] (drop-last [1 2 3 4]))
[1 2 3]
(into [] (drop-last 2 [1 2 3 4]))
[1 2]

drop-seq

Internal fast path for eager drop.

drop-while

Returns a lazy sequence of items from coll after pred returns falsy. When called with no collection, returns a transducer.

(drop-while (fn [x] (< x 3)) [1 2 3 4])
'(3 4)
(transduce (drop-while #(< % 3)) conj [] [1 2 3 4 5])
[3 4 5]

eduction

Returns a lazy sequence of applying the given transducers to coll.

(eduction (map inc) (range 5))
[1 2 3 4 5]
(eduction (map inc) (filter even?) (map str) (range 5))
["2" "4"]
(eduction cat [[1 2 3 nil] [4 5 6 nil]])
'(1 2 3 nil 4 5 6 nil)

empty

Returns an empty collection of the same type.

(empty nil)
nil
(empty [])
[]
(empty [1 2])
[]

ensure

Reads ref and prevents any other transaction from changing it before this transaction commits. Must be in dosync. Returns the current in-tx value. Capability: :stm

ensure-reduced

Wraps x in reduced if it is not already reduced.

@(ensure-reduced 42)
42

error-handler

Returns the agent's current error-handler fn or nil. Capability: :agent

error-mode

Returns the agent's current error mode. Capability: :agent

even?

Returns true if x is an even integer.

(sequence (keep-indexed (fn [i v] (when (even? i) v)))
[:a :b :c :d :e])
[:a :c :e]
(into [] (keep (fn [x] (when (even? x) (* x 10)))
[1 2 3 4 5]))
[20 40]
(into [] (keep-indexed
(fn [i x] (when (even? i) x))
[:a :b :c :d :e]))
[:a :c :e]

every-pred

Returns a function that returns true when all preds are satisfied by all its arguments.

((every-pred even?))
true
((every-pred even?) 2)
true
((every-pred even?) 2 4)
true

ex-cause

Returns the cause attached to the given exception, or nil.

(ex-cause (ex-info "boom" {:cause :down}))
:down
(ex-cause e)
root
(ex-message (ex-cause e))
"root"

ex-data

Extract the data map from an exception. Handles diagnostic maps (from catch), ex-info maps, and plain thrown values.

(try (throw "oops") (catch e (ex-data e)))
"oops"
(try (throw {:type :err}) (catch e (:type (ex-data e))))
:err
(try (try (throw "inner")
     (catch e (throw e)))
(catch e (ex-data e)))
"inner"

ex-info

Create an exception map with a message and data map. The 3-arity form additionally attaches a cause; ex-cause walks the chain via metadata so the visible map structure stays the same as the 2-arity form.

(when false (throw (ex-info "boom" {})))
nil
(when-not true (throw (ex-info "boom" {})))
nil
(if-let [a false] (throw (ex-info "boom" {})))
nil

ex-message

Extract the message from an exception. Handles both diagnostic maps and ex-info maps.

(ex-message (ex-info "oops" {}))
"oops"
(ex-message e)
"outer"
(ex-message (ex-cause e))
"root"

false?

Returns true if x is the value false.

ffirst

Returns the first item of the first item in coll.

(ffirst '((1 2) (3 4)))
1

file-exists?

Returns true if the path exists (file or directory). Capability: :fs

file-mtime

Returns the file modification time in milliseconds, or nil. Capability: :fs

filterv

Returns a vector of items in coll for which pred returns logical true.

(filterv even? [1 2 3 4 5])
[2 4]

find

Returns the map entry for the key, or nil.

(find {:a 1 :b 2} :a)
[:a 1]
(find {:a 1} :z)
nil
(find p :x)
[:x 1]

find-best-method

find-keyword

Returns the keyword for the given string. In mino keywords are always interned, so this is equivalent to keyword for string input and nil for other input.

(find-keyword "a")
:a
(find-keyword "ns" "a")
:ns/a

find-ns

Return the namespace symbol if it exists, else nil.

(ns-name (find-ns 'clojure.set))
'clojure.set
(:doc (eval (read-string "(do (ns foo \"foobar\") (meta (find-ns 'foo)))")))
"foobar"

find-var

Return the var named by a qualified symbol, or nil.

(find-var (symbol (str (ns-name *ns*)) "fv-x"))
#'fv-x
(var-get (find-var (symbol (str (ns-name *ns*)) "interned-x")))
99

flatten

Returns a lazy sequence of the non-sequential items from a nested structure.

(into [] (flatten [[1 2] [3 [4 5]] 6]))
[1 2 3 4 5 6]
(into [] (flatten [1 2 3]))
[1 2 3]

float-array

Creates a host-style float array. Zero-fills (0.0) on size; copies elements from a collection.

float?

Returns true if x is a float.

flush

Flushes pending output on *out* and *err*. No-op for string-atom bindings.

(flush)
nil

fn-arity-with-prepost

fnext

Same as (first (next coll)).

(fnext [1 3 5])
3

fnil

Returns a function like f, but replaces nil arguments with the given defaults.

((fnil + 0) nil 5)
5
((fnil + 0) 3 4)
7

force

Forces evaluation of a delay. If x is not a delay, returns x.

frequencies

Returns a map from distinct items in coll to the number of times they appear.

(frequencies [1 2 1 3 2 1])
{1 3, 2 2, 3 1}

future-call

Spawn a worker thread to evaluate the given thunk; return a future.

future-cancel

Cancel a pending future. Returns true if the future was newly cancelled.

future-cancelled?

Return true if the future was cancelled.

future-deref

Block until the future is realized; return result, rethrow exception, or throw :mino/cancelled.

future-done?

Return true if the future has reached a terminal state (resolved/failed/cancelled).

future?

Return true if x is a future or promise.

get-method

Returns the method for dispatch-val, or nil.

get-thread-bindings

Returns a map of symbol->value for the active dynamic bindings, or nil if no binding frames are active.

get-validator

Returns the validator function of an atom, or nil.

(get-validator a)
pos?
(get-validator r)
number?
(get-validator r)
pos?

global-hierarchy

group-by

Returns a map of the items in coll grouped by the result of f.

(group-by even? [1 2 3 4])
{false [1 3], true [2 4]}

halt-when

Returns a transducer that halts reduction when pred is satisfied.

(transduce (halt-when even?) conj [1 3 5 4 7])
4
(transduce (halt-when even?
  (fn [r input] {:stopped input :so-far r}))
conj [1 3 5 4 7])
{:stopped 4 :so-far [1 3 5]}
(transduce (halt-when even?) conj [1 3 5])
[1 3 5]

hash-combine

Boost-style hash combiner: mixes seed and hash into a single 32-bit hash. Matches clojure.core/hash-combine bit-for-bit so user code that manually composes hashes via this helper sees the same result on mino as on JVM Clojure. seed ^= hash + 0x9e3779b9 + (seed << 6) + (seed >> 2) The operation is performed in unchecked 32-bit arithmetic; the result is truncated to the low 32 bits.

(hash-combine 0 (hash :a))
(hash-combine 0 (hash :a))
(hash-combine 0 0)
(hash-combine nil nil)
(hash-combine 0 (hash :a))
(hash-combine nil (hash :a))

hash-ordered-coll

Computes a sequence-position-aware hash for an ordered collection.

hash-unordered-coll

Computes a position-independent hash for an unordered collection.

(hash-unordered-coll #{3 2 1})
(hash-unordered-coll #{1 2 3})

hierarchy-version

host/call

Calls a method on a host handle. Capability: :host

(host/call c :get)
1
(host/call c :get)
5
(host/call c :get)
13

host/get

Returns the value of a field on a host handle. Capability: :host

(host/get c :value)
42
(try (host/get c :nope) (catch e e))
"member not found: :Counter/:nope"

host/new

Creates a new instance of a host-registered type. Capability: :host

(try (host/new :Nope) (catch e e))
"unknown type: :Nope"

host/static-call

Calls a static method on a host-registered type. Capability: :host

(host/static-call :Math :add 3 4)
7
(try (host/static-call :Math :nope) (catch e e))
"member not found: :Math/:nope"

ident?

Returns true if x is a symbol or keyword.

identical?

Returns true if the arguments are the same object.

ifn?

Returns true if x can be called as a function.

in-ns

Set the current namespace, creating it if necessary.

(eval (read-string "(do (in-ns 'cs-strict-foo) (ns-name *ns*))"))
'cs-strict-foo
(eval (read-string "(do (in-ns 'cs-strict-all-dst) (pubA))"))
:a
(eval (read-string "(do (in-ns 'cs-strict-all-dst) (pubB))"))
:b

in-transaction?

Returns true when called from inside a `dosync` body. Capability: :stm

indexed?

Returns true if x supports nth in constant time (vectors).

infinite?

Returns true if x is positive or negative infinity.

inst-ms

Returns epoch millis (since 1970-01-01T00:00:00Z) for an inst value as returned by clojure.instant/read-instant-date or the `#inst "..."` reader literal. Throws on a non-inst argument.

(inst-ms #inst "1970-01-01T00:00:00Z")
0
(inst-ms #inst "2000-01-01T00:00:00Z")
946684800000
(inst-ms #inst "2026-05-21T00:00:00Z")
1779321600000

inst-ms-count-leaps

inst-ms-days-from-1970

inst-ms-leap?

inst?

instance?

Returns true if x is an instance of t. For record types defined with defrecord, t is the type value and the test is type-pointer identity. For built-in types or ad-hoc :type-tagged values, t may be the keyword (type x) returns and the test is keyword equality.

int-array

Creates a host-style int array. Zero-fills on size argument; copies elements from a collection.

int?

Returns true if x is an integer.

integer?

Returns true if x is an integer (long or bigint).

intern

Intern a value into a namespace by name.

(do (require '[remote :refer [cake]])
(ns-unmap *ns* 'cake)
(def resolved (resolve 'cake))
(intern *ns* 'cake "bar")
[resolved cake])
[nil "bar"]

interpose

Returns a lazy sequence of the items in coll separated by sep. When called with no collection, returns a transducer.

(sequence (interpose :s) (range 0))
[]
(sequence (interpose :s) (range 1))
[0]
(sequence (interpose :s) (range 2))
[0 :s 1]

into-array

Converts a collection to an Object array.

io!-check

Internal: throws when called inside a transaction. The io! macro expands to (do (io!-check) body...) so the check runs before the body evaluates. Capability: :stm

isa?

Returns true if child is equal to or derives from parent.

iterate

Returns a lazy sequence of x, (f x), (f (f x)), and so on.

(take 4 (iterate #(if (= % :foo) 42 :foo) :foo))
'(:foo 42 :foo 42)
(take 10 (iterate #(quot % 2) 256))
'(256 128 64 32 16 8 4 2 1 0)
(first (next (next (iterate inc 0))))
2

iteration

Creates a seqable via repeated calls to step, a function of some continuation token 'k'. The first call to step is passed initk, returning 'ret'. If (somef ret) is true, (vf ret) is included in the iteration; else iteration terminates and vf/kf are not called. If (kf ret) is non-nil it is passed to the next step call; else iteration terminates. Used to consume APIs that return paginated or batched data. step - (possibly impure) fn of 'k' -> 'ret' :somef - fn of 'ret' -> truthy/falsy, default some? :vf - fn of 'ret' -> 'v', default identity :kf - fn of 'ret' -> 'next-k' or nil, default identity :initk - first value passed to step, default nil Step with non-initk is presumed unreproducible. The first step call is deferred until the result is realized.

java.util.List/of

JVM List.of static; routes to mino's list constructor.

(java.util.List/of 1 2 3)
'(1 2 3)

java.util.Map/of

JVM Map.of static; routes to mino's hash-map constructor.

(java.util.Map/of :a 1 :b 2)
{:a 1 :b 2}

java.util.Set/of

JVM Set.of static; routes to mino's hash-set constructor.

(java.util.Set/of 1 2 3)
#{1 2 3}

java.util.UUID/fromString

Parses a UUID from its canonical string form.

(java.util.UUID/fromString (str u))
u

java.util.UUID/randomUUID

Generates a random UUID v4.

juxt

Returns a function that returns a vector of applying each f to its args.

((juxt :a :b) {:a 1 :b 2})
[1 2]
((juxt fnext first) a0)
[2 1]
((juxt a1 b1) 3)
[5 6]

keep

Returns a lazy sequence of non-nil results of (f item). When called with no collection, returns a transducer.

(into [] (keep (fn [x] (when (even? x) (* x 10)))
[1 2 3 4 5]))
[20 40]
(transduce (keep #(when (even? %) (* % %))) conj [] [1 2 3 4 5])
[4 16]

keep-indexed

Returns a lazy sequence of non-nil results of (f index item). When called with no collection, returns a transducer.

(sequence (keep-indexed (fn [i v] (when (odd? i) v))) [])
[]
(into [] (keep-indexed (fn [i v] (when (odd? i) v)))
[2 5 3 4 6 7 9 8])
[5 4 7 8]
(sequence (keep-indexed (fn [i v] (when (even? i) v)))
[:a :b :c :d :e])
[:a :c :e]

key

Returns the key of a map entry. Throws on values that are not map entries (a literal 2-vector, for instance).

(key (first {:a 1}))
:a
(key (first {nil 1}))
nil
(key (first {:a nil}))
:a

kv-reduce

last

Returns the last item in coll.

(last (byte-array [9 8 7]))
7
(last [1 2 3])
3
(last [1])
1

lazy-filter

Internal fast path for lazy filter.

lazy-map-1

Internal fast path for single-collection lazy map.

lazy-take

Internal fast path for lazy take.

list*

Creates a new list containing the items prepended to the rest, the last of which will be treated as a sequence.

(r/fold + + (list* (range 1000)))
499500

list?

Returns true if x is a list (cons chain or the empty-list singleton). Excludes lazy-seq and chunked-cons; for the broader 'is a sequence' predicate, use seq?.

load-file

Reads and evaluates all forms in the file at the given path. Returns the value of the last form.

load-string

Reads and evaluates all forms in the given source string. Returns the value of the last form.

(load-string "(+ 1 1)")
2
(load-string "(def __ls_x 42) (* __ls_x 2)")
84
(load-string "(defn __ls_sq [x] (* x x)) (__ls_sq 5)")
25

loaded-libs

Return a vector of names that have been required.

long

Coerces x to a long (64-bit integer). Throws on out-of-range values, NaN, or infinity, including bigint and bigdec out of long range.

long-array

Creates a host-style long array. Zero-fills on size argument; copies elements from a collection.

make-hierarchy

Returns an empty hierarchy.

map-entry

Constructs a (k, v) map entry. Distinct from a 2-vector: key/val accept only map entries, not plain vectors. Equality with [k v] still compares element-wise.

map-entry?

Returns true if x is a map entry (mino represents entries as 2-vectors).

map-indexed

Returns a lazy sequence of (f index item) for each item in coll. When called with no collection, returns a transducer.

(sequence (map-indexed vector) [])
[]
(sequence (map-indexed vector) (range 1 5))
[[0 1] [1 2] [2 3] [3 4]]
(into [] (map-indexed vector [:a :b :c]))
[[0 :a] [1 :b] [2 :c]]

map-n

map1

mapcat

Returns the result of applying concat to the result of mapping f over coll. When called with no collection, returns a transducer.

(mapcat (fn [x] [x (* x 10)]) [1 2 3])
'(1 10 2 20 3 30)
(transduce (mapcat #(list % %)) conj [] [1 2 3])
[1 1 2 2 3 3]

mapv

Returns a vector of applying f to each item in one or more collections.

(mapv (fn [f] (f)) (mapv outer (range 10)))
[0 1 2 3 4 5 6 7 8 9]
(mapv (fn [f] (f)) @cls)
[0 1 2 3 4]
(mapv (fn [f] (f)) fs)
[0 1 2 3 4]

match-whole

matcher?

math-acos

Returns the arc-cosine of n; n in [-1, 1]; result in [0, PI].

math-asin

Returns the arc-sine of n; n in [-1, 1]; result in [-PI/2, PI/2].

math-atan

Returns the arc-tangent of n; result in [-PI/2, PI/2].

math-cbrt

Returns the cube root of n.

math-copy-sign

Returns a value with the magnitude of mag and the sign of sgn.

math-cosh

Returns the hyperbolic cosine of n.

math-expm1

Returns exp(n) - 1, accurate for small n.

math-hypot

Returns sqrt(a^2 + b^2) avoiding intermediate overflow.

math-ieee-remainder

Returns IEEE 754 remainder of a by b.

math-log10

Returns the base-10 logarithm of n.

math-log1p

Returns the natural logarithm of (1 + n), accurate for small n.

math-next-down

Returns the next representable double less than n (toward -Inf).

math-next-up

Returns the next representable double greater than n (toward +Inf).

math-pi

math-signum

Returns -1.0, 0.0, or 1.0 depending on the sign of n (preserves -0.0).

math-sinh

Returns the hyperbolic sine of n.

math-tanh

Returns the hyperbolic tangent of n.

math-to-degrees

Converts the angle n (in radians) to degrees.

math-to-radians

Converts the angle n (in degrees) to radians.

max

Returns the greatest of the given values.

(max 3 7)
7
(max 1 5 3)
5
(max -10 -5 -1)
-1

max-key

Returns the x for which (k x) is greatest.

(max-key count "ab" "a" "abc")
"abc"
(max-key :x {:x 3} {:x 1} {:x 2})
{:x 3}
(max-key identity 42)
42

memoize

Returns a memoized version of f that caches return values by arguments.

merge

Returns a map that is the merge of the maps. If a key occurs in more than one map, the mapping from the latter (left-to-right) will be the mapping in the result. Per Clojure, position-2+ args use `conj` semantics, so MapEntries / 2-element vectors are accepted.

(meta (merge x y))
xm
(meta (merge y x))
ym
(merge {:a 1} {:b 2} {:a 3})
{:a 3 :b 2}

merge-with

Returns the merge of the given maps, calling f to combine values at shared keys.

(meta (merge-with + x y))
xm
(meta (merge-with + y x))
ym
(merge-with + {:a 1 :b 2} {:a 3 :c 4})
{:a 4 :b 2 :c 4}

meta

Returns the metadata map of the given value, or nil.

(meta (:guh y))
xm
(meta (reduce #(assoc %1 %2 (inc %2)) x (range 1000)))
xm
(meta (-> x (dissoc :foo) (dissoc :bar)))
xm

methods

Returns the method table of multimethod mm.

(count (methods area-mm))
3
(count (methods mm-test))
2
(count (methods mm-test))
1

min

Returns the least of the given values.

(min 3 7)
3
(min 1 5 3)
1
(min -10 -5 -1)
-10

min-key

Returns the x for which (k x) is least.

(min-key count "ab" "a" "abc")
"a"
(min-key :x {:x 3} {:x 1} {:x 2})
{:x 1}
(min-key identity 42)
42

mino-capability

Return the install-group capability label for the named binding as a keyword, or nil when the binding is part of the always-installed core.

(mino-capability 'slurp)
:io
(mino-capability 'spit)
:io
(mino-capability 'exit)
:io

mino-installed?

Returns true if a named capability has been installed on this runtime. Argument is a keyword, symbol, or string; supported names include :floor :regex :bignum :multimethods :protocols :transducers :io :fs :proc :stm :agent :host :async. Used by core.clj sections to gate optional surface on the host's install picks.

mino-no-grant-msg

Build the :mino/unsupported message used when host threads are not granted in the current state.

mino-thread-count

Return the live host-thread count for this state.

mino-thread-limit

Return the host-granted thread limit for this state. 1 means single-threaded; >1 means the host has granted that many concurrent worker threads.

mix-collection-hash

Combines a hash-basis with the collection's count.

mkdir-p

Creates a directory and any missing parent directories. Capability: :fs

namespace

Returns the namespace string of a symbol or keyword, or nil.

(namespace 'abc/def)
"abc"
(namespace 'abc)
nil
(namespace :abc/def)
"abc"

nat-int?

Returns true if x is a non-negative integer (long tier).

nav

(nav [1 2 3] 0 99)
99
(nav {:a 1} :a :x)
:x

neg-int?

Returns true if x is a negative integer (long tier).

neg?

Returns true if x is less than zero.

next

Returns a seq of the items after the first. Returns nil if no more items.

(loop [a []
     b [1 2 3]]
(if (seq b)
  (recur (conj a (* 2 (first b)))
         (next b))
  a))
[2 4 6]
(loop [a ()
     b [1 2 3]]
(if (seq b)
  (recur (conj a (* 2 (first b)))
         (next b))
  a))
[6 4 2]
(first (next (next (iterate inc 0))))
2

nfirst

Same as (next (first coll)).

(nfirst [[1 2] [3 4]])
'(2)

nnext

Same as (next (next coll)).

(nnext [1 2 3])
'(3)
(nnext [1 2])
nil

not-any?

Returns true if (pred x) is falsy for every x in coll.

(not-any? pos? [1])
false
(not-any? pos? [1 2])
false
(not-any? pos? [1 2 3 4 5])
false

not-empty

Returns coll if it has items, nil otherwise.

(not-empty [1])
[1]
(not-empty [])
nil

not-every?

Returns true if (pred x) is falsy for at least one x in coll.

(not-every? pos? [1])
false
(not-every? pos? [1 2])
false
(not-every? pos? [1 2 3 4 5])
false

ns-aliases

Return the alias map of a namespace.

(ns-name (get (ns-aliases *ns*) 'e1))
'clojure.walk
(ns-name (get (ns-aliases *ns*) 'c))
'clojure.core
(ns-name (get (ns-aliases *ns*) 'c2))
'clojure.core

ns-interns

Return the interned bindings of a namespace as a map.

ns-map

Return all bindings visible in a namespace as a map.

(eval (read-string "(do (defn inc [x] :foo) ((get (ns-map *ns*) 'inc) 1))"))
:foo

ns-name

Return the symbol name of a namespace.

(eval (read-string "(do (in-ns 'cs-strict-foo) (ns-name *ns*))"))
'cs-strict-foo
(ns-name *ns*)
'iso.curr.a
(ns-name *ns*)
'iso.curr.b

ns-publics

Return the public bindings of a namespace as a map.

ns-refers

Return the refer'd bindings of a namespace as a map.

ns-resolve

Resolve a symbol to a var in the given namespace.

ns-unalias

Remove an alias from a namespace.

ns-unmap

Remove a binding from a namespace.

(eval (read-string "(do (ns-unmap *ns* 'Object) (def o1 (resolve 'Object)) (import '[java.lang Object]) (def o2 (resolve 'Object)) [(some? o1) (some? o2)])"))
[false true]
(do (require '[remote :refer [cake]])
(ns-unmap *ns* 'cake)
(def resolved (resolve 'cake))
(intern *ns* 'cake "bar")
[resolved cake])
[nil "bar"]
(eval (read-string "(do (ns-unmap *ns* 'String) `String)"))
'user/String

nthnext

Returns the result of calling next n times on coll.

(nthnext [1 2 3 4 5] 2)
'(3 4 5)
(nthnext [1 2] 3)
nil

nthrest

Returns the result of calling rest n times on coll.

(into [] (nthrest [1 2 3 4 5] 2))
[3 4 5]
(into [] (nthrest [1 2] 0))
[1 2]

num

Returns x if it is a number, nil if x is nil, otherwise throws. Nil pass-through matches the cross-dialect convention used by the `:default` arm of `clojure.core-test.num` (no-op on numeric inputs plus nil), where JVM Clojure's NPE-on-nil is platform-specific.

numerator

Returns the numerator of a rational number. Capability: :bignum

(numerator 1/2)
1
(numerator -3/4)
-3
(numerator 1/3)
1

object-array

Creates a host-style Object array. With a non-negative integer, returns an array of that length filled with nil. With a collection, returns an array of its elements. Distinct from vector: vector? / coll? / counted? / sequential? / associative? all return false on the result, matching JVM Java arrays.

odd?

Returns true if x is an odd integer.

(sequence (keep-indexed (fn [i v] (when (odd? i) v))) [])
[]
(into [] (keep-indexed (fn [i v] (when (odd? i) v)))
[2 5 3 4 6 7 9 8])
[5 4 7 8]
(into [] (for [x [1 2 3] :when (odd? x) y [2 4]] [x y]))
[[1 2] [1 4] [3 2] [3 4]]

parents

Returns the immediate parents of tag in the hierarchy.

(parents h :square)
#{:shape}
(parents h :square)
#{:rect}
(parents h :d)
#{:b :c}

parse-boolean

Parses 'true' or 'false' (case-sensitive) and returns the boolean. Returns nil for strings that don't match. Per Clojure's contract raises an error on non-string input (analogous to JVM's ClassCastException / NullPointerException).

parse-double

Parses a string into a double, or returns nil on failure.

parse-long

Parses a string into a long integer, or returns nil on failure.

parse-uuid

Parses s as a UUID; returns a UUID value or nil if s is not a valid canonical UUID string.

(parse-uuid "550e8400-e29b-41d4-a716-446655440000")
(parse-uuid "550E8400-E29B-41D4-A716-446655440000")

partial

Returns a function that applies f with the given arguments prepended.

((partial + 10) 5)
15

partition-all

Like partition, but includes a final partial group if items remain. The transducer arity emits each group as a vector (matching JVM Clojure's `(vec (.toArray buf))`); the seq arities emit lists per `partition`'s shape.

(into [] (partition-all 3 [1 2 3 4 5 6 7 8]))
['(1 2 3) '(4 5 6) '(7 8)]
(partition-all 2 [1 2 3])
'((1 2) (3))
(transduce (partition-all 2) conj [] [1 2 3 4 5])
['(1 2) '(3 4) '(5)]

partition-by

Splits coll into lazy sequences of consecutive items with the same (f item) value. When called with no collection, returns a transducer.

(transduce (comp (partition-by keyword?) (take 1)) conj [] [:a])
[[:a]]
(sequence (comp (partition-by keyword?) (take 1)) [:a])
[[:a]]
(transduce (partition-by odd?) conj [] [1 3 2 4 5])
[[1 3] [2 4] [5]]

partition-protocol-specs

partitionv

Like partition but returns a lazy seq of vectors instead of lists.

(vec (partitionv 2 [1 2 3 4]))
[[1 2] [3 4]]
(vec (partitionv 2 1 [1 2 3 4]))
[[1 2] [2 3] [3 4]]
(vec (partitionv 2 2 [:p :p] [1 2 3 4 5]))
[[1 2] [3 4] [5 :p]]

partitionv-all

Like partition-all but returns a lazy seq of vectors instead of lists.

(vec (partitionv-all 2 [1 2 3 4 5]))
[[1 2] [3 4] [5]]

pcalls

Executes the no-arg fns in parallel, returning a lazy sequence of their values. Mirrors clojure.core/pcalls. When host threads aren't granted (mino-thread-limit <= 1), falls back to sequential map so the surface is portable across embedded and CLI runs.

(pcalls (fn [] 1) (fn [] 2) (fn [] 3))
'(1 2 3)
(pcalls)
()

peek

Returns the first item of a list or last item of a vector.

(peek q)
1
(peek q)
1
(peek (pop q))
2

persistent!

Seals a transient and returns its persistent collection.

(persistent! t)
[1 2 3]
(persistent! @a)
[1 2]
(persistent! t)
[1 2 3]

pmap

Like map, except f is applied in parallel via futures. Semi-lazy in that the parallel computation stays no more than thread-limit-1 items ahead of the consumer. f's invocations across the collection are independent; do not pmap with a side-effectful f if order of effects matters. Single-arity collection only: (pmap f coll). When host threads are not granted (mino-thread-limit <= 1), falls back to (map f coll) so callers don't need a conditional.

pop

Returns a collection without the peek item.

(meta (pop (pop (pop x))))
xm
(pop sv)
[2 3]
(seq (pop q))
'(2 3)

pop!

Removes the last element from a transient vector.

pop-thread-bindings

Pop the topmost dynamic-binding frame. Throws when no frame is active. Pair with push-thread-bindings.

pop-thread-bindings*

(pop-thread-bindings*) — pop and free the top dynamic-binding frame. Throws when no frame is active.

pos-int?

Returns true if x is a positive integer (long tier).

pos?

Returns true if x is greater than zero.

postwalk

Walks form depth-first, applying f to each sub-form after its children.

(postwalk (fn [x] (if (number? x) (inc x) x)) '(1 (2 3)))
'(2 (3 4))

postwalk-replace

Replaces items in form that appear as keys in smap, walking bottom-up.

(postwalk-replace {:a 1 :b 2} [:a [:b :c]])
[1 [2 :c]]

pr-builtin

Prints a value readably via the built-in C formatter, bypassing print-method.

(with-out-str (pr-builtin {:a 1}))
"{:a 1}"

prefer-method

Prefers dispatch-val x over y in multimethod mm.

prefers

Returns the prefer-table of multimethod mm.

(prefers pf-mm)
{}

prefers?

prewalk

Walks form depth-first, applying f to each sub-form before its children.

prewalk-replace

Replaces items in form that appear as keys in smap, walking top-down.

(prewalk-replace {:a 1 :b 2} [:a [:b :c]])
[1 [2 :c]]

prim-into

prim-re-find

prim-re-matches

print-method

print-str

Returns the print-string of args, space-separated, no trailing newline.

(print-str 1 2 3)
"1 2 3"

printf

Formats and prints to *out*: equivalent to (print (apply format fmt args)).

(with-out-str (printf "x=%d y=%s" 42 "ok"))
"x=42 y=ok"

println-str

Returns the print-string of args followed by a newline.

(println-str "a" "b")
"a b\n"

prn-str

Returns the readable-string of args followed by a newline.

(prn-str [1 2 3])
"[1 2 3]\n"
(prn-str "hi")
"\"hi\"\n"

promise

Return a fresh promise that can be deliver'd a value once.

protocol-dispatch

push-thread-bindings

Push a fresh dynamic-binding frame whose entries come from the map. Symbols-or-strings are accepted as keys. Must be paired with pop-thread-bindings in a try/finally.

push-thread-bindings*

(push-thread-bindings* bindings-map) — push a fresh dynamic-binding frame. Must be paired with pop-thread-bindings* in a try/finally.

qualified-ident?

Returns true if x is a namespace-qualified symbol or keyword.

qualified-keyword?

Returns true if x is a namespace-qualified keyword.

qualified-symbol?

Returns true if x is a namespace-qualified symbol.

queue?

Returns true if x is a PersistentQueue.

rand-int

Returns a random integer between 0 (inclusive) and n (exclusive).

rand-nth

Returns a random element from coll.

random-sample

Returns items from coll with probability prob. When called with no collection, returns a transducer.

(random-sample 0 [1 2 3 4 5])
'()
(random-sample 1 [1 2 3 4 5])
'(1 2 3 4 5)
(into [] (random-sample 0) [1 2 3 4 5])
'()

random-seed!

Seeds the per-state PRNG to a known integer value so subsequent rand calls produce a reproducible stream. Returns the seed.

random-uuid

Returns a random UUID v4 string.

(subs (str (random-uuid)) 14 15)
"4"

rangev

Returns a vector of integers from start (inclusive) to end (exclusive).

ratio?

Returns true if x is a ratio. Capability: :bignum

rational?

Returns true if x is a rational number (int, bigint, or ratio). Capability: :bignum

rationalize

Returns the rational value nearest to the argument. Capability: :bignum

(rationalize -0.5)
-1/2
(rationalize 0.5)
1/2
(rationalize 0.25)
1/4

re-find-on-matcher

re-groups

Returns the most recent match groups for matcher m: a vector [whole g1 g2 ...] when the pattern has groups, the whole-match string otherwise. Throws when the matcher has no recorded match yet.

(re-groups m)
["1" "1"]
(re-groups m)
["2" "2"]

re-matcher

Returns a matcher value for repeated find/match operations on text using pattern. The resulting value is consumed by re-find, re-groups and so on.

re-pattern

Returns a regex from a string pattern (no-op on an existing regex). Capability: :regex

(type (re-pattern "\\d+"))
:regex
(re-find (re-pattern "abc") "xabcy")
"abc"
(re-pattern r)
r

re-seq

Returns a lazy sequence of all matches of pattern in string s. Each match is a string when the pattern has no groups, or a vector [whole g1 g2 ...] when it does.

(into [] (re-seq "\\d+" "abc123def456ghi"))
["123" "456"]
(into [] (re-seq "[a-z]" "a1b2c3"))
["a" "b" "c"]
(count (re-seq #"\d+" "1 2 33 444"))
4

read

(read "(+ 1 2)")
'(+ 1 2)
(read "42")
42
(read "#?(:mino 3 :clj 1 :cljs 2)")
3

read*

Reads one form from *in*. Atom-bound *in* consumes from the head; stdin-backed *in* is unsupported. The user-facing `read` in core.clj dispatches on arity.

read-line

Reads one line from *in*. Returns the line without trailing newline, or nil at EOF.

(with-in-str "hello\nworld" (read-line))
"hello"
(with-in-str "a\nb\nc"
[(read-line) (read-line) (read-line) (read-line)])
["a" "b" "c" nil]
(with-in-str "no-newline" (read-line))
"no-newline"

reader-conditional

Builds a reader-conditional record with form and splicing? fields. Predicate reader-conditional? returns true on the result.

reader-conditional?

Returns true if x is a reader-conditional record produced by reader-conditional.

realized?

Returns true if a delay, lazy sequence, future, or promise has been realized.

recompute-hierarchy

record*

Runtime constructor for record values. Takes a record type and a vector of declared field values. Used by the ->Type macro expansion.

record-fields

Returns the declared field-name vector for a record type.

record-from-map

Builds a record by reading declared fields from a map; non-field keys land in ext. Used by the map->Type macro expansion.

record-type?

Returns true if x is a record type (the value defrecord defines).

record?

Returns true if x is a record value.

reduce-kv

Reduces a map (or any associative source) with f taking accumulator, key, and value. Consults IKVReduce; falls back to walking the seq.

(reduce-kv (fn [acc k v] (assoc acc k (* v 2)))
{} {:a 1 :b 2})
{:a 2 :b 4}
(reduce-kv (fn [a k v] (assoc a k v)) {} {:a 1 :b 2})
"kv:2"

reduced

Wraps a value to signal early termination of reduce.

(reduce (fn [acc x] (if (> x 3) (reduced acc) (+ acc x))) 0 (range 10))
6
(reduce (fn [acc x] (reduced acc)) 0 [1 2 3])
0
(reduce (fn [a x] (if (>= x 10) (reduced a) (+ a x)))
0 v)
45

reduced?

Returns true if x is a reduced value.

reductions

Returns a lazy sequence of the intermediate values of a reduction.

(into [] (reductions + [1 2 3 4 5]))
[1 3 6 10 15]
(into [] (reductions + 100 [1 2 3]))
[100 101 103 106]

ref

Creates an STM ref holding the given initial value. Mutate via ref-set / alter / commute inside dosync. Capability: :stm

(type (ref 1))
:ref

ref-history-count

Returns the ref's current history-count. mino uses single-version optimistic locking; this stub always returns 0. Capability: :stm

(ref-history-count r)
0

ref-max-history

Returns the ref's max-history. mino uses single-version optimistic locking; this stub always returns 10. Capability: :stm

(ref-max-history r)
10

ref-min-history

Returns the ref's min-history. mino uses single-version optimistic locking; this stub always returns 0. Capability: :stm

(ref-min-history r)
0

ref-set

Sets the value of ref. Must be in dosync. Returns the new value. Capability: :stm

ref?

Returns true if x is an STM ref. Capability: :stm

refer

Bring all publics of a namespace into the current namespace.

regex?

Returns true if x is a regex value.

register-method

release-pending-sends

Returns the count of sends queued by the current transaction and clears them so they will NOT fire on commit. Outside a transaction returns 0. Capability: :agent

remove

Returns a lazy sequence of items in coll for which pred returns falsy. When called with no collection, returns a transducer.

(into [] (remove even? [1 2 3 4 5]))
[1 3 5]
(transduce (remove even?) + 0 [1 2 3 4 5])
9

remove-all-methods

Removes all methods from multimethod mm.

remove-method

Removes the method for dispatch-val from multimethod mm.

remove-ns

Remove a namespace from the runtime.

remove-tap

Unregisters f from the tap registry. Returns nil.

remove-watch

Removes a watch function from an atom by key.

(remove-watch a :w)
a
(remove-watch a :nonexistent)
a

repeatedly

Returns a lazy sequence of calls to f. With two args, returns n calls.

(take 3 (repeatedly (fn [] 42)))
'(42 42 42)

replace

Returns a collection with items in coll replaced by entries in smap.

(meta (replace {2 "two"} x))
xm
(replace {2 "two"} x)
[1 "two" 3]
(into [] (replace {:a 1 :b 2} [:a :c :b]))
[1 :c 2]

replicate

Returns a lazy seq of n copies of x. Deprecated alias for (take n (repeat x)).

(vec (replicate 3 :x))
[:x :x :x]
(vec (replicate 0 :x))
[]

requiring-resolve

Require the namespace if needed, then resolve a qualified symbol.

(deref (requiring-resolve 'foo.bar/x))
:success

reset-meta!

Atomically resets the metadata for a reference type to meta-map. Returns meta-map.

reset-vals!

Sets the value of an atom and returns [old new].

(reset-vals! a 42)
[10 42]
(reset-vals! a 10)
[5 10]

resolve

Returns the var to which a symbol resolves, or nil.

(eval (read-string "(do (ns-unmap *ns* 'Object) (def o1 (resolve 'Object)) (import '[java.lang Object]) (def o2 (resolve 'Object)) [(some? o1) (some? o2)])"))
[false true]
(do (require '[remote :refer [cake]])
(ns-unmap *ns* 'cake)
(def resolved (resolve 'cake))
(intern *ns* 'cake "bar")
[resolved cake])
[nil "bar"]

restart-agent

Clears the agent's error and resets its state to the given value. Trailing :clear-actions true also drops every queued action targeting this agent. Capability: :agent

reversible?

Returns true if x supports rseq (vectors and sorted collections).

rm-rf

Recursively removes a file or directory. Capability: :fs

rseq

Returns a reverse sequence of a vector, or nil if empty.

rsubseq

Returns the entries of a sorted collection whose keys fall in the given range, descending.

(rsubseq m >= 3)
'([5 25] [4 16] [3 9])
(rsubseq m >= 3 < 7)
'([6 36] [5 25] [4 16] [3 9])
(rsubseq s > 1 < 5)
'(4 3 2)

run!

Applies f to each item in coll for side effects. Returns nil.

satisfies?

Returns true if x's type has implementations for all methods of proto.

second

Returns the second item in coll.

(second [1 2 3])
2
(second v)
:tail
(second e)
1

select-keys

Returns a map containing only the entries whose keys are in ks.

(meta (select-keys x [:bar]))
xm
(select-keys {:a 1 :b 2 :c 3} [:a :c])
{:a 1 :c 3}

send

Dispatches an action onto the agent's POOLED run-queue and returns the agent immediately. The action runs on the POOLED worker under state_lock. Throws MTH001 if the host has not granted a thread budget for the worker. Capability: :agent

send-off

Dispatches an action onto the agent's SOLO run-queue. mino's per-state eval lock means actions across the two pools still serialize, but the queues are independent: a long-running send-off action does not stall pending sends, and vice versa. Throws MTH001 if the host has not granted a thread budget. Capability: :agent

send-via

JVM-canon dispatches the action through a host-supplied Executor. mino has no public Executor type yet; this prim throws MST008 rather than aliasing to send and dropping the executor argument. Use send / send-off. Capability: :agent

seq

Returns a seq on the collection, or nil if empty.

(seq (byte-array [65 66 67]))
[65 66 67]
(seq (byte-array [-1 0 -128]))
[255 0 128]
(loop [a []
     b [1 2 3]]
(if (seq b)
  (recur (conj a (* 2 (first b)))
         (next b))
  a))
[2 4 6]

seq-to-map-for-destructuring

Builds a map from a sequence of keyword/value pairs, possibly with a trailing override map. Used by JVM Clojure's 1.11+ map-destructure over a varargs seq. Public so portable code can call it directly.

(seq-to-map-for-destructuring [])
{}
(seq-to-map-for-destructuring nil)
{}
(seq-to-map-for-destructuring [:a 1 :b 2])
{:a 1 :b 2}

seqable?

Returns true if (seq x) is supported.

sequence

Coerces coll to a (possibly empty) sequence, if it is not already one. Will not force a lazy seq. (sequence nil) yields (). With a transducer xf, returns a lazy sequence of applying xf to coll, or to the pair-wise step of multiple collections. Parallel collections stop at the shortest.

(sequence (map inc) (range 10))
(range 1 11)
(sequence (map-indexed vector) [])
[]
(sequence (map-indexed vector) (range 1 5))
[[0 1] [1 2] [2 3] [3 4]]

sequential?

Returns true if x is a sequential collection (list, vector, or lazy-seq).

set

Returns a set of the items in coll.

(set (keys entries))
#{:a :c}
(set (vals entries))
#{1 3}
(set [1 2 3])
#{1 2 3}

set-dyn-binding!

(set-dyn-binding! 'name value) — mutate the topmost active dynamic binding for `name`. Returns the value. Throws when no binding frame is active for `name`. Backs (set! *var* expr).

set-error-handler!

Sets the agent's error-handler fn (called with [agent ex] when an action throws). Capability: :agent

set-error-mode!

Sets the agent's error mode (:fail or :continue). Capability: :agent

set-fail-alloc-at!

Make the n-th GC allocation fail (simulated OOM). Pass 0 to disable.

set-print-method!

Installs a fn to dispatch pr / prn output; nil removes the hook.

set-validator!

Sets a validator function on an atom.

sh

Runs an external command. Returns {:exit n :out "..."}. Capability: :proc

sh!

Runs an external command. Returns stdout; throws on non-zero exit. Capability: :proc

(sh! "echo" "hello")
"hello\n"

short

Coerces x to a short (16-bit integer). Throws on out-of-range values, NaN, or infinity. Returns the value as a long since mino has only one integer tier.

short-array

Creates a host-style short array. Zero-fills on size argument; copies elements from a collection.

shuffle

Returns a randomly shuffled vector of the items in coll.

shutdown-agents

Quiesces both per-state agent workers: signals each to drain its remaining queue, joins the pthreads, seals the agent surface so subsequent send / send-off throw MST008. Idempotent. Throws MST002 if called from inside an action body (self-join). Capability: :agent

simple-ident?

Returns true if x is a non-namespace-qualified symbol or keyword.

simple-keyword?

Returns true if x is a keyword with no namespace.

simple-symbol?

Returns true if x is a symbol with no namespace.

some-fn

Returns a function that returns the first truthy value from any pred applied to any argument.

some?

Returns true if x is not nil.

(eval (read-string "(do (ns-unmap *ns* 'Object) (def o1 (resolve 'Object)) (import '[java.lang Object]) (def o2 (resolve 'Object)) [(some? o1) (some? o2)])"))
[false true]

sort-by

Returns a sorted sequence of the items in coll, ordered by (keyfn item).

(sort-by count ["ccc" "a" "bb"])
'("a" "bb" "ccc")
(sort-by count > ["a" "bb" "ccc"])
'("ccc" "bb" "a")

sorted-map

Returns a new sorted map with the given key-value pairs.

(get m (sorted-map :a 1))
:A-val
(hash (sorted-map))
(hash {})
(pr-str (sorted-map :a/x 1 :a/y 2))
"{:a/x 1, :a/y 2}"

sorted-map-by

Returns a sorted map using the given comparator function.

sorted-set

Returns a new sorted set containing the arguments.

(get m (sorted-set :a :b))
:found
(hash (sorted-set))
(hash #{})
(count (sorted-set 3 1 2))
3

sorted-set-by

Returns a sorted set using the given comparator function.

sorted?

Returns true if x is a sorted collection.

special-symbol?

Returns true if x is a symbol that names a special form.

special-symbols-set

split-at

Returns a vector of [(take n coll) (drop n coll)].

(split-at 2 [1 2 3 4 5])
['(1 2) '(3 4 5)]

split-with

Returns a vector of [(take-while pred coll) (drop-while pred coll)].

(split-with odd? [1 3 4 2 5])
['(1 3) '(4 2 5)]

splitv-at

Returns a vector [(vec (take n coll)) (vec (drop n coll))].

(splitv-at 2 [1 2 3 4])
[[1 2] [3 4]]
(splitv-at 5 [1 2 3])
[[1 2 3] []]
(splitv-at 0 [1 2 3])
[[] [1 2 3]]

subbits

Zero-copy-semantics slice of a bytes value over a half-open bit range [start..end). Result satisfies bitstring? and is byte-aligned when (- end start) is a multiple of 8.

subseq

Returns the entries of a sorted collection whose keys fall in the given range, ascending.

(subseq m >= 3)
'([3 9] [4 16] [5 25])
(subseq m > 3)
'([4 16] [5 25])
(subseq m <= 2)
'([0 0] [1 1] [2 4])

substring-index

subvec

Returns a subvector from start (inclusive) to end (exclusive).

(subvec [1 2 3 4] 1 3)
[2 3]
(subvec [1 2 3 4] 2)
[3 4]
(subvec [1 2 3] 1 1)
[]

swap-vals!

Atomically applies f to the atom and returns [old new].

(swap-vals! a inc)
[10 11]
(swap-vals! a + 5)
[0 5]
(swap-vals! a inc)
[5 6]

tagged-literal

Builds a tagged-literal record with tag and form fields. Predicate tagged-literal? returns true on the result.

tagged-literal?

Returns true if x is a tagged-literal record produced by tagged-literal.

take-last

Returns a seq of the last n items in coll.

(take-last 2 [1 2 3 4 5])
'(4 5)
(take-last 5 [1 2 3])
'(1 2 3)

take-nth

Returns a lazy sequence of every nth item in coll. When called with no collection, returns a transducer.

take-while

Returns a lazy sequence of items from coll while pred returns truthy. When called with no collection, returns a transducer.

(take-while (fn [x] (< x 3)) [1 2 3 4])
'(1 2)
(transduce (take-while #(< % 4)) conj [] [1 2 3 4 5])
[1 2 3]

tap-fns

tap>

Sends x to every registered tap. Tap fns that throw are silently skipped so a misbehaving subscriber does not poison the stream. Returns true.

tc-ancestors

the-ns

Return the namespace symbol or throw if not found.

(ns-name (the-ns (the-ns 'clojure.set)))
'clojure.set
(eval (read-string "(do (ns ^{:a 1} foo {:b 1}) (meta *ns*) (ns bar) (meta (the-ns 'foo)))"))
{:a 1, :b 1}

thread-bound?

Returns true if all of the vars provided as arguments have thread-local bindings active on the current dyn-stack.

thread-sleep

Blocks the current thread for the given number of milliseconds. Returns nil. Capability: :proc

to-array

Converts a collection to an Object array (host-style).

trampoline

Calls f with args, then repeatedly calls the result if it is a function.

(trampoline my-bounce 1000)
:done

transduce

Reduces coll using the transducer xf applied to the reducing function f.

(transduce (take 1) conj [:a])
[:a]
(transduce (comp (take 1) (take 1)) conj [:a])
[:a]
(transduce (comp (take 1) (take 1) (take 1)) conj [:a])
[:a]

transient

Returns a transient view of coll for batch mutation.

transient?

Returns true if x is a transient.

tree-seq

Returns a lazy depth-first sequence of nodes in a tree.

(into [] (tree-seq vector? seq [1 [2 [3]]]))
[[1 [2 [3]]] 1 [2 [3]] 2 [3] 3]

true?

Returns true if x is the value true.

type-marker-key

Translates an extend-protocol type marker to the dispatch key extend-type understands. Keywords pass through (used for built-in types and ad-hoc tags via :type metadata). Symbols pass through too: at runtime they evaluate to a MINO_TYPE value so (extend-protocol P Point ...) places its impls under that type's pointer in the dispatch atom. Nil maps to :nil so a (extend-protocol P nil ...) clause registers against (type nil).

unchecked-add

Returns x + y as a long with two's-complement wraparound. Operands must be ints. Opt-in fast path for code that knows overflow can't occur or wants wraparound semantics.

(unchecked-add max-int 1)
min-int
(unchecked-add 9223372036854775807 1)
-9223372036854775808
(unchecked-add 1 2)
3

unchecked-add-int

Returns x + y with 32-bit two's-complement wraparound.

(unchecked-add-int 1 1)
2
(unchecked-add-int 2147483647 1)
-2147483648

unchecked-byte

Coerce x to an 8-bit signed byte (stored in a long with sign extension).

(unchecked-byte 255)
-1
(unchecked-byte 128)
-128
(unchecked-byte 256)
0

unchecked-char

Coerce x to a Unicode char by truncating to 16 bits (matching JVM char).

(unchecked-char 65)
\A
(unchecked-char 48)
\0

unchecked-dec

Returns x - 1 as a long with two's-complement wraparound. Argument must be an int.

(unchecked-dec min-int)
max-int
(unchecked-dec -9223372036854775808)
9223372036854775807
(unchecked-dec 5)
4

unchecked-dec-int

Returns x - 1 with 32-bit two's-complement wraparound.

(unchecked-dec-int 0)
-1
(unchecked-dec-int -2147483648)
2147483647

unchecked-divide-int

Returns the truncating integer division of x by y. Both must be ints. Aliased to quot — the truncating semantic matches canon's unchecked-divide-int (no overflow check; on the JVM this is the primitive idiv instruction).

unchecked-double

Coerce x to a 64-bit double.

(unchecked-double 1)
1.0
(unchecked-double 1.0)
1.0

unchecked-float

Coerce x to a 32-bit float.

unchecked-inc

Returns x + 1 as a long with two's-complement wraparound. Argument must be an int.

(unchecked-inc max-int)
min-int
(unchecked-inc 9223372036854775807)
-9223372036854775808
(unchecked-inc 5)
6

unchecked-inc-int

Returns x + 1 with 32-bit two's-complement wraparound.

(unchecked-inc-int 0)
1
(unchecked-inc-int 2147483647)
-2147483648

unchecked-int

Coerce x to a 32-bit signed int (stored in a long with sign extension). Truncates toward zero; 32-bit wraparound.

(unchecked-int 1)
1
(unchecked-int -1)
-1
(unchecked-int 2147483648)
-2147483648

unchecked-long

Coerce x to a 64-bit long by truncating toward zero. No overflow check; out-of-range doubles clamp to long-long range.

(unchecked-long 1)
1
(unchecked-long -1)
-1
(unchecked-long 1.1)
1

unchecked-multiply

Returns x * y as a long with two's-complement wraparound. Operands must be ints.

(unchecked-multiply 2 4611686018427387904)
min-int
(unchecked-multiply 2 4611686018427387904)
-9223372036854775808
(unchecked-multiply 2 3)
6

unchecked-multiply-int

Returns x * y with 32-bit two's-complement wraparound.

(unchecked-multiply-int 2 3)
6

unchecked-negate

Returns -x as a long with two's-complement wraparound. Argument must be an int.

(unchecked-negate -9223372036854775808)
-9223372036854775808
(unchecked-negate 5)
-5

unchecked-negate-int

Returns -x with 32-bit two's-complement wraparound.

(unchecked-negate-int 5)
-5
(unchecked-negate-int -2147483647)
2147483647

unchecked-remainder-int

Returns the 32-bit signed remainder of x divided by y. Matches JVM int `%`; throws on division by zero; INT_MIN % -1 = 0.

(unchecked-remainder-int 10 3)
1
(unchecked-remainder-int -2147483648 -1)
0

unchecked-short

Coerce x to a 16-bit signed short (stored in a long with sign extension).

(unchecked-short 65535)
-1
(unchecked-short 32768)
-32768
(unchecked-short 1)
1

unchecked-subtract

Returns x - y as a long with two's-complement wraparound. Operands must be ints.

(unchecked-subtract min-int 1)
max-int
(unchecked-subtract -9223372036854775808 1)
9223372036854775807
(unchecked-subtract 5 3)
2

unchecked-subtract-int

Returns x - y with 32-bit two's-complement wraparound.

(unchecked-subtract-int 1 1)
0
(unchecked-subtract-int -2147483648 1)
2147483647

underive

Removes a parent/child relationship between child and parent.

(underive h :a :c)
h

unreduced

Unwraps a reduced value. If not reduced, returns x.

unsigned-bit-shift-right

Returns n logically shifted right by count bits.

(unsigned-bit-shift-right -1 1)
9223372036854775807
(unsigned-bit-shift-right -1 63)
1

update-in

Updates a value in a nested associative structure by applying f at the given key path.

(update-in {:a {:b 1}} [:a] update :b inc)
{:a {:b 2}}
(update-in {:a {:b 1}} [:a :b] inc)
{:a {:b 2}}

update-keys

Returns a map with f applied to each key.

(update-keys {:a 1 :b 2} name)
{"a" 1 "b" 2}
(update-keys {1 :a 2 :b} (fn [k] (* k 2)))
{2 :a 4 :b}
(update-keys {} inc)
{}

update-vals

Returns a map with f applied to each value.

(update-vals {:a 1 :b 2 :c 3} (fn [v] (* v 2)))
{:a 2 :b 4 :c 6}
(update-vals {:a 1 :b 2 :c 3} inc)
{:a 2 :b 3 :c 4}
(update-vals {} inc)
{}

uri?

use

Loads a module and refers all of its public names by default.

(eval (read-string "(do (ns ut-a2) (use 'clojure.set) (union #{1} #{2}))"))
#{1 2}
(eval (read-string "(do (ns ut-a3) (use '[clojure.set :only [union]]) (union #{1} #{2}))"))
#{1 2}

uuid-hex-pattern

uuid-string?

Validates RFC 4122 textual layout: 36 chars with dashes at the 8/13/18/23 positions and hex digits everywhere else. Avoids the {n} quantifier mino's regex engine does not support.

uuid?

Returns true if x is a UUID value.

val

Returns the value of a map entry. Throws on values that are not map entries (a literal 2-vector, for instance).

(val (first {:a 1}))
1
(val (first {nil 1}))
1
(val (first {:a nil}))
nil

valid-hierarchy?

valid-tag?

var-get

Return the root value of a var.

(var-get #'vg-x)
42
(var-get (var vg-x))
42
(var-get (find-var (symbol (str (ns-name *ns*)) "interned-x")))
99

var-set

Set the root value of a var.

var?

Returns true if x is a var.

vary-meta

Returns a copy of the value with (apply f meta args) as its metadata.

(catches-throw?
#(vary-meta (var with-meta-var-target) assoc :doc "y"))
true

vec

Converts coll into a vector. Coll must be nil, a sequential collection, a string, a map, a set, or a host array. Booleans, numbers, keywords, characters, regexes, and transients throw (matching JVM Clojure's `vec` rejecting non-seqable scalars).

(apply (fn [a b & rest] (vec (cons a (cons b rest)))) [1 2 3 4 5])
[1 2 3 4 5]
((fn [[a & rest]] [a (vec rest)]) [1 2 3])
[1 [2 3]]
(vec results)
[1 4 9 16 25]

volatile!

Creates a volatile cell with the given initial value. A volatile is a single-slot mutable reference with no watches, validators, or atomic publish — intended for transducer state where the reducing fn already implies single-thread access.

volatile?

Returns true if x is a volatile.

vreset!

Sets the value of a volatile to newval and returns newval. No watches, no validators, no atomicity.

vswap!

Applies f to the current value of the volatile and any args, sets the result, and returns it. No retry loop — single-thread only.

walk

Traverses form, applying inner to each element and outer to the result.

with-bindings*

(with-bindings* bindings-map fn) — pushes the bindings as a dynamic frame and invokes fn with no args.

(with-bindings* snap (fn [] *bt-dyn-y*))
:snap

with-meta

Returns a copy of the value with the given metadata map.

(meta (empty (with-meta [1 2] {:a 1})))
{:a 1}
(meta (empty (with-meta {:x 1} {:b 2})))
{:b 2}
(meta (empty (with-meta #{1 2} {:c 3})))
{:c 3}

with-redefs-fn

Temporarily rebinds the root values of vars to new-values while thunk runs, restoring originals afterward. bindings-map is a map of var -> new-value.

zero?

Returns true if x is zero.

(letfn [(my-even? [n] (if (zero? n) :even (my-odd?  (dec n))))
      (my-odd?  [n] (if (zero? n) :odd  (my-even? (dec n))))]
(my-even? 7))
:odd
(letfn [(my-even? [n] (if (zero? n) :even (my-odd?  (dec n))))
      (my-odd?  [n] (if (zero? n) :odd  (my-even? (dec n))))]
(my-even? 6))
:even

zipmap

Returns a map with keys mapped to corresponding vals.

(zipmap [:a :b] [1 2])
{:a 1 :b 2}
(zipmap [:a] [1 2])
{:a 1}
(zipmap [:a :b] [1])
{:a 1}

Special forms

These forms are recognized directly by the evaluator and cannot be redefined.

quote

(str (quote Foo.))
"Foo."

quasiquote

unquote

unquote-splicing

def

(eval (read-string "(do (ns foo) (def x 1) (ns bar) (def x 2) (in-ns 'baz) (def x 3) (require 'foo 'bar) [foo/x bar/x x])"))
[1 2 3]
(eval (read-string "(do (ns foo) (def x 1) (ns bar) (def x 2) (in-ns 'baz) (def x 3) (require (symbol \"foo\") (symbol \"bar\")) [foo/x bar/x x])"))
[1 2 3]
(eval (read-string "(do (in-ns 'bar) (def just-one-ns :bar/foo) (in-ns 'bar) just-one-ns)"))
:bar/foo

defmacro

if

(loop [a 1]
(if (< a 3)
  (recur (inc a))
  a))
3
(loop [a []
     b [1 2 3]]
(if (seq b)
  (recur (conj a (* 2 (first b)))
         (next b))
  a))
[2 4 6]
(loop [a ()
     b [1 2 3]]
(if (seq b)
  (recur (conj a (* 2 (first b)))
         (next b))
  a))
[6 4 2]

do

(do 1 2 3)
3
(eval (read-string
"(do (ns cs-strict-only.a (:refer-clojure :only [+ -])) (+ 1 2))"))
3
(eval (read-string "(do (in-ns 'cs-strict-foo) (ns-name *ns*))"))
'cs-strict-foo

let

(let [x 5] x)
5
(let [x 1 y 2] (+ x y))
3
(let [x 1 y (+ x 10)] y)
11

fn

((fn [n] (+ n 0)) tag-max)
tag-max
((fn [n] (+ n 1)) tag-max)
(+' tag-max 1)
((fn [n] (dec n)) tag-max)
(- tag-max 1)

loop

(loop [] 1)
1
(loop [a 1]
(if (< a 3)
  (recur (inc a))
  a))
3
(loop [a []
     b [1 2 3]]
(if (seq b)
  (recur (conj a (* 2 (first b)))
         (next b))
  a))
[2 4 6]

recur

(loop [a 1]
(if (< a 3)
  (recur (inc a))
  a))
3
(loop [a []
     b [1 2 3]]
(if (seq b)
  (recur (conj a (* 2 (first b)))
         (next b))
  a))
[2 4 6]
(loop [a ()
     b [1 2 3]]
(if (seq b)
  (recur (conj a (* 2 (first b)))
         (next b))
  a))
[6 4 2]

try

(try 42)
42
(try (+ 1 2))
3
(try (throw "oops") (catch e (ex-data e)))
"oops"

Standard library

Defined in mino source at startup. View with (source name) at the REPL.

whenmacro

Evaluates body when test is truthy. Returns nil otherwise.

Source
(defmacro when
  "Evaluates body when test is truthy. Returns nil otherwise."
  [c & body]
  `(if ~c (do ~@body)))
(when true 1)
1
(when true)
nil
(when false)
nil

condmacro

Takes pairs of test/expr. Returns the expr for the first truthy test.

Source
(defmacro cond
  "Takes pairs of test/expr. Returns the expr for the first truthy test."
  [& clauses]
  (if (< (count clauses) 2)
    nil
    `(if ~(first clauses)
         ~(first (rest clauses))
         (cond ~@(rest (rest clauses))))))
(cond)
nil
(cond nil true)
nil
(cond false true)
nil

andmacro

Returns the first falsy value, or the last value if all are truthy.

Source
(defmacro and
  "Returns the first falsy value, or the last value if all are truthy."
  [& xs]
  (if (= 0 (count xs))
    true
    (if (= 1 (count xs))
      (first xs)
      (let [g (gensym)]
        `(let [~g ~(first xs)]
           (if ~g (and ~@(rest xs)) ~g))))))
(and)
true
(and true)
true
(and nil)
nil

ormacro

Returns the first truthy value, or the last value if none are truthy.

Source
(defmacro or
  "Returns the first truthy value, or the last value if none are truthy."
  [& xs]
  (if (= 0 (count xs))
    nil
    (if (= 1 (count xs))
      (first xs)
      (let [g (gensym)]
        `(let [~g ~(first xs)]
           (if ~g ~g (or ~@(rest xs))))))))
(or)
nil
(or true)
true
(or nil)
nil

->macro

Thread-first. Inserts x as the second item in the first form, then inserts the result as the second item in the next form, and so on.

Source
(defmacro ->
  "Thread-first. Inserts x as the second item in the first form, then
  inserts the result as the second item in the next form, and so on."
  [x & forms]
  (if (= 0 (count forms))
    x
    (let [step (first forms)]
      (if (cons? step)
        `(-> (~(first step) ~x ~@(rest step)) ~@(rest forms))
        `(-> (~step ~x) ~@(rest forms))))))
(meta (-> x (dissoc :foo) (dissoc :bar)))
xm
(meta (-> x (disj 1) (disj 2) (disj 3)))
xm
(-> 10 (- 3) (- 2))
5

->>macro

Thread-last. Inserts x as the last item in the first form, then inserts the result as the last item in the next form, and so on.

Source
(defmacro ->>
  "Thread-last. Inserts x as the last item in the first form, then
  inserts the result as the last item in the next form, and so on."
  [x & forms]
  (if (= 0 (count forms))
    x
    (let [step (first forms)]
      (if (cons? step)
        `(->> (~(first step) ~@(rest step) ~x) ~@(rest forms))
        `(->> (~step ~x) ~@(rest forms))))))
(->> 10 (- 3) (- 2))
9

dosyncmacro

Runs body in an STM transaction. Refs may be altered, set, ensured, or commuted within. The transaction retries on write conflicts in multi-threaded mode. Side effects via (io! ...) inside the body throw. Requires STM to be installed (mino_install_stm).

Source
(defmacro dosync
  "Runs body in an STM transaction. Refs may be altered, set, ensured,
  or commuted within. The transaction retries on write conflicts in
  multi-threaded mode. Side effects via (io! ...) inside the body
  throw. Requires STM to be installed (mino_install_stm)."
  [& body]
  `(dosync* (fn [] ~@body)))

io!macro

If invoked within an STM transaction, throws an IllegalStateException-equivalent before evaluating body. Marks a body as having unsafe side effects so dosync can refuse it.

Source
(defmacro io!
  "If invoked within an STM transaction, throws an
  IllegalStateException-equivalent before evaluating body. Marks a
  body as having unsafe side effects so dosync can refuse it."
  [& body]
  `(do (io!-check) ~@body))

^:privatefunction

Source
(def ^:private fn-arity-with-prepost
  (fn [arity]
    (let [params (first arity)
          body   (rest arity)
          head   (first body)]
      (if (and (map? head)
               (or (contains? head :pre) (contains? head :post)))
        (let [pre   (get head :pre [])
              post  (get head :post [])
              rest-body (rest body)
              assert-pre
              (map (fn [p]
                     (list 'when-not p
                           (list 'throw
                                 (list 'ex-info
                                       (str "Pre-condition failed: "
                                            (pr-str p))
                                       {:pre (list 'quote p)}))))
                   pre)
              assert-post
              (map (fn [p]
                     (list 'when-not p
                           (list 'throw
                                 (list 'ex-info
                                       (str "Post-condition failed: "
                                            (pr-str p))
                                       {:post (list 'quote p)}))))
                   post)
              wrapped
              (apply list
                     (concat assert-pre
                             [(apply list 'let
                                     ['% (apply list 'do rest-body)]
                                     [(apply list 'do
                                             (concat assert-post
                                                     ['%]))])]))]
          (cons params wrapped))
        arity))))

defnmacro

Defines a named function. Supports docstrings, multi-arity, and :pre/:post conditions.

Source
(defmacro defn
  "Defines a named function. Supports docstrings, multi-arity, and
   :pre/:post conditions."
  [name & fdecl]
  (let [has-doc  (string? (first fdecl))
        doc      (if has-doc (first fdecl) nil)
        fdecl    (if has-doc (rest fdecl) fdecl)
        has-attr (map? (first fdecl))
        fdecl    (if has-attr (rest fdecl) fdecl)
        ;; If the first remaining form is a vector, this is single-arity
        ;; (params-vec body...). Otherwise it's a sequence of arity
        ;; lists (params-vec body...) (params-vec body...). Handle the
        ;; :pre/:post map either way.
        rewritten (if (vector? (first fdecl))
                    (fn-arity-with-prepost fdecl)
                    (mapv fn-arity-with-prepost fdecl))
        form     (if (vector? (first fdecl))
                   (cons 'fn rewritten)
                   (apply list 'fn rewritten))]
    (if doc
      `(def ~name ~doc ~form)
      `(def ~name ~form))))
(eval (read-string "(do (ns foo) (defn foo [] 1) (ns bar) (apply require ['[foo :as f]]) (f/foo))"))
1
(eval (read-string "(do (defn inc [x] :foo) ((get (ns-map *ns*) 'inc) 1))"))
:foo
(load-string "(defn __ls_sq [x] (* x x)) (__ls_sq 5)")
25

defn-macro

Same as defn, yielding a non-public def.

Source
(defmacro defn-
  "Same as defn, yielding a non-public def."
  [name & body]
  (apply list 'defn (vary-meta name assoc :private true) body))

defoncemacro

Defines name only if it has no root binding.

Source
(defmacro defonce
  "Defines name only if it has no root binding."
  [name expr]
  `(when-not (resolve '~name)
     (def ~name ~expr)))

^:privatefunction

Source
(def ^:private map1 lazy-map-1)

lazy-catmacro

Expands to code that yields a lazy concatenation of the given collections.

Source
(defmacro lazy-cat
  "Expands to code that yields a lazy concatenation of the given
   collections."
  [& colls]
  (if (seq colls)
    `(lazy-seq (concat ~(first colls) (lazy-cat ~@(rest colls))))
    `(lazy-seq nil)))

interleavefunction

Returns a lazy sequence of the first item in each collection, then the second, and so on.

Source
(def interleave
  "Returns a lazy sequence of the first item in each collection, then
   the second, and so on."
  (let [interleave2
        (fn interleave2 [c1 c2]
          (lazy-seq
            (let [s1 (seq c1) s2 (seq c2)]
              (when (and s1 s2)
                (cons (first s1)
                      (cons (first s2)
                            (interleave2 (rest s1)
                                         (rest s2))))))))]
    (fn
      ([] ())
      ([c1] (lazy-seq (seq c1)))
      ([c1 c2] (interleave2 c1 c2))
      ([c1 c2 & colls]
       (lazy-seq
         (let [ss (map seq (cons c1 (cons c2 colls)))]
           (when (every? identity ss)
             (concat (map first ss)
                     (apply interleave (map rest ss))))))))))
(interleave [1 2 3] [:a :b :c])
'(1 :a 2 :b 3 :c)

partitionfunction

Returns a lazy sequence of lists of n items each, at offsets step apart. With pad, the final partition is filled from pad to reach n; if pad is shorter than needed, returns a partition with fewer than n items.

Source
(def partition
  "Returns a lazy sequence of lists of n items each, at offsets step
   apart. With pad, the final partition is filled from pad to reach
   n; if pad is shorter than needed, returns a partition with fewer
   than n items."
  (let [part-impl
        (fn part-impl [n step coll]
          (lazy-seq
            (when-let [s (seq coll)]
              (let [p (doall (take n s))]
                (when (= n (count p))
                  (cons p (part-impl n step (drop step s))))))))
        part-pad-impl
        (fn part-pad-impl [n step pad coll]
          (lazy-seq
            (when-let [s (seq coll)]
              (let [p (doall (take n s))]
                (if (= n (count p))
                  (cons p (part-pad-impl n step pad (drop step s)))
                  (list (take n (concat p pad))))))))]
    (fn
      ([n coll]            (part-impl n n coll))
      ([n step coll]       (part-impl n step coll))
      ([n step pad coll]   (part-pad-impl n step pad coll)))))
(partition 2 [1 2 3 4])
'((1 2) (3 4))
(partition 2 [1 2 3])
'((1 2))
(partition 2 1 [1 2 3 4])
'((1 2) (2 3) (3 4))

array-mapfunction

Creates a hash-map.

Source
(def array-map    "Creates a hash-map." hash-map)

delaymacro

Creates a delay that evaluates body on first deref.

Source
(defmacro delay
  "Creates a delay that evaluates body on first deref."
  [& body]
  `(let [state# (atom {:status :pending})]
     {:delay/fn  (fn []
                   (let [s# @state#]
                     (if (= (:status s#) :done)
                       (:value s#)
                       (let [v# (do ~@body)]
                         (reset! state# {:status :done :value v#})
                         v#))))
      :delay/state state#}))

if-notmacro

Evaluates then when test is falsy, else otherwise.

Source
(defmacro if-not
  "Evaluates then when test is falsy, else otherwise."
  [test then & else]
  (if (seq else)
    `(if (not ~test) ~then ~(first else))
    `(if (not ~test) ~then)))
(if-not false :yes :no)
:yes
(if-not true :yes :no)
:no
(if-not nil :yes)
:yes

when-notmacro

Evaluates body when test is falsy.

Source
(defmacro when-not "Evaluates body when test is falsy." [test & body]
  `(when (not ~test) ~@body))
(when-not false 1)
1
(when-not true)
nil
(when-not false)
nil

if-letmacro

Binds the result of expr, evaluates then if truthy, else otherwise.

Source
(defmacro if-let
  "Binds the result of expr, evaluates then if truthy, else otherwise."
  [bindings then & else]
  (when-not (and (vector? bindings) (= 2 (count bindings)))
    (throw "if-let requires a binding vector of exactly one symbol/expr pair"))
  (let [sym  (first bindings)
        expr (first (rest bindings))
        g    (gensym)]
    (if (seq else)
      `(let [~g ~expr]
         (if ~g (let [~sym ~g] ~then) ~(first else)))
      `(let [~g ~expr]
         (if ~g (let [~sym ~g] ~then))))))
(if-let [a 1] a)
1
(if-let [[a b] '(1 2)] b)
2
(if-let [a false] (throw (ex-info "boom" {})))
nil

when-letmacro

Binds the result of expr, evaluates body if truthy.

Source
(defmacro when-let
  "Binds the result of expr, evaluates body if truthy."
  [bindings & body]
  (when-not (and (vector? bindings) (= 2 (count bindings)))
    (throw "when-let requires a binding vector of exactly one symbol/expr pair"))
  (let [sym  (first bindings)
        expr (first (rest bindings))
        g    (gensym)]
    `(let [~g ~expr]
       (when ~g (let [~sym ~g] ~@body)))))
(when-let [a 1] a)
1
(when-let [[a b] '(1 2)] b)
2
(when-let [a false] (throw (ex-info "boom" {})))
nil

when-firstmacro

Binds the first element of a collection, evaluates body if the collection is non-empty.

Source
(defmacro when-first
  "Binds the first element of a collection, evaluates body if the
   collection is non-empty."
  [[x coll] & body]
  `(when-let [s# (seq ~coll)]
     (let [~x (first s#)] ~@body)))

letfnmacro

Binds local functions. Each binding is (name [params] body...). Expands to the `letfn*` special form so the bound fns can refer to each other (mutual recursion) — every name is placeholder- bound before any fn body is evaluated, so each fn's closure captures the shared scope.

Source
(defmacro letfn
  "Binds local functions. Each binding is (name [params] body...).
   Expands to the `letfn*` special form so the bound fns can refer
   to each other (mutual recursion) — every name is placeholder-
   bound before any fn body is evaluated, so each fn's closure
   captures the shared scope."
  [bindings & body]
  (let [pairs (vec (mapcat
                     (fn [b]
                       [(first b)
                        (apply list 'fn (first b) (rest b))])
                     bindings))]
    `(letfn* ~pairs ~@body)))
(letfn [(double [x] (* 2 x))]
(double 5))
10
(letfn [(double [x] (* 2 x))
       (add1 [x] (+ x 1))]
(add1 (double 5)))
11
(letfn [(factorial [n]
         (if (<= n 1) 1 (* n (factorial (dec n)))))]
(factorial 5))
120

set!macro

Mutates a thread-local dynamic-var binding to the given value. The target must be a dynamic var with an enclosing (binding ...) form on the call stack; without one, throws \

Source
(defmacro set!
  "Mutates a thread-local dynamic-var binding to the given value.
   The target must be a dynamic var with an enclosing (binding ...)
   form on the call stack; without one, throws \"Can't
   change/establish root binding\". Matches Clojure JVM's contract
   for set! on Vars. Returns the new value.

   The JVM-only field-mutation shape (set! (.-field obj) val) is not
   supported -- mino has no JVM fields."
  [target value]
  (when-not (symbol? target)
    (throw "set!: first argument must be a symbol naming a dynamic var"))
  (list 'set-dyn-binding! (list 'quote target) value))
(set! *set-bang-test* 1)
1

commentmacro

Ignores body, returns nil.

Source
(defmacro comment "Ignores body, returns nil." [& body] nil)

if-somemacro

Binds the result of expr, evaluates then if non-nil, else otherwise.

Source
(defmacro if-some
  "Binds the result of expr, evaluates then if non-nil, else
   otherwise."
  [bindings then & else]
  (when-not (and (vector? bindings) (= 2 (count bindings)))
    (throw "if-some requires a binding vector of exactly one symbol/expr pair"))
  (let [sym  (first bindings)
        expr (first (rest bindings))
        g    (gensym)]
    (if (seq else)
      `(let [~g ~expr]
         (if (not (nil? ~g)) (let [~sym ~g] ~then) ~(first else)))
      `(let [~g ~expr]
         (if (not (nil? ~g)) (let [~sym ~g] ~then))))))
(if-some [x false] x :none)
false
(if-some [x nil] x :none)
:none
(if-some [x 42] x :none)
42

when-somemacro

Binds the result of expr, evaluates body if non-nil.

Source
(defmacro when-some
  "Binds the result of expr, evaluates body if non-nil."
  [bindings & body]
  (when-not (and (vector? bindings) (= 2 (count bindings)))
    (throw "when-some requires a binding vector of exactly one symbol/expr pair"))
  (let [sym  (first bindings)
        expr (first (rest bindings))
        g    (gensym)]
    `(let [~g ~expr]
       (when (not (nil? ~g)) (let [~sym ~g] ~@body)))))
(when-some [x 0] (str "got " x))
"got 0"
(when-some [x nil] :nope)
nil

^:privatefunction

Source
(def ^:private -lock-first first)

^:privatefunction

Source
(def ^:private -lock-next  next)

get-infunction

Returns the value in a nested associative structure at the given key path.

Source
(def get-in
  "Returns the value in a nested associative structure at the given
   key path."
  (let [step (fn step [m ks nf sentinel]
               (if ks
                 (let [v (get m (first ks) sentinel)]
                   (if (= v sentinel)
                     nf
                     (step v (next ks) nf sentinel)))
                 m))]
    (fn
      ([m ks]     (reduce get m ks))
      ([m ks nf]  (step m (seq ks) nf (gensym))))))
(meta (get-in y [:guh]))
xm
(meta (get-in y [1]))
xm
(get-in {:a {:b 42}} [:a :b])
42

as->macro

Binds expr to sym, then threads it through each form where sym can appear anywhere.

Source
(defmacro as->
  "Binds expr to sym, then threads it through each form where sym can
   appear anywhere."
  [expr sym & forms]
  (if (= 0 (count forms))
    expr
    `(let [~sym ~expr]
       (as-> ~(first forms) ~sym ~@(rest forms)))))
(as-> 1 x (+ x 2) (* x 3))
9

cond->macro

Thread-first through forms whose tests are truthy.

Source
(defmacro cond->
  "Thread-first through forms whose tests are truthy."
  [expr & clauses]
  (if (< (count clauses) 2)
    expr
    (let [g    (gensym)
          test (first clauses)
          step (first (rest clauses))]
      `(let [~g ~expr]
         (cond-> (if ~test
                   ~(if (cons? step)
                      `(~(first step) ~g ~@(rest step))
                      `(~step ~g))
                   ~g)
                 ~@(rest (rest clauses)))))))
(cond-> 1 true inc false (* 100) true (* 2))
4

cond->>macro

Thread-last through forms whose tests are truthy.

Source
(defmacro cond->>
  "Thread-last through forms whose tests are truthy."
  [expr & clauses]
  (if (< (count clauses) 2)
    expr
    (let [g    (gensym)
          test (first clauses)
          step (first (rest clauses))]
      `(let [~g ~expr]
         (cond->> (if ~test
                    ~(if (cons? step)
                       `(~(first step) ~@(rest step) ~g)
                       `(~step ~g))
                    ~g)
                  ~@(rest (rest clauses)))))))
(cond->> [4 3 2 1] true (sort <))
'(1 2 3 4)

some->macro

Thread-first through forms, short-circuiting on nil.

Source
(defmacro some->
  "Thread-first through forms, short-circuiting on nil."
  [expr & forms]
  (if (= 0 (count forms))
    expr
    (let [g (gensym)]
      `(let [~g ~expr]
         (if (nil? ~g)
           nil
           (some-> (-> ~g ~(first forms)) ~@(rest forms)))))))
(some-> {:a 1} :a inc)
2
(some-> 0 inc)
1
(some-> 1 inc inc)
3

some->>macro

Thread-last through forms, short-circuiting on nil.

Source
(defmacro some->>
  "Thread-last through forms, short-circuiting on nil."
  [expr & forms]
  (if (= 0 (count forms))
    expr
    (let [g (gensym)]
      `(let [~g ~expr]
         (if (nil? ~g)
           nil
           (some->> (->> ~g ~(first forms)) ~@(rest forms)))))))
(some->> [1 2 3] (map inc))
'(2 3 4)
(some->> [1 2 3] (reduce +))
6
(some->> [1 2 3] (map inc) (filter even?))
'(2 4)

dotomacro

Evaluates x, then calls each form with x as the first argument. Returns x.

Source
(defmacro doto
  "Evaluates x, then calls each form with x as the first argument.
   Returns x."
  [x & forms]
  (let [g       (gensym)
        stmts   (apply list (map (fn [f] (if (cons? f)
                                            `(~(first f) ~g ~@(rest f))
                                            `(~f ~g)))
                                  forms))]
    `(let [~g ~x]
       ~@stmts
       ~g)))

dotimesmacro

Evaluates body n times with sym bound to 0 through n-1.

Source
(defmacro dotimes
  "Evaluates body n times with sym bound to 0 through n-1."
  [bindings & body]
  (let [sym (first bindings)
        n   (first (rest bindings))
        gn  (gensym)
        go  (gensym)]
    ;; Named fn so the body can self-reference; mino's let is
    ;; sequential (init exprs do not see their own binding) per
    ;; Clojure semantics, so a plain `(let [go (fn [...] (go))])`
    ;; would leave (go) unbound at fn-body evaluation.
    `(let [~gn ~n
           ~go (fn ~go [~sym]
                 (when (< ~sym ~gn)
                   ~@body
                   (~go (inc ~sym))))]
       (~go 0))))
(dotimes [n 1] n)
nil
(let [a (atom 0)]
(dotimes [n 3] (swap! a inc))
@a)
3
(let [a (atom [])]
(dotimes [n 3] (swap! a conj n))
@a)
[0 1 2]

whilemacro

Repeatedly evaluates body while test is truthy.

Source
(defmacro while
  "Repeatedly evaluates body while test is truthy."
  [test & body]
  (let [go (gensym)]
    `(let [~go (fn ~go [] (when ~test ~@body (~go)))]
       (~go))))

doseqmacro

Iterates over collections for side effects, evaluating body once per binding combination, and returns nil. Supports nested bindings and the modifier clauses :let, :when, and :while -- the same surface clojure.core/doseq exposes: :let [name expr ...] introduces locals visible to inner clauses :when expr skips this iteration when expr is falsy :while expr halts all iteration when expr is falsy Implementation note: :while needs to stop the outer loop too, not just the inner one. We encode that with a shared 'stop' atom that the outer driver inspects each iteration. Without it, an outer infinite seq paired with a later :while would never terminate.

Source
(defmacro doseq
  "Iterates over collections for side effects, evaluating body once
   per binding combination, and returns nil. Supports nested
   bindings and the modifier clauses :let, :when, and :while -- the
   same surface clojure.core/doseq exposes:
     :let [name expr ...]  introduces locals visible to inner clauses
     :when expr            skips this iteration when expr is falsy
     :while expr           halts all iteration when expr is falsy

  Implementation note: :while needs to stop the outer loop too, not
  just the inner one. We encode that with a shared 'stop' atom that
  the outer driver inspects each iteration. Without it, an outer
  infinite seq paired with a later :while would never terminate."
  [bindings & body]
  (let [stop-sym (gensym "doseq-stop_")]
    (letfn [(emit [bindings]
              (cond
                (zero? (count bindings))
                `(do ~@body nil)

                (= :let (first bindings))
                (let [bs            (first (rest bindings))
                      rest-bindings (into [] (drop 2 bindings))]
                  `(let ~bs ~(emit rest-bindings)))

                (= :when (first bindings))
                (let [pred          (first (rest bindings))
                      rest-bindings (into [] (drop 2 bindings))]
                  `(when ~pred ~(emit rest-bindings)))

                (= :while (first bindings))
                (let [pred          (first (rest bindings))
                      rest-bindings (into [] (drop 2 bindings))]
                  `(if ~pred
                     ~(emit rest-bindings)
                     (do (reset! ~stop-sym true) nil)))

                ;; Plain binding sym/coll. Drive a recursive loop.
                :else
                (let [sym           (first bindings)
                      coll          (first (rest bindings))
                      rest-bindings (into [] (drop 2 bindings))
                      gs            (gensym)
                      go            (gensym)]
                  ;; Use a named fn so the body can self-reference;
                  ;; mino's `let` follows Clojure's sequential
                  ;; semantics where init exprs do not see their own
                  ;; binding, so a plain `(let [go (fn [...] (go))])`
                  ;; would leave (go) unbound at fn-body evaluation.
                  `(let [~go (fn ~go [~gs]
                               (when (and ~gs (not @~stop-sym))
                                 (let [~sym (first ~gs)]
                                   ~(emit rest-bindings)
                                   (~go (next ~gs)))))]
                     (~go (seq ~coll))))))]
      `(let [~stop-sym (atom false)]
         ~(emit bindings)
         nil))))

timemacro

Evaluates body, prints elapsed time, and returns the result.

Source
(defmacro time
  "Evaluates body, prints elapsed time, and returns the result."
  [& body]
  (let [start  (gensym)
        result (gensym)]
    `(let [~start  (time-ms)
           ~result (do ~@body)]
       (println (str "Elapsed time: " (- (time-ms) ~start) " ms"))
       ~result)))

^:privatefunction

Source
(def ^:private prim-re-find    re-find)

^:privatefunction

Source
(def ^:private prim-re-matches re-matches)

condpmacro

Takes a binary predicate, an expression, and clauses. Returns the first clause value where (pred test-val expr) is truthy. The special clause shape `test :>> result-fn` calls `(result-fn p)` on the truthy pred-result whenever `(pred test expr)` is truthy.

Source
(defmacro condp
  "Takes a binary predicate, an expression, and clauses. Returns the
   first clause value where (pred test-val expr) is truthy. The
   special clause shape `test :>> result-fn` calls `(result-fn p)`
   on the truthy pred-result whenever `(pred test expr)` is truthy."
  [pred expr & clauses]
  (let [gpred (gensym "pred__")
        gexpr (gensym "expr__")
        build (fn build [cls]
                (cond
                  (empty? cls) nil
                  (= (count cls) 1) (first cls)
                  (and (>= (count cls) 3) (= (second cls) :>>))
                  (let [test   (first cls)
                        res-fn (nth cls 2)
                        more   (drop 3 cls)
                        gp     (gensym "p__")]
                    `(if-let [~gp (~gpred ~test ~gexpr)]
                       (~res-fn ~gp)
                       ~(build more)))
                  :else
                  (let [test (first cls)
                        then (second cls)
                        more (drop 2 cls)]
                    `(if (~gpred ~test ~gexpr)
                       ~then
                       ~(build more)))))]
    `(let [~gpred ~pred ~gexpr ~expr]
       ~(build clauses))))
(condp = 1  1 :pass  2 :fail)
:pass
(condp = 1  2 :fail  1 :pass)
:pass
(condp = 1  2 :fail  :pass)
:pass

casemacro

Dispatches on the value of expr. Matches constants in pairs, with an optional default.

Source
(defmacro case
  "Dispatches on the value of expr. Matches constants in pairs, with
   an optional default."
  [expr & clauses]
  (let [gexpr   (gensym)
        quote-c (fn [c]
                  (cond
                    (nil? c)     nil
                    (keyword? c) c
                    (number? c)  c
                    (string? c)  c
                    (= c true)  true
                    (= c false) false
                    :else        (list 'quote c)))
        match1  (fn [g c]
                  (if (cons? c)
                    ;; Multi-match list: (a b c) => (or (= g 'a) (= g 'b) ...)
                    (apply list 'or (map (fn [v] (list '= g (quote-c v))) c))
                    (list '= g (quote-c c))))
        build   (fn build [cls]
                  (if (< (count cls) 2)
                    (if (= (count cls) 1)
                      (first cls)
                      (list 'throw (list 'ex-info "no matching case" {})))
                    (list 'if (match1 gexpr (first cls))
                          (first (rest cls))
                          (build (rest (rest cls))))))]
    `(let [~gexpr ~expr]
       ~(build clauses))))
(case nil nil :nil :default)
:nil
(case 999 1 :one :default)
:default
(case :b :a 1 :b 2 :c 3)
2

formacro

List comprehension. Takes binding vectors and body, returns a lazy sequence.

Source
(defmacro for
  "List comprehension. Takes binding vectors and body, returns a lazy
   sequence."
  [bindings & body]
  (let [sym  (first bindings)
        coll (first (rest bindings))
        rest-bindings (drop 2 bindings)]
    (if (empty? rest-bindings)
      ;; Last binding pair: produce elements
      `(map (fn [~sym] ~@body) ~coll)
      (let [modifier (first rest-bindings)]
        (cond
          ;; :when filter
          (= modifier :when)
          (let [pred (first (rest rest-bindings))
                remaining (into [] (drop 2 rest-bindings))]
            (if (empty? remaining)
              `(map (fn [~sym] ~@body)
                    (filter (fn [~sym] ~pred) ~coll))
              `(for ~(into [sym (list 'filter (list 'fn [sym] pred) coll)]
                           remaining)
                 ~@body)))
          ;; :while stop iteration
          (= modifier :while)
          (let [pred (first (rest rest-bindings))
                remaining (into [] (drop 2 rest-bindings))]
            (if (empty? remaining)
              `(map (fn [~sym] ~@body)
                    (take-while (fn [~sym] ~pred) ~coll))
              `(for ~(into [sym (list 'take-while (list 'fn [sym] pred) coll)]
                           remaining)
                 ~@body)))
          ;; :let local bindings
          (= modifier :let)
          (let [let-bindings (first (rest rest-bindings))
                after-let (into [] (drop 2 rest-bindings))
                ;; Collect :when/:while modifiers that follow the :let
                next-mod (first after-let)]
            (cond
              (empty? after-let)
              `(map (fn [~sym]
                      (let ~let-bindings ~@body))
                    ~coll)
              ;; :when after :let on same binding
              (= next-mod :when)
              (let [pred (first (rest after-let))
                    remaining (into [] (drop 2 after-let))]
                (if (empty? remaining)
                  `(map (fn [~sym]
                          (let ~let-bindings ~@body))
                        (filter (fn [~sym]
                                  (let ~let-bindings ~pred))
                                ~coll))
                  `(mapcat (fn [~sym]
                             (let ~let-bindings
                               (when ~pred
                                 (for ~remaining ~@body))))
                           ~coll)))
              ;; :while after :let on same binding
              (= next-mod :while)
              (let [pred (first (rest after-let))
                    remaining (into [] (drop 2 after-let))]
                (if (empty? remaining)
                  `(map (fn [~sym]
                          (let ~let-bindings ~@body))
                        (take-while (fn [~sym]
                                      (let ~let-bindings ~pred))
                                    ~coll))
                  `(mapcat (fn [~sym]
                             (let ~let-bindings
                               (for ~remaining ~@body)))
                           (take-while (fn [~sym]
                                         (let ~let-bindings ~pred))
                                       ~coll))))
              ;; Other bindings after :let
              :else
              `(mapcat (fn [~sym]
                         (let ~let-bindings
                           (for ~after-let ~@body)))
                       ~coll)))
          ;; Another binding pair: nested iteration
          :else
          `(mapcat (fn [~sym]
                     (for ~(into [] rest-bindings) ~@body))
                   ~coll))))))
(into [] (for (x [1 2 3 4 5]) (* x x)))
[1 4 9 16 25]
(into [] (for (x [1 2 3 4 5] :when (even? x)) (* x x)))
[4 16]
(into [] (for [x [1 2 3]] (* x x)))
[1 4 9]

futuremacro

Takes a body of expressions and yields a future object that will evaluate the body in another thread, blocking on deref until the value is available. Throws :mino/unsupported when host threads are not granted; see mino-thread-limit.

Source
(defmacro future
  "Takes a body of expressions and yields a future object that will
  evaluate the body in another thread, blocking on deref until the
  value is available. Throws :mino/unsupported when host threads are
  not granted; see mino-thread-limit."
  [& body]
  `(if (<= (mino-thread-limit) 1)
     (throw (ex-info (mino-no-grant-msg "future")
                     {:mino/unsupported :future
                      :mino/thread-limit (mino-thread-limit)}))
     (future-call (fn [] ~@body))))

threadmacro

Executes the body in another thread, returning a future-like value that can be deref'd. Shares the same worker pool as future. Throws :mino/unsupported when host threads are not granted.

Source
(defmacro thread
  "Executes the body in another thread, returning a future-like value
  that can be deref'd. Shares the same worker pool as future. Throws
  :mino/unsupported when host threads are not granted."
  [& body]
  `(if (<= (mino-thread-limit) 1)
     (throw (ex-info (mino-no-grant-msg "thread")
                     {:mino/unsupported :thread
                      :mino/thread-limit (mino-thread-limit)}))
     (future-call (fn [] ~@body))))

pvaluesmacro

Returns a lazy sequence of the values of the exprs, which are evaluated in parallel via pcalls. Mirrors clojure.core/pvalues.

Source
(defmacro pvalues
  "Returns a lazy sequence of the values of the exprs, which are
   evaluated in parallel via pcalls. Mirrors clojure.core/pvalues."
  [& exprs]
  `(pcalls ~@(map (fn [e] `(fn [] ~e)) exprs)))
(vec (pvalues 1 (+ 2 3) :x))
[1 5 :x]

defprotocolmacro

Defines a protocol with the given method signatures.

Source
(defmacro defprotocol
  "Defines a protocol with the given method signatures."
  [proto-name & methods]
  (let [pname (name proto-name)]
    (letfn [(method-meta [m]
              (let [mname  (first m)
                    params (second m)]
                {:mname mname
                 :params params
                 :dsym (symbol (str pname "--" (name mname)))}))
            (method-defn [mi]
              (list 'defn (:mname mi) (:params mi)
                    (apply list 'protocol-dispatch
                           (:dsym mi)
                           (str (:mname mi))
                           (:params mi))))]
      (let [methods     (remove string? methods)
            methods     (loop [ms methods result []]
                          (if (or (nil? ms) (empty? ms))
                            result
                            (if (keyword? (first ms))
                              (recur (drop 2 ms) result)
                              (recur (rest ms)
                                     (conj result (first ms))))))
            method-info (into [] (map method-meta methods))
            atom-defs   (into [] (map (fn [mi]
                                        (list 'def (:dsym mi)
                                              '(atom {})))
                                      method-info))
            fn-defs     (into [] (map method-defn method-info))
            proto-map   (into {} (map (fn [mi]
                                        [(keyword (str (:mname mi)))
                                         (:dsym mi)])
                                      method-info))
            proto-def   (list 'def proto-name
                              {:name pname :methods proto-map})
            all-forms   (concat atom-defs fn-defs
                                (list proto-def))]
        (apply list 'do all-forms)))))

extend-typemacro

Extends a protocol with method implementations for the given type.

Source
(defmacro extend-type
  "Extends a protocol with method implementations for the given type."
  [type-kw & specs]
  (let [groups (loop [remaining specs
                      result []
                      cur-proto nil
                      cur-methods []]
                 (if (empty? remaining)
                   (if cur-proto
                     (conj result [cur-proto cur-methods])
                     result)
                   (let [item (first remaining)]
                     (if (and (symbol? item) (not (list? item)))
                       (recur (rest remaining)
                              (if cur-proto
                                (conj result [cur-proto cur-methods])
                                result)
                              item [])
                       (recur (rest remaining) result cur-proto
                              (conj cur-methods item))))))
        swaps (mapcat (fn [[proto methods]]
                (let [pname (name proto)
                      pns   (namespace proto)]
                  (map (fn [m]
                    (let [mname (first m)
                          params (second m)
                          body (drop 2 m)]
                      (when-not (symbol? mname)
                        (throw (str "extend-type: method must start with a"
                                    " name symbol, got: " (pr-str m))))
                      (when-not (vector? params)
                        (throw (str "extend-type: method " (pr-str mname)
                                    " must have a params vector, got: "
                                    (pr-str params))))
                      (let [dsym (symbol pns (str pname "--" (name mname)))]
                        (list 'swap! dsym 'assoc type-kw
                              (apply list 'fn params body)))))
                   methods)))
              groups)]
    (apply list 'do (vec swaps))))

extend-protocolmacro

Extends a protocol with implementations for multiple types.

Source
(defmacro extend-protocol
  "Extends a protocol with implementations for multiple types."
  [proto & specs]
  (let [groups (partition-protocol-specs specs)
        forms (into [] (map (fn [group]
                              (apply list 'extend-type
                                     (first group) proto
                                     (rest group)))
                            groups))]
    (apply list 'do forms)))

internal-reducefunction

Source
(def internal-reduce reduce)

internal-reduce-kvfunction

Source
(def internal-reduce-kv reduce-kv)

^:privatefunction

Source
(def ^:private global-hierarchy
  (atom {:parents {} :ancestors {} :descendants {}}))

^:privatefunction

Source
(def ^:private hierarchy-version (atom 0))

defmultimacro

Defines a multimethod with the given dispatch function.

Source
(defmacro defmulti
  "Defines a multimethod with the given dispatch function."
  [mm-name & options]
  (let [options  (if (string? (first options)) (rest options) options)
        options  (if (map? (first options)) (rest options) options)
        dispatch-fn-form (first options)
        kw-opts  (apply hash-map (rest options))
        default-val (get kw-opts :default :default)]
    (list 'def mm-name
          (list 'create-multimethod dispatch-fn-form default-val))))

defmethodmacro

Defines a method for a multimethod.

Source
(defmacro defmethod
  "Defines a method for a multimethod."
  [mm-name dispatch-val & fn-tail]
  (list 'register-method mm-name dispatch-val
        (apply list 'fn fn-tail)))

with-out-strmacro

Evaluates body with *out* bound to a fresh string-collecting atom, and returns the accumulated string.

Source
(defmacro with-out-str
  "Evaluates body with *out* bound to a fresh string-collecting atom,
  and returns the accumulated string."
  [& body]
  `(let [a# (atom "")]
     (binding [*out* a#]
       ~@body)
     (deref a#)))
(with-out-str (println "hi"))
"hi\n"
(with-out-str (prn [1 2 3]))
"[1 2 3]\n"
(with-out-str (print 1 2 3))
"1 2 3"

with-in-strmacro

Evaluates body with *in* bound to a string-cursor atom holding s. read and read-line consume from the cursor as forms or lines are taken; the body's value is returned.

Source
(defmacro with-in-str
  "Evaluates body with *in* bound to a string-cursor atom holding
  s. read and read-line consume from the cursor as forms or lines
  are taken; the body's value is returned."
  [s & body]
  `(let [a# (atom ~s)]
     (binding [*in* a#]
       ~@body)))
(with-in-str "hello\nworld" (read-line))
"hello"
(with-in-str "a\nb\nc"
[(read-line) (read-line) (read-line) (read-line)])
["a" "b" "c" nil]
(with-in-str "no-newline" (read-line))
"no-newline"

with-openmacro

Binds resources, evaluates body, then closes each resource.

Source
(defmacro with-open
  "Binds resources, evaluates body, then closes each resource."
  [bindings & body]
  (if (empty? bindings)
    `(do ~@body)
    (let [name (first bindings)
          init (nth bindings 1)
          rest-bindings (drop 2 bindings)]
      `(let [~name ~init]
         (try
           (with-open ~(into [] rest-bindings) ~@body)
           (finally (close ~name)))))))

^:privatefunction

Source
(def ^:private prim-into into)

*clojure-version*function

Source
(def *clojure-version* {:major 1 :minor 11 :incremental 0 :qualifier nil})

^:dynamicfunction

Source
(def ^:dynamic *compile-path* nil)

^:dynamicfunction

Source
(def ^:dynamic *source-path*  "NO_SOURCE_PATH")

^:dynamicfunction

Source
(def ^:dynamic *compile-files* false)

^:dynamicfunction

Source
(def ^:dynamic *warn-on-reflection* false)

^:dynamicfunction

Source
(def ^:dynamic *unchecked-math* false)

assertmacro

Source
(defmacro assert
  ([x] (list 'when-not x (list 'throw "Assert failed")))
  ([x msg] (list 'when-not x (list 'throw msg))))

^:dynamicfunction

Source
(def ^:dynamic *assert*
  "Controls assertion compilation. When false, `assert` is a no-op.
   Defaults to true."
  true)

^:dynamicfunction

Source
(def ^:dynamic *print-length*
  "Maximum number of items printed in a single collection (vector,
   list, map, set, chunk, chunked-cons). nil means no limit (the
   default). The remainder is replaced with `...`. Resolved once per
   top-level pr / prn / print / println / pr-str call; nested
   collections share the same limit."
  nil)

^:dynamicfunction

Source
(def ^:dynamic *print-level*
  "Maximum nesting depth printed. A collection found at depth >= this
   limit is replaced with `#`. nil means no limit (the default).
   Resolved once per top-level pr / print call."
  nil)

^:dynamicfunction

Source
(def ^:dynamic *print-readably*
  "When true (the default), strings are emitted with their quote
   characters and characters with their escape form so the printed
   output round-trips through the reader. When false, strings and
   characters print their underlying bytes — pr/prn behave like
   print/println. Resolved once per top-level pr / print call."
  true)

^:dynamicfunction

Source
(def ^:dynamic *print-meta*
  "When true, every value carrying non-nil metadata is printed with
   its meta map prefixed as `^{...} `. When false (the default), meta
   is silent. Resolved once per top-level pr / print call."
  false)

^:dynamicfunction

Source
(def ^:dynamic *print-dup*
  "When true, the printer emits forms a reader can reconstruct
   exactly. mino's built-in record / collection / scalar prints are
   already reader-roundtrip-compatible, so the flag is currently an
   information channel for user-installed print-method implementations
   that branch on dup vs. non-dup output. Default false."
  false)

^:dynamicfunction

Source
(def ^:dynamic *print-namespace-maps*
  "When true, a map whose keys are keywords (or symbols) sharing a
   common non-empty namespace is printed as `#:ns{:k1 v1, :k2 v2}`
   instead of `{:ns/k1 v1, :ns/k2 v2}`. Default false."
  false)

^:dynamicfunction

Source
(def ^:dynamic *flush-on-newline*
  "When true (the default), the I/O sink behind `*out*` is flushed
   automatically after any write that contains a newline. When false,
   the sink stays buffered so consecutive writes coalesce."
  true)

^:dynamicfunction

Source
(def ^:dynamic *math-context*
  "Precision/rounding-mode for bigdec division. nil means exact-or-
   throw (mirrors java.math.BigDecimal.divide without MathContext).
   When set, the value is a map of {:precision N :rounding-mode K}
   where N is a positive integer and K is one of: :half-up (default),
   :down, :up, :floor, :ceiling, :half-down, :half-even, :unnecessary.
   :unnecessary throws when rounding would change the value (mirrors
   JVM's ArithmeticException). Resolved by mino_bigdec_div on each
   call."
  nil)

with-precisionmacro

Sets *math-context* to {:precision precision :rounding-mode mode} around body. The keyword :rounding takes the next form as a rounding-mode keyword (e.g. (with-precision 5 :rounding :half-up (/ 1M 3M))). Without :rounding, the mode defaults to :half-up.

Source
(defmacro with-precision
  "Sets *math-context* to {:precision precision :rounding-mode mode}
  around body. The keyword :rounding takes the next form as a
  rounding-mode keyword (e.g. (with-precision 5 :rounding :half-up
  (/ 1M 3M))). Without :rounding, the mode defaults to :half-up."
  [precision & body]
  (let [has-rounding? (and (seq body) (= :rounding (first body)))
        mode          (if has-rounding? (second body) :half-up)
        actual-body   (if has-rounding? (drop 2 body) body)]
    `(binding [*math-context* {:precision ~precision
                               :rounding-mode ~mode}]
       ~@actual-body)))
(with-precision 5 (/ 1M 3M))
0.33333M
(with-precision 3 (/ 2M 3M))
0.667M
(with-precision 2 (/ 25M 33M))
0.76M

^:privatefunction

Source
(def ^:private special-symbols-set
  '#{& . case* catch def deftype* do finally fn fn* if let let* letfn*
     loop loop* new ns quote recur refer-clojure set! throw try var
     binding lazy-seq})

let-bitsmacro

Destructure-shaped binding over a bytes value. (let-bits [bytes-val [sym & opts] ...] body...) See documentation in core.clj just above this definition.

Source
(defmacro let-bits
  "Destructure-shaped binding over a bytes value.
   (let-bits [bytes-val [sym & opts] ...] body...)
   See documentation in core.clj just above this definition."
  [bindings & body]
  (when-not (vector? bindings)
    (throw (ex-info "let-bits: first form must be a binding vector"
                    {:got bindings})))
  (let [packet-form (first bindings)
        segments    (rest bindings)
        packet-sym  (gensym "packet__")
        total-sym   (gensym "totalbits__")]
    (loop [segs   segments
           offset 0
           pairs  []]
      (if (empty? segs)
        `(let [~packet-sym ~packet-form
               ~total-sym  (* 8 (count ~packet-sym))
               ~@(mapcat identity pairs)]
           ~@body)
        (let [seg (first segs)]
          (when-not (vector? seg)
            (throw (ex-info "let-bits: each segment must be a vector"
                            {:got seg})))
          (let [sym         (first seg)
                opts        (rest seg)
                opts-map    (apply hash-map opts)
                seg-size    (bits-let-seg-size opts-map)
                type        (or (:type opts-map) :int)
                endian      (:endian opts-map)
                signed?     (:signed? opts-map)
                size-form   (if (= seg-size :rest)
                              `(- ~total-sym ~offset)
                              seg-size)
                next-offset (if (= seg-size :rest)
                              total-sym
                              (+ offset seg-size))
                bg          `(bits-get ~packet-sym
                                       :offset ~offset
                                       :size   ~size-form
                                       :type   ~type
                                       ~@(when endian [:endian endian])
                                       ~@(when (some? signed?) [:signed? signed?]))]
            (recur (rest segs)
                   next-offset
                   (conj pairs [sym bg]))))))))

^:privatefunction

Source
(def ^:private uuid-hex-pattern #"[0-9a-fA-F]+")

with-bindingsmacro

Takes a map of var->value pairs. Installs the bindings, executes body, and pops the bindings in a finally clause.

Source
(defmacro with-bindings
  "Takes a map of var->value pairs. Installs the bindings, executes
   body, and pops the bindings in a finally clause."
  [binding-map & body]
  `(let [vmap# ~binding-map]
     (push-thread-bindings vmap#)
     (try
       ~@body
       (finally
         (pop-thread-bindings)))))

bound-fnmacro

Returns a function defined by the given fntail, which will install the same bindings in effect as in the thread at the time bound-fn was called.

Source
(defmacro bound-fn
  "Returns a function defined by the given fntail, which will install
   the same bindings in effect as in the thread at the time bound-fn
   was called."
  [& fntail]
  `(bound-fn* (fn ~@fntail)))

^:privatefunction

Source
(def ^:private tap-fns (atom #{}))

EMPTYfunction

Source
(def EMPTY (-empty-queue))

defrecordmacro

Defines a record type Name with the given fields and optional inline protocol specs. Establishes: Name — the MINO_TYPE value (used by extend-type and instance? as the dispatch key) ->Name — positional constructor: (->Name f1 f2 ...) returns a record value map->Name — map constructor: (map->Name {:f1 v1 :f2 v2}) reads declared fields from the map; non-field keys land in ext. Fields must be a vector of symbols; they are stored as keywords on the type. Specs follow the same shape as extend-type: protocol-name followed by one or more (method [args] body) forms. Inside an inline protocol method body, field names resolve as locals bound to (get this :field) -- matches Clojure's defrecord contract so (defrecord R [a b] IFoo (bar [this] (+ a b))) works without writing (:a this) / (:b this) by hand.

Source
(defmacro defrecord
  "Defines a record type Name with the given fields and optional
   inline protocol specs. Establishes:
     Name       — the MINO_TYPE value (used by extend-type and
                  instance? as the dispatch key)
     ->Name     — positional constructor: (->Name f1 f2 ...) returns
                  a record value
     map->Name  — map constructor: (map->Name {:f1 v1 :f2 v2}) reads
                  declared fields from the map; non-field keys land
                  in ext.

   Fields must be a vector of symbols; they are stored as keywords
   on the type. Specs follow the same shape as extend-type:
   protocol-name followed by one or more (method [args] body) forms.

   Inside an inline protocol method body, field names resolve as
   locals bound to (get this :field) -- matches Clojure's defrecord
   contract so (defrecord R [a b] IFoo (bar [this] (+ a b))) works
   without writing (:a this) / (:b this) by hand."
  [name fields & specs]
  (when-not (vector? fields)
    (throw (str "defrecord: fields must be a vector, got: "
                (pr-str fields))))
  (let [ns-str     (str (ns-name *ns*))
        name-str   (str name)
        ctor       (symbol (str "->" name))
        map-ctor   (symbol (str "map->" name))
        field-kws  (mapv (fn [f] (keyword (str f))) fields)
        bind-meth  (fn [m] (defrecord-bind-fields-in-method fields m))
        wrap-spec  (fn [s]
                     (if (and (or (list? s) (cons? s))
                              (seq s)
                              (symbol? (first s))
                              (or (list? (rest s)) (cons? (rest s)))
                              (vector? (first (rest s))))
                       (bind-meth s)
                       s))
        specs*     (mapv wrap-spec specs)
        forms      [(list 'def name (list 'defrecord* ns-str name-str field-kws))
                    (list 'defn ctor fields
                          (list 'record* name (vec fields)))
                    (list 'defn map-ctor ['m]
                          (list 'record-from-map name 'm))]]
    (apply list 'do (if (seq specs*)
                      (conj forms (apply list 'extend-type name specs*))
                      forms))))

deftypemacro

Alias for defrecord. mino has no separate JVM-class layer to expose, so the deftype/defrecord distinction collapses; values created either way are real types with map-isomorphic behaviour.

Source
(defmacro deftype
  "Alias for defrecord. mino has no separate JVM-class layer to
   expose, so the deftype/defrecord distinction collapses; values
   created either way are real types with map-isomorphic behaviour."
  [name fields & specs]
  (when-not (vector? fields)
    (throw (str "deftype: fields must be a vector, got: "
                (pr-str fields))))
  (apply list 'defrecord name fields specs))

reifymacro

Returns an instance of a fresh anonymous record type that satisfies the named protocols. Each reify form generates one type at expansion time; repeated invocations of the form share that type, so (= (type r1) (type r2)) is true for two values produced by the same reify form.

Source
(defmacro reify
  "Returns an instance of a fresh anonymous record type that
   satisfies the named protocols. Each reify form generates one
   type at expansion time; repeated invocations of the form share
   that type, so (= (type r1) (type r2)) is true for two values
   produced by the same reify form."
  [& specs]
  (let [ns-str   (str (ns-name *ns*))
        sym      (gensym "reify_T_")
        name-str (str sym)
        T        (gensym "T")]
    (list 'let [T (list 'defrecord* ns-str name-str [])]
          (apply list 'extend-type T specs)
          (list 'record* T []))))

proxymacro

Source
(defmacro proxy [& _]
  (throw (ex-info
           "proxy is not supported on mino — there is no JVM to subclass"
           {:mino/unsupported :proxy})))

gen-classmacro

Source
(defmacro gen-class [& _]
  (throw (ex-info
           (str "gen-class is not supported on mino — there is no"
                " JVM to compile against")
           {:mino/unsupported :gen-class})))

definterfacemacro

Source
(defmacro definterface [& _]
  (throw (ex-info
           (str "definterface is not supported on mino — use"
                " defprotocol instead")
           {:mino/unsupported :definterface})))

importmacro

Source
(defmacro import [& _]
  (throw (ex-info
           (str "Java import is not supported on mino — there are no"
                " Java classes to import")
           {:mino/unsupported :import})))
(eval (read-string "(do (ns-unmap *ns* 'Object) (def o1 (resolve 'Object)) (import '[java.lang Object]) (def o2 (resolve 'Object)) [(some? o1) (some? o2)])"))
[false true]

with-redefsmacro

Temporarily rebinds the root bindings of vars while body executes, restoring them in a finally clause. Bindings is a vector of var-name/value pairs. The temp-value exprs are evaluated in parallel BEFORE any rebind fires, so a later binding-value that names an earlier-listed var sees that var's pre-redef value (matching Clojure JVM).

Source
(defmacro with-redefs
  "Temporarily rebinds the root bindings of vars while body executes, restoring
   them in a finally clause. Bindings is a vector of var-name/value pairs.

   The temp-value exprs are evaluated in parallel BEFORE any rebind fires, so a
   later binding-value that names an earlier-listed var sees that var's
   pre-redef value (matching Clojure JVM)."
  [bindings & body]
  (let [pairs    (partition 2 bindings)
        var-syms (map first pairs)
        new-vals (map second pairs)
        olds     (map (fn [_] (gensym "old")) pairs)
        news     (map (fn [_] (gensym "new")) pairs)
        sets     (map (fn [v new-sym]
                        (list 'alter-var-root (list 'var v)
                              (list 'fn ['_] new-sym)))
                      var-syms news)
        restores (map (fn [v old]
                        (list 'alter-var-root (list 'var v)
                              (list 'fn ['_] old)))
                      var-syms olds)
        finally-form (apply list 'finally restores)
        try-form     (apply list 'try (concat sets body (list finally-form)))]
    (list 'let
          (vec (concat
                 (mapcat (fn [old v] [old (list 'deref (list 'var v))])
                         olds var-syms)
                 (mapcat (fn [new-sym new-val] [new-sym new-val])
                         news new-vals)))
          try-form)))

with-local-varsmacro

Binds names to fresh, lexically-scoped vars holding init values. Within body the names refer to vars: read with @name, mutate with (var-set name val). The vars are interned in the current namespace under gensym'd suffixes so they don't collide with named defs.

Source
(defmacro with-local-vars
  "Binds names to fresh, lexically-scoped vars holding init values.
   Within body the names refer to vars: read with @name, mutate with
   (var-set name val). The vars are interned in the current namespace
   under gensym'd suffixes so they don't collide with named defs."
  [bindings & body]
  (let [pairs (partition 2 bindings)
        let-pairs (mapcat (fn [pair]
                            (let [n    (first pair)
                                  init (first (rest pair))]
                              [n (list 'intern '*ns*
                                       (list 'gensym (str (name n) "__lv__"))
                                       init)]))
                          pairs)]
    (apply list 'let (vec let-pairs) body)))

I/O primitives

Available only when the host installs MINO_CAP_IO (via mino_install(S, env, MINO_CAP_IO | ...)). Not present in sandboxed environments.

chdir

Changes the current working directory. Capability: :io

exit

Exits the process with the given status code. Capability: :io

file-seq

Returns a vector of all file paths under a directory, recursively. Capability: :io

gc!

Forces a full garbage collection. Returns nil. Capability: :io

gc-stats

Returns a map of GC statistics. Capability: :io

getcwd

Returns the current working directory. Capability: :io

getenv

Returns the value of an environment variable, or nil. Capability: :io

nano-time

Returns monotonic wall-clock time in nanoseconds. Capability: :io

newline

Writes a line separator to *out*.

(newline)
nil
(with-out-str (newline))
"\n"

pr

Prints the arguments readably to *out*, without a trailing newline.

(pr 1 2 3)
nil
(with-out-str (pr ^{:type :shouty} {:s "hi"}))
"<SHOUTY>"

print

Prints the arguments space-separated to *out*, without a trailing newline.

(print "io-test-print")
nil
(with-out-str (print 1 2 3))
"1 2 3"
(with-out-str (print "a") (println "b"))
"ab\n"

println

Prints the arguments to *out*, followed by a newline.

(println "io-test-println")
nil
(with-out-str (println "hi"))
"hi\n"
(with-out-str (print "a") (println "b"))
"ab\n"

prn

Prints the arguments readably to *out*, followed by a newline.

(prn 1 2 3)
nil
(with-out-str (prn [1 2 3]))
"[1 2 3]\n"
(with-out-str (prn ^{:type :shouty} {:s "hi"}))
"<SHOUTY>\n"

slurp

Reads the entire contents of a file as a string. Capability: :io

(slurp f)
"hello"
(slurp f)
"42"

spit

Writes the string content to a file. Capability: :io

time-ms

Returns the current time in milliseconds. Capability: :io

core.async

CSP channels and go blocks. Available after (require '[clojure.core.async :as a]).

^:privatedef

Source
(def ^:private BUF-KIND-NONE     0)

^:privatedef

Source
(def ^:private BUF-KIND-FIXED    1)

^:privatedef

Source
(def ^:private BUF-KIND-DROPPING 2)

^:privatedef

Source
(def ^:private BUF-KIND-SLIDING  3)

^:privatedef

Source
(def ^:private BUF-KIND-PROMISE  4)

bufferfn

Fixed-size buffer descriptor. Pairs with chan.

Source
(defn buffer
  "Fixed-size buffer descriptor. Pairs with chan."
  [n]
  {:kind :buf :buf-kind :fixed :capacity n})

dropping-bufferfn

Dropping buffer descriptor. New values are silently dropped once full.

Source
(defn dropping-buffer
  "Dropping buffer descriptor. New values are silently dropped once full."
  [n]
  {:kind :buf :buf-kind :dropping :capacity n})

sliding-bufferfn

Sliding buffer descriptor. Oldest value is evicted when full.

Source
(defn sliding-buffer
  "Sliding buffer descriptor. Oldest value is evicted when full."
  [n]
  {:kind :buf :buf-kind :sliding :capacity n})

chanfn

Source
(defn chan
  "Create a channel.
     ()                           -- unbuffered
     (buf-or-n)                   -- buffered (int or buffer descriptor)
     (buf-or-n xform)             -- buffered with a transducer
     (buf-or-n xform ex-handler)  -- also with an exception handler"
  ([] (chan nil nil nil))
  ([buf-or-n] (chan buf-or-n nil nil))
  ([buf-or-n xform] (chan buf-or-n xform nil))
  ([buf-or-n xform ex-handler]
   (let [[kind cap]
         (cond
           (nil? buf-or-n)                       [BUF-KIND-NONE 0]
           (and (integer? buf-or-n)
                (zero? buf-or-n))                [BUF-KIND-NONE 0]
           (integer? buf-or-n)                   [BUF-KIND-FIXED buf-or-n]
           (buffer? buf-or-n)                    [(buf-kind->int (:buf-kind buf-or-n))
                                                  (:capacity buf-or-n)]
           :else
           (throw (str "chan: buffer-or-n must be nil, a non-negative "
                       "integer, or a buffer")))
         ch (chan-new kind cap nil nil)]
     (when xform
       ;; Wrap the user xform around an `add-fn` reducing step whose
       ;; effect is to push outputs into the channel's buffer.
       (let [add-fn (fn
                      ([result] result)
                      ([result input]
                       (chan-buf-add ch input)
                       result))
             rf     (xform add-fn)]
         (chan-set-xform ch rf ex-handler)))
     ch)))

promise-chanfn

Create a promise channel. The first value latches; all takers see it.

Source
(defn promise-chan
  "Create a promise channel. The first value latches; all takers see it."
  ([] (promise-chan nil nil))
  ([xform] (promise-chan xform nil))
  ([xform ex-handler]
   (let [ch (chan-new BUF-KIND-PROMISE 1 nil nil)]
     (when xform
       (let [add-fn (fn
                      ([result] result)
                      ([result input]
                       (chan-buf-add ch input)
                       result))
             rf     (xform add-fn)]
         (chan-set-xform ch rf ex-handler)))
     ch)))

closed?fn

True if the channel is closed.

Source
(defn closed?
  "True if the channel is closed."
  [ch]
  (chan-closed? ch))

offer!fn

Put val on ch if immediately possible. Returns true/false. Never enqueues as pending.

Source
(defn offer!
  "Put val on ch if immediately possible. Returns true/false. Never
   enqueues as pending."
  [ch val]
  (when (nil? val)
    (throw "cannot put nil on a channel"))
  (cond
    (chan-closed? ch)
    false

    (chan-get-xform ch)
    (do (run-xform-step! ch val) true)

    :else
    (chan-offer ch val)))

poll!fn

Take from ch if immediately available. Returns the value or nil.

Source
(defn poll!
  "Take from ch if immediately available. Returns the value or nil."
  [ch]
  (chan-poll ch))

put!fn

Source
(defn put!
  "Asynchronously put val on ch. Optional cb receives true (delivered) or
   false (channel closed). Returns nil."
  ([ch val] (put! ch val nil))
  ([ch val cb]
   (when (nil? val)
     (throw "cannot put nil on a channel"))
   (cond
     (chan-closed? ch)
     (do (when cb (async-sched-enqueue* cb false)) nil)

     (chan-get-xform ch)
     (do (run-xform-step! ch val)
         (when cb (async-sched-enqueue* cb (if (chan-closed? ch) false true)))
         nil)

     :else
     (do (chan-put ch val cb) nil))))

take!fn

Asynchronously take from ch. cb receives the value, or nil if ch is closed and empty. Returns nil.

Source
(defn take!
  "Asynchronously take from ch. cb receives the value, or nil if ch is
   closed and empty. Returns nil."
  [ch cb]
  (chan-take ch cb)
  nil)

close!fn

Close the channel. Pending takers receive nil; pending putters false. Buffered values still flow to waiting takers.

Source
(defn close!
  "Close the channel. Pending takers receive nil; pending putters false.
   Buffered values still flow to waiting takers."
  [ch]
  (when-not (chan-closed? ch)
    ;; If the channel has a transducer, run its completion arity to
    ;; flush any held state into the buffer before closing.
    (when-let [rf (chan-get-xform ch)]
      (try (rf nil) (catch _ nil))
      (chan-flush-buf-to-takers ch))
    (chan-close ch)
    ;; Drain wake-callbacks the close pushed onto the scheduler so
    ;; blocking <!! / >!! callers see the resolution before any other
    ;; producer's wake has a chance to leave them parked.
    (drain!))
  nil)

chan?fn

True if x is a channel.

Source
(defn chan?
  "True if x is a channel."
  [x]
  (chan-instance? x))

alts!fn

Source
(defn alts!
  "Atomically complete one of several channel operations.
   ops is a vector. Each element is either a channel (take) or
   [ch val] (put). opts (kwargs or a single map):
     :priority true  -- try in order (no shuffle)
     :default val    -- return [val :default] if no op is ready
   Returns [result channel]."
  [ops & opts]
  (let [opts-m (alts-opts-map opts)
        result (atom nil)
        cb     (fn [r] (reset! result r))]
    (alts-start ops opts-m cb)
    (drain!)
    @result))

alts-callbackfn

Source
(defn alts-callback
  "Callback-style alts matching the old C alts* contract. cb fires with
   [val ch]. If an op completes immediately, cb is scheduled; otherwise
   ops register pending on a shared flag and cb fires when one wins.
   Returns 1 (matches the old C contract)."
  [ops opts cb]
  (alts-start ops opts cb)
  1)

alt!macro

Source
(defmacro alt!
  "Sugar for alts! plus a cond over which clause completed. See the
  alts! docstring for the underlying contract.

  Each pair: `(channel-or-vec result)` or `:default expr` or
  `:priority bool`. Result may be:
    - a plain expression
    - `([v] body...)` to bind the value
    - `([v c] body...)` to bind value and channel

  Returns the result expression for the winning clause, or the
  :default expression when no port was ready (and :default was given)."
  [& clauses]
  (let [pairs       (partition 2 clauses)
        priority?   (some (fn [[k _]] (= k :priority)) pairs)
        priority-v  (when priority? (second (first (filter #(= :priority (first %)) pairs))))
        default?    (some (fn [[k _]] (= k :default)) pairs)
        default-expr (when default? (second (first (filter #(= :default (first %)) pairs))))
        port-pairs  (remove (fn [[k _]] (or (= k :priority) (= k :default))) pairs)
        port-vec    (vec (map first port-pairs))
        rsym (gensym "alt-result-")
        vsym (gensym "alt-val-")
        csym (gensym "alt-ch-")
        bind-result (fn [clause]
                      (if (and (seq? clause) (vector? (first clause)))
                        (let [bvec (first clause)
                              body (rest clause)]
                          (cond
                            (= 1 (count bvec))
                            `(let [~(first bvec) ~vsym] ~@body)
                            (= 2 (count bvec))
                            `(let [~(first bvec) ~vsym
                                   ~(second bvec) ~csym] ~@body)
                            :else clause))
                        clause))
        cond-clauses
        (mapcat (fn [[op result]]
                  (let [port (if (vector? op) (first op) op)]
                    [`(identical? ~csym ~port) (bind-result result)]))
                port-pairs)
        opts (concat (when priority? [:priority priority-v])
                     (when default? [:default :alt!-default-fired]))]
    `(let [~rsym (alts! ~port-vec ~@opts)
           ~vsym (first ~rsym)
           ~csym (second ~rsym)]
       (cond ~@cond-clauses
             ~@(when default?
                 [`(identical? ~csym :default) default-expr])
             :else nil))))

>!macro

Source
(defmacro >!
  "puts a val into port. nil values are not allowed. Must be called
   inside a (go ...) block. Will park if no buffer space available."
  [_port _val]
  `(throw "(>! port val) used not in (go ...) block"))

<!macro

Source
(defmacro <!
  "takes a val from port. Must be called inside a (go ...) block.
   Will park if nothing is available."
  [_port]
  `(throw "(<! port) used not in (go ...) block"))

timeoutfn

Returns a channel that closes after ms milliseconds.

Source
(defn timeout
  "Returns a channel that closes after ms milliseconds."
  [ms]
  (let [ch (chan)]
    (async-schedule-timer* ms (fn [_] (close! ch)))
    ch))

gomacro

Asynchronously executes the body in a lightweight state machine. Returns a channel which will receive the result of the body when it completes. <! and >! are parking operations that suspend the go block until the channel operation completes.

Source
(defmacro go
  "Asynchronously executes the body in a lightweight state machine.
   Returns a channel which will receive the result of the body
   when it completes. <! and >! are parking operations that
   suspend the go block until the channel operation completes."
  [& body]
  (let [result-ch-sym (gensym "go_result_")
        machine-sym   (gensym "go_fn_")
        expanded      (go-expand-if (cons 'do body))
        states        (go-transform expanded result-ch-sym)]
    `(let [~result-ch-sym (chan* (buf-fixed* 1))
           ~machine-sym   ~(go-emit-machine states result-ch-sym)]
       (~machine-sym 0 nil)
       ~result-ch-sym)))

go-loopmacro

Source
(defmacro go-loop
  "Like (go (loop bindings body...))."
  [bindings & body]
  `(go (loop ~bindings ~@(seq body))))

<!!fn

Source
(defn <!!
  "Blocking take from a channel. When host threads are granted, parks
   the calling thread until a value is available (or the channel
   closes). Without threads, drains the scheduler in a loop and throws
   if no progress can be made. Returns the taken value (nil if closed)."
  [ch]
  (let [p (promise)]
    (take! ch (fn [v] (deliver p [v])))
    (drain!)
    (cond
      (realized? p)
      (first @p)

      (> (mino-thread-limit) 1)
      (first @p)

      :else
      (if (drain-loop! (fn [] (realized? p)))
        (first @p)
        (throw "<!!: would deadlock -- no producer for this channel")))))

>!!fn

Blocking put onto a channel. When host threads are granted, parks the calling thread until the put completes. Without threads, drains the scheduler in a loop and throws if no progress can be made. Returns true if successful, false if the channel is closed.

Source
(defn >!!
  "Blocking put onto a channel. When host threads are granted, parks
   the calling thread until the put completes. Without threads, drains
   the scheduler in a loop and throws if no progress can be made.
   Returns true if successful, false if the channel is closed."
  [ch val]
  (let [p (promise)]
    (put! ch val (fn [v] (deliver p [v])))
    (drain!)
    (cond
      (realized? p)
      (first @p)

      (> (mino-thread-limit) 1)
      (first @p)

      :else
      (if (drain-loop! (fn [] (realized? p)))
        (first @p)
        (throw ">!!: would deadlock -- no consumer for this channel")))))

alts!!fn

Blocking version of alts!. When host threads are granted, parks the calling thread until one operation completes. Without threads, drains the scheduler in a loop and throws on no progress. Returns [val ch].

Source
(defn alts!!
  "Blocking version of alts!. When host threads are granted, parks the
   calling thread until one operation completes. Without threads,
   drains the scheduler in a loop and throws on no progress.
   Returns [val ch]."
  ([ops] (alts!! ops {}))
  ([ops opts]
   (let [p (promise)]
     (alts* ops opts (fn [v] (deliver p [v])))
     (drain!)
     (cond
       (realized? p)
       (first @p)

       (> (mino-thread-limit) 1)
       (first @p)

       :else
       (if (drain-loop! (fn [] (realized? p)))
         (first @p)
         (throw "alts!!: would deadlock -- no operations can complete"))))))

pipefn

Source
(defn pipe
  "Takes elements from the from channel and puts them on the to channel.
   Closes the to channel when from is exhausted (unless close? is false).
   Returns the to channel."
  ([from to] (pipe from to true))
  ([from to close?]
   (let [do-pipe (fn do-pipe [v]
                   (if (nil? v)
                     (when close? (close! to))
                     (do (put! to v)
                         (take! from do-pipe))))]
     (take! from do-pipe))
   to))

onto-chan!fn

Source
(defn onto-chan!
  "Puts each element of coll onto the channel ch, then closes ch
   (unless close? is false). Returns ch."
  ([ch coll] (onto-chan! ch coll true))
  ([ch coll close?]
   (doseq [v coll]
     (put! ch v))
   (when close? (close! ch))
   ch))

to-chan!fn

Creates and returns a channel that receives all elements of coll, then closes.

Source
(defn to-chan!
  "Creates and returns a channel that receives all elements of coll,
   then closes."
  [coll]
  (let [ch (chan (count coll))]
    (onto-chan! ch coll)))

intofn

Returns a channel containing the single result of reducing all values from ch into init using conj.

Source
(defn into
  "Returns a channel containing the single result of reducing
   all values from ch into init using conj."
  [init ch]
  (let [result-ch (chan 1)
        acc       (atom init)
        do-take   (fn do-take [v]
                    (if (nil? v)
                      (do (put! result-ch @acc)
                          (close! result-ch))
                      (do (swap! acc conj v)
                          (take! ch do-take))))]
    (take! ch do-take)
    result-ch))

mergefn

Takes a collection of source channels and returns a channel that contains all values from all source channels. Closes when all source channels are closed.

Source
(defn merge
  "Takes a collection of source channels and returns a channel that
   contains all values from all source channels. Closes when all
   source channels are closed."
  ([chs] (merge chs nil))
  ([chs buf-or-n]
   (let [out       (if buf-or-n (chan buf-or-n) (chan))
         remaining (atom (count chs))]
     (if (= 0 (count chs))
       (close! out)
       (doseq [ch chs]
         (let [do-take (fn do-take [v]
                         (if (nil? v)
                           (when (= 0 (swap! remaining dec))
                             (close! out))
                           (do (put! out v)
                               (take! ch do-take))))]
           (take! ch do-take))))
     out)))

reducefn

Asynchronously reduces ch with f, starting from init. Returns a channel that yields the final accumulated value when ch closes. Behaves like clojure.core/reduce but without the 2-arg form: in a channel context the seeded form is the only one that makes sense.

Source
(defn reduce
  "Asynchronously reduces ch with f, starting from init. Returns a
   channel that yields the final accumulated value when ch closes.
   Behaves like clojure.core/reduce but without the 2-arg form: in a
   channel context the seeded form is the only one that makes sense."
  [f init ch]
  (let [result-ch (chan 1)
        acc       (atom init)
        do-take   (fn do-take [v]
                    (cond
                      (nil? v)
                      (do (put! result-ch @acc)
                          (close! result-ch))

                      (reduced? @acc)
                      (do (put! result-ch (deref @acc))
                          (close! result-ch))

                      :else
                      (do (swap! acc f v)
                          (if (reduced? @acc)
                            (do (put! result-ch (deref @acc))
                                (close! result-ch))
                            (take! ch do-take)))))]
    (take! ch do-take)
    result-ch))

transducefn

Asynchronously reduces ch with the transducer xform applied to f, starting from init. Returns a channel that yields the result of the completing arity of the transducing reducer.

Source
(defn transduce
  "Asynchronously reduces ch with the transducer xform applied to f,
   starting from init. Returns a channel that yields the result of
   the completing arity of the transducing reducer."
  [xform f init ch]
  (let [xf        (xform f)
        result-ch (chan 1)
        acc       (atom init)
        finish    (fn finish []
                    (let [final (xf @acc)]
                      (put! result-ch final)
                      (close! result-ch)))
        do-take   (fn do-take [v]
                    (if (nil? v)
                      (finish)
                      (let [next-acc (xf @acc v)]
                        (reset! acc next-acc)
                        (if (reduced? next-acc)
                          (do (reset! acc (deref next-acc))
                              (finish))
                          (take! ch do-take)))))]
    (take! ch do-take)
    result-ch))

splitfn

Source
(defn split
  "Splits ch into two channels by predicate p. Values for which (p v)
   is truthy go to the first channel; the rest go to the second.
   Returns a vector [t-ch f-ch]. Both channels close when ch closes.
   Optional t-buf and f-buf set buffer sizes (or buffer instances)."
  ([p ch] (split p ch nil nil))
  ([p ch t-buf f-buf]
   (let [t-ch    (if t-buf (chan t-buf) (chan))
         f-ch    (if f-buf (chan f-buf) (chan))
         do-take (fn do-take [v]
                   (if (nil? v)
                     (do (close! t-ch)
                         (close! f-ch))
                     (let [out (if (p v) t-ch f-ch)]
                       (put! out v)
                       (take! ch do-take))))]
     (take! ch do-take)
     [t-ch f-ch])))

partition-byfn

Source
(defn partition-by
  "Returns a channel of vectors of consecutive items from ch with the
   same (f item). Closes when ch closes; flushes the in-progress
   partition before closing."
  ([f ch] (partition-by f ch nil))
  ([f ch buf-or-n]
   (let [out      (if buf-or-n (chan buf-or-n) (chan))
         current  (atom [])
         last-key (atom ::none)
         flush!   (fn []
                    (when (seq @current)
                      (put! out @current)
                      (reset! current [])))
         do-take  (fn do-take [v]
                    (if (nil? v)
                      (do (flush!)
                          (close! out))
                      (let [k (f v)]
                        (if (or (= ::none @last-key) (= k @last-key))
                          (do (swap! current conj v)
                              (reset! last-key k)
                              (take! ch do-take))
                          (do (flush!)
                              (swap! current conj v)
                              (reset! last-key k)
                              (take! ch do-take))))))]
     (take! ch do-take)
     out)))

multfn

Source
(defn mult
  "Creates a mult on source channel ch. Values taken from ch are
   distributed to all tapped channels. Returns a mult handle (map)."
  [ch]
  (let [taps   (atom #{})
        m      {:ch ch :taps taps}
        do-take (fn do-take [v]
                  (if (nil? v)
                    (doseq [t @taps]
                      (close! t))
                    (do (doseq [t @taps]
                          (put! t v))
                        (take! ch do-take))))]
    (take! ch do-take)
    m))

tapfn

Registers channel ch as a tap on mult m. Returns ch.

Source
(defn tap
  "Registers channel ch as a tap on mult m. Returns ch."
  ([m ch] (tap m ch true))
  ([m ch close?]
   (swap! (:taps m) conj ch)
   ch))

untapfn

Unregisters channel ch from mult m.

Source
(defn untap
  "Unregisters channel ch from mult m."
  [m ch]
  (swap! (:taps m) disj ch)
  nil)

pubfn

Source
(defn pub
  "Creates a pub on source channel ch with a topic-fn that extracts
   the topic from each value. Returns a pub handle (map)."
  [ch topic-fn]
  (let [subs    (atom {})
        p       {:ch ch :topic-fn topic-fn :subs subs}
        do-take (fn do-take [v]
                  (if (nil? v)
                    (doseq [[_ chs] @subs]
                      (doseq [c chs]
                        (close! c)))
                    (let [topic (topic-fn v)
                          chs   (get @subs topic)]
                      (when chs
                        (doseq [c chs]
                          (put! c v)))
                      (take! ch do-take))))]
    (take! ch do-take)
    p))

subfn

Subscribes channel ch to topic on pub p. Returns ch.

Source
(defn sub
  "Subscribes channel ch to topic on pub p. Returns ch."
  ([p topic ch] (sub p topic ch true))
  ([p topic ch close?]
   (swap! (:subs p) update topic
     (fn [chs] (conj (or chs #{}) ch)))
   ch))

unsubfn

Unsubscribes channel ch from topic on pub p.

Source
(defn unsub
  "Unsubscribes channel ch from topic on pub p."
  [p topic ch]
  (swap! (:subs p) update topic
    (fn [chs] (disj (or chs #{}) ch)))
  nil)

unsub-allfn

Unsubscribes all channels from pub p, or all channels from a specific topic if provided.

Source
(defn unsub-all
  "Unsubscribes all channels from pub p, or all channels from a
   specific topic if provided."
  ([p] (reset! (:subs p) {}) nil)
  ([p topic]
   (swap! (:subs p) dissoc topic)
   nil))

mixfn

Source
(defn mix
  "Creates a mix on the output channel out. Multiple input channels can
   be added with admix. Each input channel can have modes:
   :solo, :mute, :pause (all default false).
   solo-mode controls what happens to non-soloed channels: :mute or :pause."
  [out]
  {:out out
   :state (atom {:channels {} :solo-mode :mute})})

admixfn

Adds ch as an input to the mix. Starts reading from it. Always reads from the channel while it is in the mix; paused/muted values are consumed but not forwarded.

Source
(defn admix
  "Adds ch as an input to the mix. Starts reading from it.
   Always reads from the channel while it is in the mix; paused/muted
   values are consumed but not forwarded."
  [m ch]
  (swap! (:state m) update :channels assoc ch
         {:solo false :mute false :pause false})
  (let [do-read (fn do-read [v]
                  (let [s @(:state m)]
                    (if (nil? v)
                      ;; Channel closed: remove from mix
                      (swap! (:state m) update :channels dissoc ch)
                      (do
                        (when (mix-should-pass? s ch)
                          (put! (:out m) v))
                        ;; Continue reading while still in mix
                        (when (get (:channels @(:state m)) ch)
                          (take! ch do-read))))))]
    (take! ch do-read))
  nil)

unmixfn

Removes ch from the mix.

Source
(defn unmix
  "Removes ch from the mix."
  [m ch]
  (swap! (:state m) update :channels dissoc ch)
  nil)

unmix-allfn

Removes all inputs from the mix.

Source
(defn unmix-all
  "Removes all inputs from the mix."
  [m]
  (swap! (:state m) assoc :channels {})
  nil)

togglefn

Sets modes on channels in the mix. state-map is {ch {:solo bool :mute bool :pause bool}}.

Source
(defn toggle
  "Sets modes on channels in the mix.
   state-map is {ch {:solo bool :mute bool :pause bool}}."
  [m state-map]
  (doseq [entry state-map]
    (let [ch    (key entry)
          modes (val entry)]
      (swap! (:state m) update :channels
        (fn [channels]
          (if (get channels ch)
            (update channels ch (fn [old] (clojure.core/into old modes)))
            channels)))))
  nil)

solo-modefn

Sets the solo mode for the mix. mode is :mute or :pause.

Source
(defn solo-mode
  "Sets the solo mode for the mix. mode is :mute or :pause."
  [m mode]
  (swap! (:state m) assoc :solo-mode mode)
  nil)

pipelinefn

Source
(defn pipeline
  "Takes items from the from channel, applies xf to each (using n
   parallel go blocks), and puts results on the to channel.
   Closes to when from is exhausted (unless close? is false).
   Preserves input ordering regardless of worker completion order.

   ex-handler, when supplied, is invoked with any exception thrown by
   xf; its return value is used as the replacement output (nil drops)."
  ([n to xf from] (pipeline n to xf from true nil))
  ([n to xf from close?] (pipeline n to xf from close? nil))
  ([n to xf from close? ex-handler]
   (let [jobs    (chan n)
         results (chan n)
         done    (atom 0)
         apply-xf (fn [v]
                    (if ex-handler
                      (try (xf v)
                           (catch e (ex-handler e)))
                      (xf v)))]
     ;; Feed: for each input, create a result channel, send [val res-ch]
     ;; to workers, and send res-ch to collector (in order).
     ;; Uses callbacks to wait for puts, preventing stalls when channels fill.
     (let [feeder (fn feeder [v]
                    (if (nil? v)
                      (close! jobs)
                      (let [res-ch (chan 1)]
                        (put! jobs [v res-ch]
                          (fn [_] (put! results res-ch
                                    (fn [_] (take! from feeder))))))))]
       (take! from feeder))
     ;; Workers: take [val res-ch], apply xf, put result on res-ch
     (dotimes [_ n]
       (let [worker (fn worker [job]
                      (if (nil? job)
                        (when (= n (swap! done inc))
                          (close! results))
                        (let [v      (first job)
                              res-ch (second job)
                              out    (apply-xf v)]
                          (when (some? out)
                            (put! res-ch out))
                          (close! res-ch)
                          (take! jobs worker))))]
         (take! jobs worker)))
     ;; Collector: take res-chs in order, drain each to output
     (let [collector (fn collector [res-ch]
                       (if (nil? res-ch)
                         (when close? (close! to))
                         (let [drain (fn drain [v]
                                       (if (nil? v)
                                         (take! results collector)
                                         (do (put! to v)
                                             (take! res-ch drain))))]
                           (take! res-ch drain))))]
       (take! results collector))
     to)))

pipeline-asyncfn

Like pipeline, but af is an async function that takes [val result-ch]. af should put results on result-ch and close it when done. Preserves input ordering regardless of worker completion order.

Source
(defn pipeline-async
  "Like pipeline, but af is an async function that takes [val result-ch].
   af should put results on result-ch and close it when done.
   Preserves input ordering regardless of worker completion order."
  ([n to af from] (pipeline-async n to af from true))
  ([n to af from close?]
   (let [jobs    (chan n)
         results (chan n)
         done    (atom 0)]
     ;; Feed: for each input, create a result channel, send [val res-ch]
     ;; to workers, and send res-ch to collector (in order).
     ;; Uses callbacks to wait for puts, preventing stalls when channels fill.
     (let [feeder (fn feeder [v]
                    (if (nil? v)
                      (close! jobs)
                      (let [res-ch (chan 1)]
                        (put! jobs [v res-ch]
                          (fn [_] (put! results res-ch
                                    (fn [_] (take! from feeder))))))))]
       (take! from feeder))
     ;; Workers: take [val res-ch], call af which puts results on res-ch
     (dotimes [_ n]
       (let [worker (fn worker [job]
                      (if (nil? job)
                        (when (= n (swap! done inc))
                          (close! results))
                        (let [v      (first job)
                              res-ch (second job)]
                          (af v res-ch)
                          (take! jobs worker))))]
         (take! jobs worker)))
     ;; Collector: take res-chs in order, drain each to output
     (let [collector (fn collector [res-ch]
                       (if (nil? res-ch)
                         (when close? (close! to))
                         (let [drain (fn drain [v]
                                       (if (nil? v)
                                         (take! results collector)
                                         (do (put! to v)
                                             (take! res-ch drain))))]
                           (take! res-ch drain))))]
       (take! results collector))
     to)))

pipeline-blockingdef

Source
(def pipeline-blocking pipeline)