Skip to main content

core

Jump to function (506)

%#

(% dividend divisor)

Alias for rem. Returns the truncated remainder of dividend / divisor. Result has the same sign as dividend.

Example:

(% 11 2) ; => 1

*#

(* & xs)

Returns the product of all elements in xs. All elements in xs must be numbers. If xs is empty, return 1.

*'#

(*' & xs)

Auto-promoting variant of *. Integer results are returned as BigInt; floats and rationals pass through unchanged.

Example:

(*' 2 3) ; => 6N

**#

(** a x)

Return a to the power of x.

*assert*#

Controls whether assert expands to a runtime check. When logical false at macroexpansion time, assert expands to nil and performs no runtime check, matching Clojure's compile-time *assert* semantics. Defaults to true. To disable globally, set the core binding before compilation via PHP: \Phel::addDefinition("phel\\core", "*assert*", false).

*build-mode*#

*file*#

*file*

Returns the path of the current source file.

Example:

(println *file*) ; => "/path/to/current/file.phel"

*ns*#

*ns*

Returns the namespace in the current scope.

Example:

(println *ns*) ; => "my-app.core"

*program*#

The script path or namespace being executed.

+#

(+ & xs)

Returns the sum of all elements in xs. All elements xs must be numbers. If xs is empty, return 0.

+'#

(+' & xs)

Auto-promoting variant of +. Integer results are returned as BigInt so callers get explicit promotion semantics; floats and rationals pass through unchanged. Equivalent to + for overflow protection (Phel's + already auto-promotes on overflow), kept for .cljc interop.

Example:

(+' 1 2) ; => 3N

-#

(- & xs)

Returns the difference of all elements in xs. If xs is empty, return 0. If xs has one element, return the negative value of that element.

-'#

(-' & xs)

Auto-promoting variant of -. Integer results are returned as BigInt; floats and rationals pass through unchanged.

Example:

(-' 5 2) ; => 3N

->#

(-> x & forms)

Threads the expr through the forms. Inserts x as the second item in the first form, making a list of it if it is not a list already. If there are more forms, insert the first form as the second item in the second form, etc.

->>#

(->> x & forms)

Threads the expr through the forms. Inserts x as the last item in the first form, making a list of it if it is not a list already. If there are more forms, insert the first form as the last item in the second form, etc.

->closure#

(->closure f)

Converts a Phel function to a PHP Closure. Many PHP libraries (AMPHP, ReactPHP) type-hint \Closure and reject Phel's AbstractFn even though it is callable. This bridges the gap.

Example:

(->closure (fn [x] (* x 2)))

/#

(/ & xs)

Returns the nominator divided by all the denominators. If xs is empty, returns 1. If xs has one value, returns the reciprocal of x.

Integer division with a non-zero remainder returns a Ratio (e.g. (/ 1 2) => 1/2). Use (/ 1.0 2) or (double ...) for float division.

<#

(< a & more)

Checks if each argument is strictly less than the following argument.

Example:

(< 1 2 3 4) ; => true

<=#

(<= a & more)

Checks if each argument is less than or equal to the following argument. Returns a boolean.

<=>#

(<=> a b)

Alias for the spaceship PHP operator in ascending order. Returns an int. Dispatches on Ratio and BigInt so numeric ordering stays correct for those types.

=#

(= a & more)

Checks if all values are equal (value equality, not identity).

Example:

(= [1 2 3] [1 2 3]) ; => true

==#

(== a & more)

Numeric equality comparison. Returns true if all arguments have the same numeric value regardless of type (e.g. int vs float); throws on non-numeric arguments. Unlike =, which is value-and-type-strict, == treats 1 and 1.0 as equal, matching Clojure's clojure.core/==.

Example:

(== 1 1.0) ; => true

>#

(> a & more)

Checks if each argument is strictly greater than the following argument.

Example:

(> 4 3 2 1) ; => true

>=#

(>= a & more)

Checks if each argument is greater than or equal to the following argument. Returns a boolean.

>=<#

(>=< a b)

Alias for the spaceship PHP operator in descending order. Returns an int.

NAN#

Constant for Not a Number (NAN) values.

NaN?#

(NaN? x)

Checks if x is not a number. Alias for nan?, matching Clojure's NaN?.

abs#

(abs x)

Returns the absolute value of x. Throws InvalidArgumentException if x is not a number; PHP's permissive abs(null) => 0 / abs("abc") coercions are rejected.

Example:

(abs -5) ; => 5

aclone#

(aclone arr)

Returns a shallow copy of a PHP array. The returned array is a distinct value, mutating the copy via php/aset does not affect the original, and vice versa. Matches Clojure's aclone for .cljc interop; raises InvalidArgumentException on non-array inputs since Phel's persistent collections are already immutable and don't need cloning.

Example:

(aclone (object-array 3)) ; => a fresh PHP array [nil, nil, nil]

add-tap#

(add-tap f)

Registers f as a tap. Every call to tap> invokes each registered tap with the tapped value. Returns nil.

Example:

(add-tap println)
(tap> 42) ; prints 42

add-watch#

(add-watch variable key f)

Adds a watch function to a variable. The watch fn is called when the variable changes with four arguments: key, ref, old-value, new-value.

Example:

(add-watch my-var :logger (fn [key ref old new] (println old "->" new)))

aget#

(aget arr & indices)

Returns the value at index in a PHP array. With multiple indices, accesses nested arrays: (aget arr i j) is (aget (aget arr i) j). Matches Clojure's aget for .cljc interop.

Example:

(aget (php/array 10 20 30) 1) ; => 20

alength#

(alength arr)

Returns the number of elements in a PHP array. Matches Clojure's alength for .cljc interop; raises InvalidArgumentException on non-array inputs (use count for collections).

Example:

(alength (int-array 3)) ; => 3

all?#

(all? pred coll)

Returns true if predicate is true for every element in collection, false otherwise.

Example:

(all? even? [2 4 6 8]) ; => true

alter-meta!#

(alter-meta! r f & args)

Replaces the metadata on r with (apply f current-meta args). Works on Var handles (mutates per-var metadata, surviving subsequent def redefinitions) and on atoms (mutates the atom's own meta map). Returns the new metadata map.

Example:

(alter-meta! #'my-var assoc :tag :int)

alter-var-root#

(alter-var-root v f & args)

Replaces the root binding of v with (apply f current-root args). Returns the new root value. v must be a Var; pass an atom and you get a clear error pointing at swap! instead.

Example:

(def counter 0)
(alter-var-root #'counter inc) ; => 1

ancestors#

(ancestors tag)
(ancestors h tag)

Returns the set of all transitive ancestors of tag, or nil. When a hierarchy is provided, consults it; otherwise uses the global hierarchy.

and#

(and & args)

Evaluates expressions left to right, returning the first falsy value or the last value.

Example:

(and true 1 "hello") ; => "hello"

any?#

(any? _)

Returns true given any argument, including nil and false. Mirrors Clojure's clojure.core/any?, useful as a default predicate in spec / validation contexts where every value should be accepted.

Example:

(any? nil) ; => true
(any? 0) ; => true

apply#

(apply f expr*)

Calls the function with the given arguments. The last argument must be a list of values, which are passed as separate arguments, rather than a single list. Apply returns the result of the calling function.

Example:

(apply + [1 2 3]) ; => 6

argv#

Vector of user arguments passed to the script (excludes program name). Use program to get the script path or namespace.

array-map#

Constructs a map from the given key/value pairs. If any keys are equal, later values replace earlier ones, as if by repeated assoc. Phel has no distinct array-map type, so the result is the same persistent map as hash-map, array-map exists for .cljc interop with Clojure sources.

Example:

(array-map :a 1 :b 2) ; => {:a 1 :b 2}

as->#

(as-> expr name & forms)

Binds name to expr, evaluates the first form in the lexical context of that binding, then binds name to that result, repeating for each successive form, returning the result of the last form.

aset#

(aset arr idx & more)

Sets the value at index in a PHP array to val. Returns val. With additional indices, navigates nested arrays before setting: (aset arr i j val) sets index j in (aget arr i). Matches Clojure's aset for .cljc interop. This is a macro because PHP arrays are value types; a function wrapper would mutate a copy rather than the original.

Example:

(let [a (php/array 1 2 3)] (aset a 0 42) (aget a 0)) ; => 42

assert#

(assert expr & [message])

Throws an exception if expr is falsy. Optional message string. Used for precondition checking in application code. When *assert* is logical false at macroexpansion time, assert expands to nil and performs no runtime check.

assoc#

(assoc ds key value & more)

Associates one or more key-value pairs with a collection. Additional key-value pairs beyond the first are applied in order. Throws if an odd number of extra arguments is provided.

Example:

(assoc {:a 1} :b 2) ; => {:a 1 :b 2}
(assoc {:a 1} :b 2 :c 3) ; => {:a 1 :b 2 :c 3}

assoc!#

(assoc! tcoll key value & more)

Associates one or more key-value pairs with a transient collection, mutating it in place. Works on transient hash-maps and transient vectors. Variadic forms apply each key-value pair in order. A trailing key without a value is associated with nil. Raises InvalidArgumentException when tcoll is not a supported transient collection. Matches Clojure's assoc! semantics.

Example:

(persistent! (assoc! (transient {}) :a 1 :b 2)) ; => {:a 1 :b 2}

assoc-in#

(assoc-in ds [k & ks] v)

Associates a value in a nested data structure at the given path.

Creates intermediate maps if they don't exist.

Example:

(assoc-in {:a {:b 1}} [:a :c] 2) ; => {:a {:b 1 :c 2}}

associative?#

(associative? x)

Returns true if x is an associative data structure, false otherwise.

Associative data structures include vectors, hash maps, structs, and PHP arrays (both indexed and associative), matching Clojure's Associative protocol.

Example:

(associative? [1 2 3]) ; => true

async#

(async & body)

Runs body asynchronously in a new fiber. Returns an Amp\Future.

Captures the caller's dynamic bindings and reinstalls them inside the fiber, so bindings established outside async are visible to body (binding conveyance, as in Clojure's future).

Example:

(async (do-something))

atom#

(atom value & opts)

Creates a new atom with the given value.

Atoms provide a way to manage mutable state. Use reset! to set a new value and swap! to update based on the current value.

Optional :meta and :validator keyword arguments may follow the value in any order. The validator is applied to the initial value when set.

Example:

(def counter (atom 0))
(atom 0 :meta {:tag :counter} :validator number?)

atom?#

(atom? x)

Returns true if the given value is an atom.

await#

(await future)

Blocks the current fiber until the Future resolves and returns its value. Accepts either a raw Amp\Future or a Future wrapper.

Example:

(await (async (+ 1 2)))

await-all#

(await-all futures)

Awaits all Futures in the given collection. Returns a vector of results. Accepts a mix of raw Amp\Future and Future wrappers.

Example:

(await-all [(async 1) (async 2)])

await-any#

(await-any futures)

Awaits the first Future to resolve. Returns its value. Accepts a mix of raw Amp\Future and Future wrappers.

Example:

(await-any [(async 1) (async 2)])

bigdec#

(bigdec x)

Coerces x to a Phel\Lang\BigDecimal. Accepts BigDecimal (returned as-is), ints, floats (via the shortest round-trip decimal of the float), BigInt, Ratio (computed via exact decimal division; throws ArithmeticError when the expansion does not terminate, matching (bigdec 1/3)), and numeric strings.

Example:

(bigdec 1.5) ; => 1.5M
(bigdec 1/2) ; => 0.5M
(bigdec "3.14") ; => 3.14M

bigdec?#

(bigdec? x)

Returns true when x is a Phel\Lang\BigDecimal value.

Example:

(bigdec? 1.5M) ; => true

bigint#

(bigint x)

Coerces x to a Phel\Lang\BigInt. Accepts ints, floats (truncated toward zero, rejecting NaN/Inf), numeric strings, and BigInt values.

Example:

(bigint 42) ; => 42N
(bigint 1.9) ; => 1N
(bigint "123") ; => 123N

bigint?#

(bigint? x)

Returns true when x is a Phel\Lang\BigInt value.

Example:

(bigint? (php/:: \Phel\Lang\BigInt (fromInt 1))) ; => true

biginteger#

(biginteger x)

Alias for bigint. Coerces x to a Phel\Lang\BigInt.

Example:

(biginteger 42) ; => 42N

binding#

(binding bindings & body)

Temporarily rebinds dynamic vars while executing body.

Each var in bindings must be tagged ^:dynamic at its def. The rebinding is fiber-local: concurrent fibers observe independent values, and child futures (future, async, future-fiber) inherit the bindings active at their creation.

Throws at runtime if any var in the bindings vector is not :dynamic. To swap a non-dynamic var for the duration of an expression (e.g. mocking in tests), use with-redefs.

bit-and#

(bit-and x y & args)

Bitwise and.

bit-clear#

(bit-clear x n)

Clear bit an index n.

bit-flip#

(bit-flip x n)

Flip bit at index n.

bit-not#

(bit-not x)

Bitwise complement.

bit-or#

(bit-or x y & args)

Bitwise or.

bit-set#

(bit-set x n)

Set bit an index n.

bit-shift-left#

(bit-shift-left x n)

Bitwise shift left.

bit-shift-right#

(bit-shift-right x n)

Bitwise shift right.

bit-test#

(bit-test x n)

Test bit at index n.

bit-xor#

(bit-xor x y & args)

Bitwise xor.

boolean#

(boolean x)

Coerces x to a boolean. Returns false if x is nil or false, true otherwise.

Example:

(boolean nil) ; => false

boolean?#

(boolean? x)

Returns true if x is a boolean, false otherwise.

bound?#

(bound? v)

Returns true when v has a current root binding in the namespace registry. v must be a Var.

Example:

(bound? #'phel.core/map) ; => true

butlast#

(butlast coll)

Returns all but the last item in coll. Returns nil when coll is nil or has fewer than two items.

Example:

(butlast [1 2 3 4]) ; => [1 2 3]
(butlast [0]) ; => nil

byte#

(byte x)

Coerces x to a signed 8-bit integer in the range -128..127. Decimal values are truncated toward zero. Ratio and BigInt values are accepted (truncate toward zero, then range-check). Values outside the range or non-numeric inputs raise InvalidArgumentException. Phel has no dedicated byte type, so the result is a plain PHP int.

Example:

(byte 127) ; => 127
(byte 1.9) ; => 1
(byte -128) ; => -128

canonical-ns#

(canonical-ns ns-str)

Returns the canonical (dot-separated) form of a namespace string. Pass user-supplied namespace strings through this before any registry lookup or write.

Example:

(canonical-ns "phel\core") ; => "phel.core"

case#

(case e & pairs)

Evaluates expression and matches it against constant test values, returning the associated result.

Example:

(case x 1 "one" 2 "two" "other") ; => "one" (when x is 1)

cat#

(cat rf)

A transducer that concatenates the contents of each input into the reduction.

catch#

(catch exception-type exception-name expr*)

Handle exceptions thrown in a try block by matching on the provided exception type. The caught exception is bound to exception-name while evaluating the expressions.

Example:

(try (throw (php/new \Exception "error")) (catch \Exception e (php/-> e (getMessage))))

ceil#

(ceil x)

Returns the smallest integer not less than x. Ints and BigInt values are returned unchanged. Ratios collapse via ceiling division. Floats route through PHP's ceil.

Example:

(ceil 1.2) ; => 2.0
(ceil -1.7) ; => -1.0
(ceil 7/3) ; => 3

char#

(char x)

Coerces x to a single-character string representing the given Unicode code point. Accepts a non-negative integer (the code point, converted via mb_chr) or a single-character string, which is returned as-is. Phel has no dedicated char type, character literals such as \A are already single-character strings, so the result is always a plain string. Matches Clojure's char for .cljc interop; raises InvalidArgumentException on negative ints, non-single-character strings, and all other inputs.

Example:

(char 65) ; => "A"
(char 32) ; => " "
(char \A) ; => "A"

char?#

(char? x)

Returns true if x is a single-character string, false otherwise. Phel has no dedicated character type, character literals such as \A are already single-character strings, so char? is true for any string of length 1 (UTF-8 counted). Matches ClojureScript's char? for .cljc interop; Clojure/JVM's char? tests for the distinct Character type, which does not exist here.

Example:

(char? \A) ; => true
(char? "a") ; => true
(char? "ab") ; => false

class#

(class x)

Returns a Phel\Lang\PhpClass for x. With an object argument returns the class of the object. With a string argument resolves the named class or interface FQN. Throws InvalidArgumentException for any other input.

Example:

(class (php/new \stdClass)) ; => stdClass

class-name#

(class-name c)

Returns the FQN string of c (a Phel\Lang\PhpClass). Leading backslashes are not preserved (e.g. \stdClass becomes stdClass).

Example:

(class-name (class "stdClass")) ; => "stdClass"

class?#

(class? x)

Returns true if x is a Phel\Lang\PhpClass value.

Example:

(class? (class (php/new \stdClass))) ; => true

coerce-in#

(coerce-in v min max)

Returns v if it is in the range, or min if v is less than min, or max if v is greater than max.

coll?#

(coll? x)

Returns true if x is a persistent collection, vector, list, hash-map (including sorted-map), struct, set (including sorted-set), or lazy-seq, and false otherwise. Strings, numbers, nil, booleans, keywords, symbols, and plain PHP arrays are not considered collections, matching Clojure's IPersistentCollection membership.

Example:

(coll? [1 2 3]) ; => true
(coll? "abc") ; => false

comment#

(comment &)

Ignores the body of the comment.

comp#

(comp & fs)

Takes a list of functions and returns a function that is the composition of those functions.

compact#

(compact coll & values)

Returns a lazy sequence with specified values removed from coll. If no values are specified, removes nil values by default.

Example:

(compact [1 nil 2 nil 3]) ; => (1 2 3)

compare#

(compare x y)

Compares x and y, returning a negative integer, zero, or a positive integer when x is less than, equal to, or greater than y.

nil is less than every non-nil value and equal to itself. Throws InvalidArgumentException when x and y come from mutually incomparable categories (e.g. (compare 1 [])).

compile#

(compile form)

Returns the compiled PHP code string for the given form.

complement#

(complement f)

Returns a function that takes the same arguments as f and returns the opposite truth value.

completing#

(completing f & args)

Takes a reducing function f of 2 args and returns a fn suitable for transduce by adding a 1-arity (completion) that calls cf (default: identity).

concat#

(concat & colls)

Concatenates multiple collections into a lazy sequence.

Example:

(concat [1 2] [3 4]) ; => (1 2 3 4)

cond#

(cond & pairs)

Evaluates test/expression pairs, returning the first matching expression.

Example:

(cond (< x 0) "negative" (> x 0) "positive" "zero") ; => "negative", "positive", or "zero" depending on x

cond->#

(cond-> expr & clauses)

Takes an expression and a set of test/form pairs. Threads expr (via ->) through each form for which the corresponding test expression is true. Note that, unlike cond branching, cond-> threading does not short-circuit after the first true test expression.

Example:

(cond-> 1 true inc false (* 42) true (* 3)) ; => 6

cond->>#

(cond->> expr & clauses)

Takes an expression and a set of test/form pairs. Threads expr (via ->>) through each form for which the corresponding test expression is true. Note that, unlike cond branching, cond->> threading does not short-circuit after the first true test expression.

Example:

(cond->> [1 2 3] true (map inc) false (filter odd?)) ; => [2 3 4]

condp#

(condp pred expr & clauses)

Takes a binary predicate, an expression, and a set of clauses. Each clause takes the form of either: test-expr result-expr test-expr :>> result-fn For each clause, (pred test-expr expr) is evaluated. If it returns logical true, the clause is a match. If a binary clause is a match, result-expr is returned. If a ternary clause with :>> is a match, the result of (pred test-expr expr) is passed to result-fn and the return value is the result. If no clause matches, the default value is returned (if provided), otherwise an exception is thrown.

Example:

(condp = 1 1 "one" 2 "two" "other") ; => "one"

conj#

(conj)
(conj coll)
(conj coll value)
(conj coll value & more)

Returns a new collection with values added. Appends to vectors/sets, prepends to lists.

Example:

(conj [1 2] 3) ; => [1 2 3]

conj!#

(conj!)
(conj! tcoll)
(conj! tcoll value)
(conj! tcoll value & more)

Adds value to the transient collection tcoll, mutating it in place, and returns tcoll. The 'addition' may happen at different 'places' depending on the concrete transient type: transient vectors append at the tail, transient hash-sets add the element (no-op if already present), and transient hash-maps treat value as a [key value] pair (or an associative collection of entries). With zero arguments returns a new empty transient vector. With one argument returns tcoll unchanged. Variadic forms reduce conj! over the remaining values. Raises InvalidArgumentException when tcoll is not a transient collection. Matches Clojure's conj! semantics.

Example:

(persistent (conj! (transient [1 2]) 3)) ; => [1 2 3]

cons#

(cons x coll)

Prepends an element to the beginning of a collection.

Example:

(cons 0 [1 2 3]) ; => [0 1 2 3]

constantly#

(constantly x)

Returns a function that always returns x and ignores any passed arguments.

contains-value?#

(contains-value? coll val)

Returns true if the value is present in the given collection, otherwise returns false.

Example:

(contains-value? {:a 1 :b 2} 2) ; => true

contains?#

(contains? coll key)

Returns true if key is present in collection (checks keys/indices, not values).

Example:

(contains? [10 20 30] 1) ; => true

count#

(count coll)

Counts the number of elements in a sequence. Can be used on everything that implements the PHP Countable interface.

Works with lists, vectors, hash-maps, sets, strings, and PHP arrays. Returns 0 for nil.

Example:

(count [1 2 3]) ; => 3

counted?#

(counted? coll)

Returns true if coll can report its length in constant time, persistent vectors, lists, hash-maps (including sorted-map), structs, and sets (including sorted-set). Returns false for lazy sequences (counting them requires realizing the whole sequence), strings, numbers, nil, and every other non-counted type. Matches Clojure's counted? semantics, which mirror the clojure.lang.Counted marker interface.

Example:

(counted? [1 2 3]) ; => true
(counted? (range)) ; => false

create-ns#

(create-ns ns-str)

Creates the given namespace if it does not already exist. Returns the namespace name in display form. Existing namespaces are left untouched.

Example:

(create-ns "my-app.tmp") ; => "my-app.tmp"

csv-seq#

(csv-seq filename)
(csv-seq filename options)

Returns a lazy sequence of rows from a CSV file.

Example:

(take 10 (csv-seq "data.csv")) ; => [["col1" "col2"] ["val1" "val2"] ...]

cycle#

(cycle coll)

Returns an infinite lazy sequence that cycles through the elements of collection. Maps are iterated as [key value] pairs.

Example:

(take 7 (cycle [1 2 3])) ; => (1 2 3 1 2 3 1)

dec#

(dec x)

Decrements x by one.

dec'#

(dec' x)

Auto-promoting variant of dec. Integer results are returned as BigInt; floats and rationals pass through unchanged.

Example:

(dec' 1) ; => 0N

decimal?#

(decimal? x)

Alias for bigdec?. Returns true when x is a Phel\Lang\BigDecimal.

Example:

(decimal? 1.5M) ; => true

declare#

Declare a global symbol before it is defined.

dedupe#

(dedupe & args)

Returns a lazy sequence with consecutive duplicate values removed in coll. When called with no args, returns a transducer.

Example:

(dedupe [1 1 2 2 2 3 1 1]) ; => (1 2 3 1)

deep-merge#

(deep-merge & args)

Recursively merges data structures.

def#

(def name meta? value)

This special form binds a value to a global symbol.

Example:

(def my-value 42)

def-#

Define a private value that will not be exported.

defexception#

(defexception name)

Define a new exception.

defexception*#

(defexception my-ex)

Define a new exception.

Example:

(defexception my-error)

definterface#

(definterface name & fns)

An interface in Phel defines an abstract set of functions. It is directly mapped to a PHP interface. An interface can be defined by using the definterface macro.

Example:

(definterface name & fns)

definterface*#

(definterface name & fns)

An interface in Phel defines an abstract set of functions. It is directly mapped to a PHP interface. An interface can be defined by using the definterface macro.

Example:

(definterface Greeter (greet [name]))

defmacro#

Define a macro.

defmacro-#

(defmacro- name & fdecl)

Define a private macro that will not be exported.

defmethod#

(defmethod multi-name dispatch-val & fn-tail)

Registers a method implementation for a multimethod.

multi-name is the name of the multimethod defined by defmulti. When extending a multimethod from a different namespace, fully qualify the multi-name (e.g. phel\test/assert-expr) so the methods table is resolved in the multimethod's home namespace. dispatch-val is the value that triggers this method. args and body define the function implementation.

Example:

(defmethod area :circle [{:radius r}] (* 3.14159 r r))

defmulti#

(defmulti name & args)

Defines a multimethod. dispatch-fn is called on the arguments to produce a dispatch value, which is then used to select the appropriate method registered via defmethod.

An optional docstring may be provided between name and dispatch-fn.

If no method matches the dispatch value, the :default method is used (if defined), otherwise an error is thrown.

Example:

(defmulti area "Area of shape." :shape)

defn#

Define a new global function.

defn-#

(defn- name & fdecl)

Define a private function that will not be exported.

defprotocol#

(defprotocol protocol-name & method-specs)

Defines a protocol with the given method signatures. Each method signature is a list of (method-name [args]).

Creates a dispatching function for each method that dispatches on the type of the first argument. Use extend-type to add implementations.

A :default type can be registered via extend-type as a fallback when no specific type implementation is found.

Example:

(defprotocol Stringable (to-string [this]))

defrecord#

(defrecord name fields & impls)

Defines a record type with the given fields, matching Clojure's defrecord.

Expands to a defstruct plus Clojure-style factory functions:

  • Name, positional constructor (from defstruct)
  • Name?, type predicate (from defstruct)
  • ->Name, positional factory, identical to Name
  • map->Name, map factory that takes {:field value ...}

An optional tail of protocol/method forms is spliced into an extend-type call, so inline protocol implementations work exactly like Clojure's defrecord body. Only Phel protocols are supported in the inline tail; PHP interface implementations remain on defstruct.

Example:

(defrecord Point [x y] Drawable (draw [this canvas] ...))

defstruct#

(defstruct name keys & implementations)

A Struct is a special kind of Map. It only supports a predefined number of keys and is associated to a global name. The Struct not only defines itself but also a predicate function.

defstruct*#

(defstruct my-struct [a b c])

A Struct is a special kind of Map. It only supports a predefined number of keys and is associated to a global name. The Struct not only defines itself but also a predicate function.

Example:

(defstruct point [x y])

deftype#

(deftype name fields & impls)

Defines a type with the given fields, matching Clojure's deftype syntax.

Expands to a defstruct plus a Clojure-style positional factory:

  • Name, positional constructor (from defstruct)
  • Name?, type predicate (from defstruct)
  • ->Name, positional factory, identical to Name

Unlike defrecord, no map->Name factory is generated.

An optional tail of protocol/method forms is spliced into an extend-type call. Only Phel protocols are supported in the inline tail.

Deviation from Clojure: Phel's deftype shares the map-backed defstruct infrastructure, so instances remain map-like (keys are accessible via get). Clojure's deftype produces a non-map type; if you need that semantic, use native PHP interop.

Example:

(deftype PointT [x y] Drawable (draw [this canvas] ...))

delay#

(delay & body)

Takes a body of expressions and yields a Delay object that will invoke the body only the first time it is forced (via force or deref/@), caching the result.

Example:

(def d (delay (println "computing") 42))

delay?#

(delay? x)

Returns true if x is a Delay.

deliver#

(deliver p value)

Delivers value to p if it is still unrealized. Returns p on first delivery, nil if p was already delivered.

Example:

(deliver (promise) 7)

denominator#

(denominator r)

Returns the denominator of r. For rationals the denominator collapses to a PHP int when it fits; integers and BigInt values report 1.

Example:

(denominator 1/2) ; => 2
(denominator 5) ; => 1

deref#

(deref variable & args)

Returns the current value inside an atom or var.

For atoms returns the current cell value; for Var instances returns the current root binding from the namespace registry.

With three arguments, and when variable is a future or promise, blocks for at most timeout-ms milliseconds waiting for it to resolve. If the awaitable has not completed within the timeout, returns timeout-val.

Example:

(deref (atom 42)) ; => 42
(deref #'phel.core/map) ; => <fn>

derive#

(derive child parent)
(derive h child parent)

Establishes a parent/child relationship between child and parent keywords. With two arguments, mutates the global hierarchy and returns nil. With a hierarchy h, returns a new hierarchy with the relationship added; the original hierarchy is not modified. Throws on cyclic derivation.

Example:

(derive :square :shape)

descendants#

(descendants tag)
(descendants h tag)

Returns the set of all descendants of tag, or nil. Only derive-recorded relationships are walked: type inheritance (PHP class hierarchy, protocol extensions) is not surfaced, matching Clojure's contract.

difference#

(difference set & sets)

Difference between multiple sets into a new one.

disj#

(disj set)
(disj set k)
(disj set k & ks)

Returns a new set that does not contain the given key(s). Works on hash-sets and sorted-sets. Removing a non-existent key is a no-op. Returns nil when called on nil.

Example:

(disj #{1 2 3} 2) ; => #{1 3}

disj!#

(disj! tcoll)
(disj! tcoll value)
(disj! tcoll value & more)

Removes one or more elements from a transient set, mutating it in place. Raises InvalidArgumentException when tcoll is not a transient set. Matches Clojure's disj! semantics.

Example:

(persistent! (disj! (transient #{1 2 3}) 2)) ; => #{1 3}

display-ns#

(display-ns ns-str)

Returns the display (dot-separated) form of a namespace string. Equivalent to canonical-ns; kept as a separate name so call sites read intent (display vs. canonicalize).

Example:

(display-ns "phel\core") ; => "phel.core"

dissoc#

(dissoc ds & ks)

Returns ds without the given keys. With no keys returns ds unchanged.

Example:

(dissoc {:a 1 :b 2} :b) ; => {:a 1}
(dissoc {:a 1 :b 2 :c 3} :a :c) ; => {:b 2}

dissoc!#

(dissoc! tcoll)
(dissoc! tcoll key)
(dissoc! tcoll key & ks)

Dissociates one or more keys from a transient map, mutating it in place. Raises InvalidArgumentException when tcoll is not a transient map. Matches Clojure's dissoc! semantics.

Example:

(persistent! (dissoc! (transient {:a 1 :b 2}) :a)) ; => {:b 2}

dissoc-in#

(dissoc-in ds [k & ks])

Dissociates a value from a nested data structure at the given path.

Example:

(dissoc-in {:a {:b 1 :c 2}} [:a :b]) ; => {:a {:c 2}}

distinct#

(distinct & args)

Returns a lazy sequence with duplicated values removed in coll. When called with no args, returns a transducer.

Example:

(distinct [1 2 1 3 2 4 3]) ; => (1 2 3 4)

do#

(do expr*)

Evaluates the expressions in order and returns the value of the last expression. If no expression is given, nil is returned.

Example:

(do (println "Hello") (+ 1 2)) ; prints "Hello", returns 3

doall#

(doall coll)

Forces realization of a lazy sequence and returns it as a vector.

Example:

(doall (map println [1 2 3])) ; => [nil nil nil]

dofor#

(dofor head & body)

Repeatedly executes body for side effects with bindings and modifiers as provided by for. Returns nil.

dorun#

(dorun coll)

Forces realization of a lazy sequence for side effects, returns nil.

Example:

(dorun (map println [1 2 3])) ; => nil

doseq#

(doseq seq-exprs & body)

Repeatedly executes body for side effects with Clojure-style bindings. (doseq [x coll] body) runs body once per element of coll. When coll is a map, each iteration sees a [k v] entry pair, so destructuring works just like in Clojure: (doseq [[k v] m] ...). Supports :when, :while, and :let modifiers between bindings.

Example:

(doseq [x [1 2 3]] (println x))
(doseq [[k v] {:a 1 :b 2}] (println k v))

doseq-iterable#

(doseq-iterable coll)

Internal helper used by the doseq macro expansion. Returns a value suitable for Clojure-style iteration: maps are expanded to a sequence of [k v] pair vectors so destructuring binds entries as in Clojure. Every other value is returned unchanged.

dotimes#

(dotimes [binding n] & body)

Evaluates body n times with binding bound to integers from 0 to n-1. Returns nil.

Example:

(dotimes [i 5] (println i))

doto#

(doto x & forms)

Evaluates x then calls all of the methods and functions with the value of x supplied at the front of the given arguments. The forms are evaluated in order. Returns x.

double#

(double x)

Coerces x to a double. In PHP there is no distinction between float and double; both map to the same native PHP float type. Alias for float.

Example:

(double 1) ; => 1.0

double-array#

(double-array size-or-seq)
(double-array size init-val-or-seq)

Creates a PHP array of doubles (same as float-array in PHP). Accepts the same arities and semantics as float-array.

Example:

(double-array 3) ; => PHP array [0.0, 0.0, 0.0]
(double-array 4 1.5) ; => PHP array [1.5, 1.5, 1.5, 1.5]

double?#

(double? x)

Returns true if x is a floating-point number, false otherwise. Alias for float?, matching Clojure's double? naming. Since Phel uses PHP floats (IEEE 754 doubles) there is no separate single-precision float type.

drop#

(drop n & args)

Drops the first n elements of coll. Returns a lazy sequence. When called with n only, returns a transducer.

Example:

(drop 2 [1 2 3 4 5]) ; => (3 4 5)

drop-last#

(drop-last coll)
(drop-last n coll)

Drops the last n elements of coll. n defaults to 1 when omitted, matching Clojure's (drop-last coll) single-arity form. Returns an empty sequence when coll is nil. Works with any seqable collection including lazy sequences and ranges.

Example:

(drop-last [1 2 3 4 5]) ; => (1 2 3 4)
(drop-last 2 [1 2 3 4 5]) ; => (1 2 3)
(drop-last 5 nil) ; => ()

drop-while#

(drop-while pred & args)

Drops all elements at the front of coll where (pred x) is true. Returns a lazy sequence. When called with pred only, returns a transducer.

Example:

(drop-while #(< % 5) [1 2 3 4 5 6 3 2 1]) ; => (5 6 3 2 1)

eduction#

(eduction & args)

Returns a reducible/iterable applying transducers to coll. The last argument is the source collection; preceding arguments are transducers composed left-to-right. The transformation is re-run on each consumption (no caching), so the result is safe to reduce or iterate multiple times.

Example:

(reduce + (eduction (map inc) (filter odd?) [1 2 3 4])) ; => 8

empty#

(empty coll)

Returns an empty collection of the same category as coll, preserving the original metadata, or nil if coll has no empty equivalent.

Example:

(empty [1 2 3]) ; => []
(empty {:a 1}) ; => {}
(empty (range 10)) ; => ()

empty?#

(empty? x)

Returns true if x would be 0, "" or empty collection, false otherwise. Safe on infinite/lazy sequences: checks the first element instead of counting.

eval#

(eval form)

Evaluates a form and return the evaluated results.

even?#

(even? x)

Checks if x is even.

every?#

(every? pred coll)

Returns true if predicate is true for every element in collection, false otherwise. Alias for all?.

Example:

(every? even? [2 4 6 8]) ; => true

ex-cause#

(ex-cause ex)

Returns the cause of an exception, or nil.

ex-data#

(ex-data ex)

Returns the data map from an ex-info exception, or nil if not an ExceptionInfo.

ex-info#

(ex-info msg data)
(ex-info msg data cause)

Creates an exception with a message and a data map. Optionally takes a cause.

Example:

(throw (ex-info "Invalid input" {:field :email}))

ex-message#

(ex-message ex)

Returns the message of an exception.

extend-protocol#

(extend-protocol protocol-name & specs)

Convenience macro that extends a single protocol to multiple types. Alternates type-specs and method implementations.

Equivalent to multiple extend-type calls.

Example:

(extend-protocol Describable
  :string (describe [s] s)
  :int (describe [n] (str n)))

extend-type#

(extend-type type-spec & specs)

Extends a type with protocol method implementations.

type-spec can be:

  • nil for the nil type
  • a type keyword matching what type returns: :string, :int, :float, :boolean, :keyword, :symbol, :vector, :list, :hash-map, :set, :atom, :var, :function, :php/array
  • a symbol for struct names (resolved in current namespace)
  • a string for explicit PHP class names (cross-namespace structs)

Note: :struct and :php/object cannot be used as type-specs because protocol dispatch resolves these to their specific PHP class names. Use a struct symbol or PHP class name string instead.

Example:

(extend-type :string Stringable (to-string [s] s))

extends?#

(extends? protocol type-key)

Returns true if the given type-key has implementations for all methods of the protocol. type-key should match what protocol-type-key returns.

Example:

(extends? Stringable :string)

extreme#

(extreme order args)

Returns the most extreme value in args based on the binary order function.

false?#

(false? x)

Checks if value is exactly false (not just falsy).

Example:

(false? nil) ; => false

ffirst#

(ffirst coll)

Same as (first (first coll)).

file-seq#

(file-seq path)

Returns a lazy sequence of all files and directories in a directory tree.

Example:

(filter #(php/str_ends_with % ".phel") (file-seq "src/")) ; => ["src/file1.phel" "src/file2.phel" ...]

filter#

(filter pred & args)

Returns a lazy sequence of elements where predicate returns true. When called with pred only, returns a transducer.

Example:

(filter even? [1 2 3 4 5 6]) ; => (2 4 6)

finally#

(finally expr*)

Evaluate expressions after the try body and all matching catches have completed. The finally block runs regardless of whether an exception was thrown.

Example:

(defn risky-operation [] (throw (php/new \Exception "Error!")))
(defn cleanup [] (println "Cleanup!"))
(try (risky-operation) (catch \Exception e nil) (finally (cleanup)))

find#

(find pred-or-coll coll-or-key)

When called with a collection first, returns [key value] when key is present. Otherwise returns the first item in coll where (pred item) evaluates to true.

Example:

(find {:a 1} :a) ; => [:a 1]
(find #(> % 5) [1 2 3 6 7 8]) ; => 6

find-hierarchy-method#

(find-hierarchy-method methods dispatch-val)
(find-hierarchy-method methods dispatch-val prefers-map)

Finds the best matching method for dispatch-val using the global hierarchy. Returns the method function or nil. Used internally by defmulti. When multiple methods match and none is more specific, consults prefers-map (built by prefer-method); if still ambiguous, throws.

find-index#

(find-index pred coll)

Returns the index of the first item in coll where (pred item) evaluates to true.

Example:

(find-index #(> % 5) [1 2 3 6 7 8]) ; => 3

find-ns#

(find-ns ns-str)

Returns the namespace name in display form if it is loaded, or nil if no namespace of that name exists. Accepts dot or backslash separators on input.

Example:

(find-ns "phel.core") ; => "phel.core"

find-var#

(find-var sym)

Returns the Var named by the fully-qualified symbol, or nil if no matching definition exists. Tries the symbol name verbatim first (matching how def stores entries), then falls back to the encoded form (matching how intern stores entries).

Example:

(find-var 'phel.core/map) ; => #'phel.core/map

first#

Returns the first element of a sequence, or nil if empty.

Maps are treated as a sequence of entries: (first {:a 1}) returns a typed MapEntry equal by value to [:a 1]. Strings are treated as sequences of multibyte characters.

Example:

(first [1 2 3]) ; => 1

flatten#

(flatten coll)

Flattens nested sequential structure into a lazy sequence of all leaf values.

Example:

(flatten [[1 2] [3 [4 5]] 6]) ; => (1 2 3 4 5 6)

float#

(float x)

Coerces x to a float. In PHP there is no distinction between float and double; both map to the same native PHP float type. Ratio, BigInt, and BigDecimal values collapse to their float value; everything else delegates to PHP's floatval, so non-numeric strings return 0.0 and nil returns 0.0.

Example:

(float 1) ; => 1.0
(float 1/2) ; => 0.5

float-array#

(float-array size-or-seq)
(float-array size init-val-or-seq)

Creates a PHP array of floats. Accepts the same arities as int-array; coerces elements to float via floatval and zero-pads with 0.0.

Example:

(float-array 3) ; => PHP array [0.0, 0.0, 0.0]
(float-array 4 1.5) ; => PHP array [1.5, 1.5, 1.5, 1.5]

float?#

(float? x)

Returns true if x is float point number, false otherwise.

floor#

(floor x)

Returns the largest integer not greater than x. Ints and BigInt values are returned unchanged. Ratios collapse via floor division. Floats route through PHP's floor.

Example:

(floor 1.7) ; => 1.0
(floor -1.2) ; => -2.0
(floor 7/3) ; => 2

fn#

(fn [params*] expr*)

Defines a function. A function consists of a list of parameters and a list of expression. The value of the last expression is returned as the result of the function. All other expression are only evaluated for side effects. If no expression is given, the function returns nil.

Example:

(fn [x y] (+ x y))

fn?#

(fn? x)

Returns true if x is a function, false otherwise.

fnext#

(fnext coll)

Same as (first (next coll)).

Example:

(fnext [1 2 3]) ; => 2

fnil#

(fnil f & defaults)

Returns a function that replaces nil arguments with the provided defaults before calling f. The number of defaults determines how many leading arguments are nil-checked.

Example:

(let [safe-inc (fnil inc 0)] (safe-inc nil)) ; => 1

for#

(for head & body)

List comprehension. The head of the loop is a vector that contains a sequence of bindings modifiers and options. A binding is a sequence of three values binding :verb expr. Where binding is a binding as in let and :verb is one of the following keywords:

  • :range loop over a range by using the range function.
  • :in loops over all values of a collection (including strings).
  • :keys loops over all keys/indexes of a collection.
  • :pairs loops over all key-value pairs of a collection.

After each loop binding, additional modifiers can be applied. Modifiers have the form :modifier argument. The following modifiers are supported:

  • :while breaks the loop if the expression is falsy.
  • :let defines additional bindings.
  • :when only evaluates the loop body if the condition is true.

Finally, additional options can be set:

  • :reduce [accumulator initial-value] Instead of returning a list, it reduces the values into accumulator. Initially accumulator is bound to initial-value.

Example:

(for [x :in [1 2 3]] (* x 2)) ; => [2 4 6]

force#

(force x)

If x is a Delay, forces it and returns its cached value. Otherwise returns x.

Example:

(force (delay 42)) ; => 42

foreach#

(foreach [value valueExpr] expr*)
(foreach [key value valueExpr] expr*)

The foreach special form can be used to iterate over all kind of PHP datastructures. The return value of foreach is always nil. The loop special form should be preferred of the foreach special form whenever possible.

Example:

(foreach [x [1 2 3]] (println x))

format#

(format fmt & xs)

Returns a formatted string. See PHP's sprintf for more information.

frequencies#

(frequencies coll)

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

Works with vectors, lists, sets, and strings.

Example:

(frequencies [:a :b :a :c :b :a]) ; => {:a 3 :b 2 :c 1}

full-name#

(full-name x)

Return the namespace and name string of a string, keyword or symbol.

function?#

Deprecated: 0.32.0, Use fn? instead

(function? x)

Returns true if x is a function, false otherwise.

future#

(future & body)

Starts evaluating body asynchronously and returns a Future that can be derefed (blocks the current fiber until the value is available) or checked with realized?.

Supports the 3-arg (deref f timeout-ms timeout-val) form for time-bounded blocking, as well as future-cancel, future-cancelled? and future-done? for lifecycle management.

Must be called from inside a fiber context (e.g. the AMPHP event loop or an enclosing async block), because deref resolves via AMPHP's fiber-based await.

Example:

(let [f (future (expensive-computation))] @f)

future-call#

(future-call f)

Invokes f (a zero-arg function) in a new fiber. Returns a PhelFiberFuture you can deref or inspect with future-done? and future-cancel.

Captures the caller's dynamic bindings and reinstalls them inside the fiber before invoking f, so bindings are conveyed the same way as with future/async.

Example:

(future-call (fn [] 42))

future-cancel#

(future-cancel f)

Signals the future's internal cancellation token, causing any pending or subsequent deref call to raise CancelledException (or return the timeout value for the 3-arg form). Due to AMPHP's cooperative fibers, the body keeps running until its next cancellation checkpoint; from the caller's perspective the future behaves as cancelled after this returns.

Example:

(future-cancel (future (expensive-call)))

future-cancelled?#

(future-cancelled? f)

Returns true if future-cancel was called on f, false otherwise.

Example:

(future-cancelled? f)

future-done?#

(future-done? f)

Returns true if the future is in a final state (completed, failed, or cancelled).

Dispatches on type: for a \Phel\Fiber\Domain\Future (fiber-backed) it calls isDone; for any other value it falls back to realized?. This lets the same predicate serve both the AMPHP Future wrapper and the cooperative fiber future.

Example:

(future-done? f)

future-fiber#

(future-fiber & body)

Runs body in a new fiber via the cooperative scheduler. Returns a fiber-future that supports deref, realized?, future-done?, and future-cancel. Works at the top level (no enclosing async block required), in contrast to future which requires an AMPHP fiber context.

Example:

@(future-fiber (+ 1 2))

future?#

(future? x)

Returns true if x is a fiber-future (from future-call/future-fiber) or a Future (from the AMPHP-backed future macro).

Example:

(future? (future-call (fn [] 1))) ; => true

gensym#

(gensym)

Generates a new unique symbol.

get#

(get ds k & [opt])

Gets the value at key in a collection. Returns default if not found.

Example:

(get {:a 1} :a) ; => 1

get-in#

(get-in ds ks & [opt])

Accesses a value in a nested data structure via a sequence of keys.

Returns opt (default nil) when a key is missing mid-traversal. When the path is nil or empty, returns ds as-is (which may be nil).

Example:

(get-in {:a {:b {:c 42}}} [:a :b :c]) ; => 42

get-validator#

(get-validator variable)

Returns the validator function of a variable, or nil.

group-by#

(group-by f coll)

Returns a map of the elements of coll keyed by the result of f on each element.

Example:

(group-by count ["a" "bb" "c" "ddd" "ee"]) ; => {1 ["a" "c"] 2 ["bb" "ee"] 3 ["ddd"]}

hash-map#

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

Creates a new hash map. If no argument is provided, an empty hash map is created. The number of parameters must be even. Shortcut: {}

Example:

(hash-map :name "Alice" :age 30) ; => {:name "Alice" :age 30}

hash-map?#

Deprecated: 0.32.0, Use map? instead

(hash-map? x)

Returns true if x is a hash map, false otherwise.

hash-set#

(hash-set & xs)

Creates a new Set from the given arguments. Shortcut: #{}

Example:

(hash-set 1 2 3) ; => #{1 2 3}

id#

Deprecated: 0.32.0, Use identical? instead

(id a & more)

Checks if all values are identical. Same as a === b in PHP.

ident?#

(ident? x)

Returns true if x is a symbol or keyword.

Example:

(ident? 'x) ; => true
(ident? :a) ; => true
(ident? 42) ; => false

identical?#

(identical? a & more)

Checks if all values are identical. Same as a === b in PHP.

identity#

(identity x)

Returns its argument.

if#

(if test then else?)

A control flow structure. First evaluates test. If test evaluates to true, only the then form is evaluated and the result is returned. If test evaluates to false only the else form is evaluated and the result is returned. If no else form is given, nil will be returned.

The test evaluates to false if its value is false or equal to nil. Every other value evaluates to true. In sense of PHP this means (test != null && test !== false).

Example:

(if (> x 0) "positive" "non-positive")

if-let#

(if-let bindings then & [else])

If test is true, evaluates then with binding-form bound to the value of test, if not, yields else

if-not#

(if-not test then & [else])

Evaluates then if test is false, else otherwise.

Example:

(if-not (< 5 3) "not less" "less") ; => "not less"

if-some#

(if-some bindings then & [else])

Binds name to the value of test. If test is not nil, evaluates then with binding-form bound to the value of test, if not, yields else. Unlike if-let, false and 0 are not treated as falsy, only nil triggers the else branch.

ifn?#

(ifn? x)

Returns true if x can be invoked as a function. This includes functions, keywords, maps, vectors, sets, and lists.

Example:

(ifn? inc) ; => true
(ifn? :a) ; => true
(ifn? {}) ; => true
(ifn? 42) ; => false

inc#

(inc x)

Increments x by one.

inc'#

(inc' x)

Auto-promoting variant of inc. Integer results are returned as BigInt; floats and rationals pass through unchanged.

Example:

(inc' 1) ; => 2N

indexed?#

(indexed? x)

Returns true if x is an indexed sequence, false otherwise.

Indexed sequences include lists, vectors, and indexed PHP arrays.

Example:

(indexed? [1 2 3]) ; => true

inf?#

(inf? x)

Checks if x is infinite.

Example:

(inf? php/INF) ; => true

instance?#

(instance? c x)

Returns true if x is an instance of class c, false otherwise. Mirrors Clojure's clojure.core/instance? argument order (class first, value second). c should be a literal class reference such as DateTime or a :used short name; for runtime class names use (php/is_a x class-name).

Example:

(instance? DateTime (php/new DateTime)) ; => true

int#

(int x)

Coerces x to an integer. Ratio and BigDecimal values truncate toward zero ((int 1/10) is 0, (int -1.1M) is -1); BigInt and float values collapse to their PHP int value or throw OverflowException when outside the PHP int range (NaN/Inf floats raise InvalidArgumentException). Numeric strings are parsed via PHP's intval, and nil returns 0.

Example:

(int 1.9) ; => 1
(int "42") ; => 42
(int 1/10) ; => 0

int-array#

(int-array size-or-seq)
(int-array size init-val-or-seq)

Creates a PHP array of integers, matching Clojure's clojure.core/int-array.

  • (int-array size-or-seq), given a non-negative integer, fills with 0; given a sequence, coerces each element to int via intval.
  • (int-array size init-val-or-seq), when init-val-or-seq is a number, every slot is filled with it (coerced to int). When it is a sequence, its elements fill the prefix of the array (truncated to size if longer) and the remaining slots are zero-padded.

PHP has no typed arrays, so the result is a plain PHP array.

Example:

(int-array 3) ; => PHP array [0, 0, 0]
(int-array [1.5 2.7]) ; => PHP array [1, 2]
(int-array 4 7) ; => PHP array [7, 7, 7, 7]
(int-array 5 [10 20]) ; => PHP array [10, 20, 0, 0, 0]

int?#

(int? x)

Returns true if x is a fixed-precision PHP integer. BigInt values return false; use integer? to accept either.

integer?#

(integer? x)

Returns true if x is a mathematical integer: a fixed-precision PHP int or a BigInt.

interleave#

(interleave & colls)

Returns a lazy sequence of the first item in each colls, then the second item in each, until any one of the collections is exhausted. Any remaining items in the other collections are ignored. Returns an empty sequence when no collections are supplied or when any collection is empty or nil. Maps are iterated as [key value] pairs.

Example:

(interleave [1 2 3] [:a :b :c]) ; => (1 :a 2 :b 3 :c)
(interleave [1 2 3] [:a :b]) ; => (1 :a 2 :b)

intern#

(intern ns-str name-str & rest)

Finds or creates a definition named by name-str in namespace ns-str. When a value is supplied, sets the root value to val (overwriting any existing value). When no value is supplied, returns the existing definition unchanged, or creates a new one with nil if none exists. Auto-registers the namespace when creating a new definition; the arity-2 form is a no-op when the definition already exists. Returns the fully qualified symbol naming the definition (with the namespace in display form).

Example:

(intern "user" "x" 42) ; => user/x

interpose#

(interpose sep & args)

Returns elements separated by a separator. Returns a lazy sequence. When called with sep only, returns a transducer.

Example:

(interpose 0 [1 2 3]) ; => (1 0 2 0 3)

intersection#

(intersection set & sets)

Intersect multiple sets into a new one.

into#

(into to & rest)

Returns to with all elements of from added.

When from is associative, it is treated as a sequence of key-value pairs. Supports persistent and transient collections.

Example:

(into [] '(1 2 3)) ; => [1 2 3]

into-array#

(into-array aseq)
(into-array _type aseq)

Returns a PHP array containing the elements of aseq. Accepts any collection (vector, list, set, map, PHP array) or nil, which yields an empty PHP array. The optional type argument is accepted for .cljc interop but has no runtime effect, PHP has no typed arrays, so the result is always a plain PHP array. Use the dedicated coercion helpers (int-array, long-array, float-array, double-array, short-array) when element coercion is actually required.

Example:

(into-array [1 2 3]) ; => a PHP array [1, 2, 3]
(into-array :Object [:a :b]) ; => a PHP array [:a, :b]

invert#

(invert map)

Returns a new map where the keys and values are swapped.

If map has duplicated values, some keys will be ignored.

Example:

(invert {:a 1 :b 2 :c 3}) ; => {1 :a 2 :b 3 :c}

isa?#

(isa? child parent)
(isa? h child parent)

Returns true if child equals parent, or child is a descendant of parent. When a hierarchy is provided, the check is performed against it; otherwise the global hierarchy is used.

Example:

(do (derive :square :shape) (isa? :square :shape)) ; => true

iterate#

(iterate f x)

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

Example:

(take 5 (iterate inc 0)) ; => (0 1 2 3 4)

iteration#

(iteration step opts)

Creates a lazy sequence from successive calls to step. step is called with a key (starting with :initk) and returns a result. :kf extracts the next key, :vf extracts the value from the result. Terminates when the result is nil.

Options map keys: :kf , key function (default: identity) :vf , value function (default: identity) :initk , initial key (default: nil)

Example:

(iteration fetch-page {:kf :next-token :vf :items :initk nil})

juxt#

(juxt & fs)

Takes a list of functions and returns a new function that is the juxtaposition of those functions.

Example:

((juxt inc dec #(* % 2)) 10) => [11 9 20]

keep#

(keep pred & args)

Returns a lazy sequence of non-nil results of applying function to elements. When called with f only, returns a transducer.

Example:

(keep #(when (even? %) (* % %)) [1 2 3 4 5]) ; => (4 16)

keep-indexed#

(keep-indexed pred & args)

Returns a lazy sequence of non-nil results of (pred i x). When called with f only, returns a transducer.

Example:

(keep-indexed #(when (even? %1) %2) ["a" "b" "c" "d"]) ; => ("a" "c")

key#

(key entry)

Returns the key of a map entry. Accepts a typed Phel\Lang\Collections\Map\MapEntry value or a 2-element vector [key value] (the form Phel maps yield when iterated).

Example:

(key (first (pairs {:a 1}))) ; => :a

keys#

(keys coll)

Returns a sequence of all keys in a map, or nil when the map is nil or empty.

Example:

(keys {:a 1 :b 2}) ; => (:a :b)
(keys nil) ; => nil

keyword#

(keyword x)
(keyword ns nm)

Creates a new Keyword.

Arity-1 accepts a string, keyword, or symbol. Returns nil when x is nil. If x is already a keyword, it is returned unchanged.

Arity-2 builds a namespaced keyword from the namespace and name parts; returns nil when name is nil.

Example:

(keyword "name") ; => :name
(keyword :abc) ; => :abc
(keyword "ns" "name") ; => :ns/name

keyword?#

(keyword? x)

Returns true if x is a keyword, false otherwise.

kvs#

(kvs coll)

Returns a vector of key-value pairs like [k1 v1 k2 v2 k3 v3 ...].

Example:

(kvs {:a 1 :b 2}) ; => [:a 1 :b 2]

last#

(last coll)

Returns the last element of coll or nil if coll is empty or nil.

Example:

(last [1 2 3]) ; => 3

lazy-cat#

(lazy-cat & colls)

Concatenates collections into a lazy sequence (expands to concat).

Example:

(lazy-cat [1 2] [3 4]) ; => (1 2 3 4)

lazy-seq#

(lazy-seq & body)

Creates a lazy sequence that evaluates the body only when accessed.

Example:

(lazy-seq (cons 1 (lazy-seq nil))) ; => (1)

lazy-seq?#

(lazy-seq? x)

Returns true if x is a lazy sequence, false otherwise.

Unlike seq?, this predicate is true only for lazy sequences, not for realized lists. Use seq? if you want to accept either.

Example:

(lazy-seq? (map inc [1 2 3])) ; => true
(lazy-seq? '(1 2 3))         ; => false
(lazy-seq? [1 2 3])          ; => false

let#

(let [bindings*] expr*)

Creates a new lexical context with assignments defined in bindings. Afterwards the list of expressions is evaluated and the value of the last expression is returned. If no expression is given nil is returned.

Example:

(let [x 1 y 2] (+ x y)) ; => 3

letfn#

(letfn bindings & body)

Defines mutually recursive local functions.

bindings is a vector of function specs: (letfn [(f [params] body) (g [params] body)] expr) All function names are in scope within all function bodies and the body expression, enabling mutual recursion.

Example:

(letfn [(my-even? [n] (if (zero? n) true (my-odd? (dec n))))
        (my-odd? [n] (if (zero? n) false (my-even? (dec n))))]
  (my-even? 10))

line-seq#

(line-seq filename)

Returns a lazy sequence of lines from a file.

Example:

(take 10 (line-seq "large-file.txt")) ; => ["line1" "line2" ...]

list#

(list 1 2 3) ; => '(1 2 3)

Creates a new list. If no argument is provided, an empty list is created. Shortcut: '()

Example:

(list 1 2 3) ; => '(1 2 3)

list?#

(list? x)

Returns true if x is a list, false otherwise. Returns false for the seq view of non-list collections produced by seq.

load-file#

(load-file path)

Loads and evaluates a Phel source file. Reads the file content and evaluates it using the compiler. Returns the result of the last expression, or nil if the file cannot be read.

Example:

(load-file "src/my-module.phel")

loaded-namespaces#

(loaded-namespaces)

Returns all namespaces currently loaded, in dot-separated display form.

Example:

(loaded-namespaces) ; => ["phel.core" "phel.repl"]

long#

(long x)

Coerces x to a long integer. In PHP there is no distinction between int and long; both map to the same native PHP int type. Alias for int.

Example:

(long 1.9) ; => 1

long-array#

(long-array size-or-seq)
(long-array size init-val-or-seq)

Creates a PHP array of longs (same as int-array in PHP). Accepts the same arities and semantics as int-array.

Example:

(long-array 3) ; => PHP array [0, 0, 0]
(long-array 4 7) ; => PHP array [7, 7, 7, 7]

loop#

(loop [bindings*] expr*)

Creates a new lexical context with variables defined in bindings and defines a recursion point at the top of the loop.

Example:

(loop [i 0] (if (< i 5) (do (println i) (recur (inc i)))))

macroexpand#

(macroexpand form)

Recursively expands the given form until it is no longer a macro call.

macroexpand-1#

(macroexpand-1 form)

Expands the given form once if it is a macro call.

make-hierarchy#

(make-hierarchy)

Creates a fresh, empty hierarchy.

Returns a map with :parents, :descendants, and :ancestors keys, each holding an empty map. Matches Clojure's hierarchy shape so consumers can destructure any of the three relationship views.

map#

(map f & colls)

Returns a lazy sequence of the result of applying f to all of the first items in each coll, followed by applying f to all the second items in each coll until anyone of the colls is exhausted.

When given a single collection, applies the function to each element. With multiple collections, applies the function to corresponding elements from each collection, stopping when the shortest collection is exhausted.

Example:

(map inc [1 2 3]) ; => (2 3 4)

map-entry#

(map-entry k v)

Returns a typed Phel\Lang\Collections\Map\MapEntry for k/v. Equal to the two-element vector [k v] so existing code that destructures [k v] keeps working.

Example:

(map-entry :a 1) ; => [:a 1]

map-entry?#

(map-entry? x)

Returns true if x is a map entry. Accepts both the typed Phel\Lang\Collections\Map\MapEntry value and any 2-element vector (Phel maps still yield vectors when iterated).

Example:

(map-entry? [:a 1]) ; => true
(map-entry? (map-entry :a 1)) ; => true
(map-entry? [1 2 3]) ; => false

map-indexed#

(map-indexed f coll)

Maps a function over a collection with index. Returns a lazy sequence.

Applies f to each element in xs. f is a two-argument function where the first argument is the index (0-based) and the second is the element itself. Works with infinite sequences.

Example:

(map-indexed vector [:a :b :c]) ; => ([0 :a] [1 :b] [2 :c])

map?#

(map? x)

Returns true if x is a hash map, false otherwise.

mapcat#

(mapcat f & args)

Maps a function over one or more collections and concatenates the results. Returns a lazy sequence. When called with f alone, returns a transducer.

With a single collection behaves like (apply concat (map f coll)). With multiple collections, f is called with corresponding elements from each (stopping when the shortest is exhausted) and the resulting sequences are concatenated.

Example:

(mapcat reverse [[1 2] [3 4]]) ; => (2 1 4 3)
(mapcat list [:a :b :c] [1 2 3]) ; => (:a 1 :b 2 :c 3)

max#

(max & numbers)

Returns the maximum of all arguments. Returns ##NaN whenever any numeric argument is ##NaN.

max-key#

(max-key k x & more)

Returns the arg for which (k arg) is largest. On ties, returns the latest argument.

Example:

(max-key count "bb" "aaa" "b") ; => "aaa"

mean#

(mean xs)

Returns the mean of xs as a float.

median#

(median xs)

Returns the median of xs. With an even-sized collection the result is the float average of the two middle elements.

memoize#

(memoize f)

Returns a memoized version of the function f. The memoized function caches the return value for each set of arguments.

Example:

(defn fact [n]
  (if (zero? n)
    1
    (* n (fact (dec n)))))
(def fact-memo (memoize fact))

memoize-lru#

(memoize-lru f)
(memoize-lru f max-size)

Returns a memoized version of the function f with an LRU (Least Recently Used) cache limited to max-size entries. When the cache exceeds max-size, the least recently used entry is evicted. This prevents unbounded memory growth in long-running processes.

Without arguments, uses a default cache size of 128 entries.

Example:

(defn fact [n]
  (if (zero? n)
    1
    (* n (fact (dec n)))))
(def fact-memo (memoize-lru fact 100))

merge#

(merge)
(merge map)
(merge map & more)

Merges multiple maps into one new map.

If a key appears in more than one collection, later values replace previous ones.

Example:

(merge {:a 1 :b 2} {:b 3 :c 4}) ; => {:a 1 :b 3 :c 4}

merge-with#

(merge-with f & hash-maps)

Merges multiple maps into one new map. If a key appears in more than one collection, the result of (f current-val next-val) is used.

meta#

Gets the metadata attached to a value. For a quoted symbol ((meta 'foo)) the definition metadata registered via def is returned. For any other expression the value is looked up at runtime and its MetaInterface metadata returned.

min#

(min & numbers)

Returns the minimum of all arguments. Returns ##NaN whenever any numeric argument is ##NaN.

min-key#

(min-key k x & more)

Returns the arg for which (k arg) is smallest. On ties, returns the latest argument.

Example:

(min-key count "bb" "aaa" "b") ; => "b"

mod#

(mod dividend divisor)

Returns the floor remainder of dividend / divisor. The result has the same sign as divisor. Differs from rem on mixed-sign operands: (mod -7 3) => 2 while (rem -7 3) => -1.

Example:

(mod 7 3) ; => 1
(mod -7 3) ; => 2

name#

(name x)

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

namespace#

(namespace x)

Return the namespace string of a symbol or keyword. Nil if not present.

nan?#

(nan? x)

Checks if x is not a number.

nat-int?#

(nat-int? x)

Returns true if x is a non-negative integer (zero or positive). Accepts both fixed-precision PHP int and arbitrary-precision BigInt values.

Example:

(nat-int? 0) ; => true
(nat-int? 1) ; => true
(nat-int? (bigint 5)) ; => true

neg-int?#

(neg-int? x)

Returns true if x is a negative integer. Accepts both fixed-precision PHP int and arbitrary-precision BigInt values.

Example:

(neg-int? -1) ; => true
(neg-int? 0) ; => false
(neg-int? (bigint -5)) ; => true

neg?#

(neg? x)

Checks if x is smaller than zero.

next#

Returns the sequence after the first element, or nil if empty.

Example:

(next [1 2 3]) ; => [2 3]

nfirst#

(nfirst coll)

Same as (next (first coll)).

nil?#

(nil? x)

Returns true if value is nil, false otherwise.

Example:

(nil? (get {:a 1} :b)) ; => true

nnext#

(nnext coll)

Same as (next (next coll)).

not#

(not x)

Returns true if value is falsy (nil or false), false otherwise.

Example:

(not nil) ; => true

not-any?#

(not-any? pred coll)

Returns true if (pred x) is logical false for every x in coll or if coll is empty. Otherwise returns false.

not-empty#

(not-empty coll)

Returns coll if it contains elements, otherwise nil.

not-every?#

(not-every? pred coll)

Returns false if (pred x) is logical true for every x in collection coll or if coll is empty. Otherwise returns true.

not=#

(not= a & more)

Checks if all values are unequal. Same as a != b in PHP.

ns#

(ns name imports*)

Defines the namespace for the current file and adds imports to the environment. Imports can either be uses or requires. The keyword :use is used to import PHP classes, the keyword :require is used to import Phel modules and the keyword :require-file is used to load php files.

Example:

(ns my-app\core (:require phel\string :as str))

ns-aliases#

(ns-aliases ns-str)

Returns a hash-map of {alias => namespace} for all require aliases in the given namespace string. Target namespaces are returned in display form.

Example:

(ns-aliases *ns*) ; => {"repl" "phel.repl" ...}

ns-interns#

(ns-interns ns-str)

Returns a hash-map of {name => value} for every definition in the given namespace, including private ones. Returns an empty map if the namespace has no definitions.

Example:

(ns-interns "phel\core")

ns-publics#

(ns-publics ns-str)

Returns a hash-map of {name => value} for all public definitions in the given namespace string. Private definitions are excluded.

Example:

(ns-publics "phel\core") ; => {"map" <fn> "filter" <fn> ...}

ns-refers#

(ns-refers ns-str)

Returns a hash-map of {name => source-namespace} for all referred symbols in the given namespace string. Source namespaces are returned in display form.

Example:

(ns-refers *ns*) ; => {"doc" "phel.repl" ...}

nth#

(nth coll index)
(nth coll index not-found)

Returns the value at index in coll. Throws an OutOfBoundsException if the index is out of range and no not-found value is supplied. For indexed collections (vectors, strings) this is O(1); for sequences it is O(n).

Example:

(nth [1 2 3] 1) ; => 2
(nth [1 2 3] 5 :default) ; => :default

nthnext#

(nthnext coll n)

Returns the nth next of coll, (seq coll) when n is 0. Returns nil if there are fewer than n elements remaining.

Example:

(nthnext [1 2 3 4 5] 2) ; => (3 4 5)
(nthnext [1 2] 5) ; => nil

nthrest#

(nthrest coll n)

Returns the nth rest of coll, coll when n is less than 1. Returns an empty list once the collection is exhausted.

Example:

(nthrest [1 2 3 4 5] 2) ; => (3 4 5)
(nthrest [1 2] 5) ; => ()
(nthrest nil 0) ; => nil
(nthrest nil 3) ; => ()

number?#

(number? x)

Returns true if x is a number: int, float, Ratio, BigInt, or BigDecimal.

numerator#

(numerator r)

Returns the numerator of r. For rationals the numerator collapses to a PHP int when it fits; for plain ints and BigInt values r is returned unchanged.

Example:

(numerator 1/2) ; => 1
(numerator 5) ; => 5

object-array#

(object-array size-or-seq)

Creates a PHP array of the given size initialized to nil, or a PHP array containing the elements of the given sequence. Matches Clojure's object-array for .cljc interop, in Phel the result is a plain PHP array (accessible via php/aget/php/aset) since PHP has no typed array distinction.

Example:

(object-array 3) ; => a PHP array [nil, nil, nil]
(object-array [1 2 3]) ; => a PHP array [1, 2, 3]

odd?#

(odd? x)

Checks if x is odd.

one?#

(one? x)

Checks if x is one.

or#

(or & args)

Evaluates expressions left to right, returning the first truthy value or the last value.

Example:

(or false nil 42 100) ; => 42

pairs#

(pairs coll)

Gets the pairs of an associative data structure.

Example:

(pairs {:a 1 :b 2}) ; => ([:a 1] [:b 2])

parents#

(parents tag)
(parents h tag)

Returns the set of immediate parents of tag, or nil. When a hierarchy is provided, consults it; otherwise uses the global hierarchy.

parse-boolean#

(parse-boolean s)

Parses a string as a boolean. Returns true for the exact string "true", false for "false", and nil for any other input. The match is case-sensitive and does not tolerate surrounding whitespace.

Example:

(parse-boolean "true") ; => true
(parse-boolean "True") ; => nil

parse-double#

(parse-double s)

Parses a string as a float. Returns nil for non-numeric input or for inputs that are not strings. Accepts Infinity, -Infinity, and NaN alongside regular decimal and scientific notation.

Example:

(parse-double "3.14") ; => 3.14
(parse-double "Infinity") ; => INF

parse-long#

(parse-long s)

Parses a string as an integer. Returns nil if parsing fails.

Example:

(parse-long "123") ; => 123

parse-uuid#

(parse-uuid s)

Parses s as a canonical UUID string and returns a Phel\Lang\UUID value, or nil if s is not a valid canonical UUID. Already-typed UUID values pass through unchanged.

Example:

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

partial#

(partial f & args)

Takes a function f and fewer than normal arguments of f and returns a function that a variable number of additional arguments. When call f will be called with args and the additional arguments.

partition#

(partition n coll)

Partitions collection into chunks of size n, dropping incomplete final partition.

Example:

(partition 3 [1 2 3 4 5 6 7]) ; => ([1 2 3] [4 5 6])

partition-all#

(partition-all n coll)

Partitions collection into chunks of size n, including incomplete final partition.

Example:

(partition-all 3 [1 2 3 4 5 6 7]) ; => ([1 2 3] [4 5 6] [7])

partition-by#

(partition-by f coll)

Returns a lazy sequence of partitions. Applies f to each value in coll, splitting them each time the return value changes.

Example:

(partition-by #(< % 3) [1 2 3 4 5 1 2]) ; => [[1 2] [3 4 5] [1 2]]

peek#

(peek coll)

Returns the head of a vector / PHP array (the last element) or the head of a list / lazy sequence / queue (the first element). Returns nil if coll is empty or nil.

Example:

(peek [1 2 3]) ; => 3
(peek '(:a :b :c)) ; => :a

persistent#

(persistent coll)

Converts a transient collection back to a persistent collection.

Example:

(def t (transient {}))

persistent!#

(persistent! coll)

Converts a transient collection back to a persistent collection. Alias for persistent, matching Clojure's persistent! naming.

Example:

(persistent! (conj! (transient []) 1 2 3)) ; => [1 2 3]

phel->php#

(phel->php x)

Recursively converts a Phel data structure to a PHP array.

Example:

(phel->php {:a [1 2 3] :b {:c 4}}) ; => (PHP array ["a" => [1, 2, 3], "b" => ["c" => 4]])

php->phel#

(php->phel x)

Recursively converts a PHP array to Phel data structures.

Indexed PHP arrays become vectors, associative PHP arrays become maps.

Example:

(php->phel (php-associative-array "a" 1 "b" 2)) ; => {"a" 1 "b" 2}

php-array-to-map#

(php-array-to-map arr)

Converts a PHP Array to a Phel map.

Example:

(php-array-to-map (php-associative-array "a" 1 "b" 2)) ; => {"a" 1 "b" 2}

php-array?#

(php-array? x)

Returns true if x is a PHP Array, false otherwise.

php-associative-array#

(php-associative-array & xs)

Creates a PHP associative array from key-value pairs.

Arguments: Key-value pairs (must be even number of arguments)

Example:

(php-associative-array "name" "Alice" "age" 30) ; => (PHP array ["name" => "Alice", "age" => 30])

php-indexed-array#

(php-indexed-array & xs)

Creates a PHP indexed array from the given values.

Example:

(php-indexed-array 1 2 3) ; => (PHP array [1, 2, 3])

php-object?#

(php-object? x)

Returns true if x is a PHP object, false otherwise.

php-resource?#

(php-resource? x)

Returns true if x is a PHP resource, false otherwise.

pmap#

(pmap f & colls)

Like map, but applies f to elements concurrently via fibers.

Returns a vector of results in the original order. With multiple collections, applies f to corresponding elements from each collection, stopping when the shortest collection is exhausted.

PHP fibers are cooperative on a single thread, so pmap overlaps IO-bound work (HTTP, DB, file IO) but does not parallelize CPU-bound computations across cores, unlike clojure.core/pmap, which uses a thread pool. ClojureScript and Basilisp follow the same single-threaded model.

Example:

(pmap inc [1 2 3]) ; => [2 3 4]

pop#

(pop coll)

Removes the last element of a collection. Returns nil for nil.

pop!#

(pop! tcoll)

Removes the last element from a transient vector, mutating it in place. Raises InvalidArgumentException when tcoll is not a transient vector. Matches Clojure's pop! semantics.

Example:

(persistent! (pop! (transient [1 2 3]))) ; => [1 2]

pos-int?#

(pos-int? x)

Returns true if x is a positive integer (greater than zero). Accepts both fixed-precision PHP int and arbitrary-precision BigInt values.

Example:

(pos-int? 1) ; => true
(pos-int? 0) ; => false
(pos-int? (bigint 5)) ; => true

pos?#

(pos? x)

Checks if x is greater than zero.

prefer-method#

(prefer-method multi-name dispatch-val-x dispatch-val-y)

Causes the multimethod to prefer matches of dispatch-val-x over dispatch-val-y when there is an ambiguity (both match via the hierarchy and neither is more specific). Preferences are transitive.

Throws if the new preference would create a cycle, i.e. y is already (transitively) preferred over x.

Example:

(prefer-method draw :drawable :shape)

prefers#

(prefers multi-name)

Returns the preference map for a multimethod (built by prefer-method). Keys are dispatch values; values are sets of dispatch values they are preferred over (directly; preference is transitive when consulted).

Example:

(prefers draw)

prefers?#

(prefers? prefers-map x y)

Returns true if dispatch value x is preferred over y in prefers-map, considering transitive preferences. Used by multimethod dispatch when multiple methods match and the hierarchy does not pick a unique winner.

print#

(print & xs)

Prints the given values to the default output stream. Returns nil.

(print-str & xs)

Same as print. But instead of writing it to an output stream, the resulting string is returned.

printf#

(printf fmt & xs)

Output a formatted string. See PHP's printf for more information.

println#

(println & xs)

Same as print followed by a newline.

promise#

(promise)

Returns a new unrealized promise. Deliver a value with (deliver p v) and read it back with @p (or (deref p)).

Once delivered the value is frozen; subsequent deliver calls are no-ops. deref on an unrealized promise blocks: from inside a fiber it suspends cooperatively, from the top level it drains the scheduler ready queue and sleeps briefly between checks.

Example:

(let [p (promise)] (deliver p 42) @p) ; => 42

protocol-type-key#

(protocol-type-key x)

Returns the dispatch key for protocol dispatch. Returns a type keyword for primitive types, or the PHP class name string for objects/structs.

Optimized to avoid the full type cond chain: checks scalars first (most common in tight loops), then objects.

push#

Deprecated: 0.25.0, Use conj instead

(push coll x)

Inserts x at the end of the sequence coll.

put#

Deprecated: 0.25.0, Use assoc instead

(put ds key value)

Puts value mapped to key on the datastructure ds. Returns ds.

put-in#

Deprecated: 0.25.0, Use assoc-in instead

(put-in ds ks v)

Puts a value into a nested data structure.

queue#

Creates a persistent FIFO queue. With no arguments returns an empty queue; with arguments returns a queue with the values pushed in order so that the first argument is at the front.

Example:

(queue 1 2 3) ; => first 1, then 2, then 3

queue?#

(queue? x)

Returns true if x is a Phel\Lang\Collections\Queue\PersistentQueue value.

Example:

(queue? (queue 1 2 3)) ; => true

quot#

(quot dividend divisor)

Returns the truncated integer quotient of dividend / divisor. Truncates toward zero. Throws \DivisionByZeroError when divisor is zero.

Example:

(quot 7 3) ; => 2
(quot -7 3) ; => -2

quote#

(quote form)

Returns the unevaluated form.

Example:

(quote (+ 1 2)) ; => '(+ 1 2)

rand#

(rand)
(rand n)

Without arguments, returns a random number in [0, 1). With one argument n, returns a random number in [0, n).

Example:

(rand) ; => 0.42
(rand 100) ; => 73.2

rand-int#

(rand-int n)

Returns a random number between 0 and n.

rand-nth#

(rand-nth xs)

Returns a random item from xs.

random-uuid#

(random-uuid)

Returns a random version 4 UUID as a Phel\Lang\UUID value.

Example:

(random-uuid) ; => #uuid "550e8400-e29b-41d4-a716-446655440000"

range#

(range & args)

Creates a lazy sequence of numbers. With no arguments returns an infinite sequence starting at 0. With one argument returns (0..n). With two (start..end). With three (start..end step). Note: the infinite sequence is bounded by PHP_INT_MAX.

Example:

(range 5) ; => (0 1 2 3 4)

ratio?#

(ratio? x)

Returns true if x is a Ratio value. Integer-valued rationals auto-collapse to int/BigInt at construction time, so (ratio? 2/2) is false.

Example:

(ratio? 1/2) ; => true
(ratio? 0.5) ; => false

rationalize#

(rationalize x)

Converts x to a Ratio. Floats use the shortest decimal expansion that round-trips back to the same float, so (rationalize 0.1) is 1/10 rather than the float-noise denominator. Ints, BigInt, and integer-valued BigDecimal values become n/1 and auto-collapse, so they are returned as the integer value. BigDecimal with a fractional part rationalizes through its canonical decimal form.

Example:

(rationalize 0.5) ; => 1/2
(rationalize 3) ; => 3
(rationalize 1M) ; => 1

re-find#

(re-find re s)

Returns the first match of pattern in string, or nil if no match. If the pattern has groups, returns a vector of [full-match group1 group2 ...].

Example:

(re-find #"\d+" "abc123def") ; => "123"

re-matches#

(re-matches re s)

Returns the match, if any, of string to pattern. If the pattern has groups, returns a vector of [full-match group1 group2 ...]. Returns nil if no match. Unlike re-find, the entire string must match.

Example:

(re-matches #"(\d+)-(\d+)" "12-34") ; => ["12-34" "12" "34"]

re-pattern#

(re-pattern s)

Returns a PCRE pattern string from s. If s is already delimited, returns it as-is. Otherwise wraps in / delimiters.

Example:

(re-pattern "\\d+") ; => "/\\d+/"

re-seq#

(re-seq re s)

Returns a sequence of successive matches of pattern in string.

Example:

(re-seq #"\d+" "a1b2c3") ; => ["1" "2" "3"]

read-file-lazy#

(read-file-lazy filename)
(read-file-lazy filename chunk-size)

Returns a lazy sequence of byte chunks from a file.

Example:

(take 5 (read-file-lazy "large-file.bin" 1024)) ; => ["chunk1" "chunk2" ...]

read-string#

(read-string s)

Reads the first phel expression from the string s.

realized?#

(realized? coll)

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

Example:

(realized? (take 5 (iterate inc 1))) ; => false

recur#

(recur expr*)

Internally recur is implemented as a PHP while loop and therefore prevents the Maximum function nesting level errors.

Example:

(loop [n 5 acc 1] (if (<= n 1) acc (recur (dec n) (* acc n))))

reduce#

(reduce f & args)

Reduces collection to a single value by repeatedly applying function to accumulator and elements. Respects early termination via (reduced val).

Example:

(reduce + [1 2 3 4]) ; => 10

reduced#

(reduced x)

Wraps x in a Reduced, signaling early termination from reduce/transduce.

reduced?#

(reduced? x)

Returns true if x is a Reduced value.

register-protocol-implementor!#

(register-protocol-implementor! type-key protocol-value protocol-tag)

Records that type-key implements the protocol identified by both protocol-value (the defprotocol map) and protocol-tag (its FQN string). Called from extend-type's expansion.

reify#

(reify & specs)

Creates an anonymous object implementing one or more protocols. Method bodies close over local bindings. Each instance carries its own captured state, so reify works correctly inside loops.

Syntax: (reify ProtocolName (method-name [this arg1] body) AnotherProtocol (another-method [this] body))

Example:

(reify Speakable (speak [this] "hello"))

rem#

(rem dividend divisor)

Returns the truncated remainder of dividend / divisor. The result has the same sign as dividend (matches PHP's %).

Example:

(rem 7 3) ; => 1
(rem -7 3) ; => -1

remove#

(remove pred & args)

Returns a lazy sequence of elements where predicate returns false. Opposite of filter. When called with pred only, returns a transducer.

Example:

(remove even? [1 2 3 4 5 6]) ; => (1 3 5)

remove-ns#

(remove-ns ns-str)

Removes the namespace and all of its definitions from the registry. Use with caution. Returns nil.

Example:

(remove-ns "my-app\tmp")

remove-tap#

(remove-tap f)

Removes f from the tap set. Returns nil.

remove-watch#

(remove-watch variable key)

Removes a watch function from a variable by key.

rename-keys#

(rename-keys m kmap)

Returns the map with keys renamed according to kmap. Keys not present in kmap are left unchanged.

Example:

(rename-keys {:a 1 :b 2 :c 3} {:a :x :b :y}) ; => {:x 1 :y 2 :c 3}

repeat#

(repeat a & rest)

Returns a vector of length n where every element is x.

With one argument returns an infinite lazy sequence of x.

Example:

(repeat 3 :a) ; => [:a :a :a]

repeatedly#

(repeatedly a & rest)

Returns a vector of length n with values produced by repeatedly calling f.

With one argument returns an infinite lazy sequence of calls to f.

Example:

(repeatedly 3 rand) ; => [0.234 0.892 0.456] (random values)

reset!#

(reset! variable value)

Sets a new value on the given atom. Returns the new value.

Example:

(def x (atom 10))

reset-meta!#

(reset-meta! r meta-map)

Installs meta-map as the metadata on r, replacing any prior metadata. Works on Var handles and on atoms. Returns the installed map.

Example:

(reset-meta! #'my-var {:tag :int})

resolve#

(resolve sym)

Resolves the given symbol in the current environment and returns a resolved Symbol with the absolute namespace or nil if it cannot be resolved.

Example:

(resolve 'map) ; => phel\core/map

rest#

(rest coll)

Returns the sequence after the first element, or empty sequence if none.

Example:

(rest [1 2 3]) ; => [2 3]

reverse#

(reverse coll)

Reverses the order of the elements in the given sequence.

Example:

(reverse [1 2 3 4]) ; => [4 3 2 1]

reversible?#

(reversible? coll)

Returns true if coll can be reverse-iterated in constant time. Currently this is true for vectors, sorted-maps, and sorted-sets.

Example:

(reversible? [1 2 3]) ; => true

round#

(round x)

Rounds x to the nearest integer using PHP's round (half away from zero). Ints and BigInt values are returned unchanged. Ratios and floats return floats.

Example:

(round 1.5) ; => 2.0
(round -1.5) ; => -2.0
(round 5) ; => 5

rseq#

(rseq rev)

Returns, in constant time, a sequence of the items in rev in reverse order. rev must be reversible (a vector, sorted-map, or sorted-set); otherwise an exception is thrown. For sorted-maps, returns reversed [key value] pairs. Returns nil if rev is empty.

Example:

(rseq [1 2 3]) ; => (3 2 1)

run!#

(run! f coll)

Calls (f x) for each element in coll for side effects. Returns nil.

Example:

(run! println [1 2 3])

satisfies?#

(satisfies? protocol x)

Returns true if x's type implements all methods of the given protocol.

Example:

(satisfies? Stringable "hello")

second#

(second coll)

Returns the second element of a sequence, or nil if not present.

Example:

(second [1 2 3]) ; => 2

select-keys#

(select-keys m ks)

Returns a new map including key value pairs from m selected with keys ks.

Example:

(select-keys {:a 1 :b 2 :c 3} [:a :c]) ; => {:a 1 :c 3}

seq#

(seq coll)

Returns a seq on the collection. Strings are converted to a vector of characters. Other non-empty collections (vectors, sets, sorted-maps, sorted-sets, PHP arrays) are converted to a non-list seq. Returns nil if coll is empty or nil.

This function is useful for explicitly converting strings to sequences of characters, enabling sequence operations like map, filter, and frequencies.

Example:

(seq "hello") ; => ["h" "e" "l" "l" "o"]
(seq [1 2 3]) ; => (1 2 3)

seq?#

(seq? x)

Returns true if x is a seq (a list, a lazy sequence, or a realized Cons cell returned by (next some-lazy-seq)).

seqable?#

(seqable? x)

Returns true if (seq x) is supported: collections (vectors, lists, maps, sets, structs), lazy sequences, strings, PHP arrays, and nil. Returns false for numbers, booleans, keywords, symbols, and other types.

Example:

(seqable? [1 2]) ; => true
(seqable? 42) ; => false

sequence#

(sequence xform coll)

Applies transducer xform to coll, returning a vector of results.

Example:

(sequence (comp (filter even?) (map inc)) [1 2 3 4 5]) ; => [3 5]

sequential?#

(sequential? x)

Returns true if x is a sequential collection (vector, list, or lazy sequence), false otherwise. Sequential collections maintain insertion order and support indexed or linear access. Maps, sets, and structs are not sequential, matching Clojure's Sequential marker.

Example:

(sequential? [1 2 3]) ; => true
(sequential? {:a 1}) ; => false

set#

(set coll)

Coerces a collection to a set. Returns a set containing the distinct elements of coll. For creating sets from arguments, use hash-set.

Example:

(set [1 2 3 2 1]) ; => #{1 2 3}

set-meta!#

Deprecated: 0.32.0, Use with-meta instead Sets the metadata to a given object.

set-validator!#

(set-validator! variable f)

Sets a validator function on a variable. The validator is called before any state change with the proposed new value. If it returns a falsy value, an exception is thrown and the state is not changed. Pass nil to remove.

Example:

(set-validator! my-var pos?)

set-var#

(var value)

Variables provide a way to manage mutable state that can be updated with set! and swap!. Each variable contains a single value. To create a variable use the var function.

Example:

(def counter (var 0))

set?#

(set? x)

Returns true if x is a set, false otherwise.

short#

(short x)

Coerces x to a signed 16-bit integer in the range -32768..32767. Decimal values are truncated toward zero. Ratio and BigInt values are accepted (truncate toward zero, then range-check). Values outside the range or non-numeric inputs raise InvalidArgumentException. Phel has no dedicated short type, so the result is a plain PHP int.

Example:

(short 32767) ; => 32767
(short 1.9) ; => 1
(short -32768) ; => -32768

short-array#

(short-array size-or-seq)
(short-array size init-val-or-seq)

Creates a PHP array of shorts (16-bit integers). Accepts the same arities and semantics as int-array.

Example:

(short-array 3) ; => PHP array [0, 0, 0]
(short-array 4 7) ; => PHP array [7, 7, 7, 7]

shuffle#

(shuffle coll)

Returns a random permutation of coll.

Example:

(shuffle [1 2 3 4 5]) ; => [3 1 5 2 4] (random order)

simple-ident?#

(simple-ident? x)

Returns true if x is a symbol or keyword without a namespace.

simple-keyword?#

(simple-keyword? x)

Returns true if x is a keyword without a namespace.

simple-symbol?#

(simple-symbol? x)

Returns true if x is a symbol without a namespace.

slice#

(slice coll & [offset & [length]])

Extracts a slice of coll starting at offset with optional length.

Example:

(slice [1 2 3 4 5] 1 3) ; => [2 3 4]

slurp#

(slurp path & [opts])

Reads entire file or URL into a string.

Example:

(slurp "file.txt") ; => "file contents"

some#

(some pred coll)

Returns the first truthy value of applying predicate to elements, or nil if none found.

Example:

(some #(when (> % 10) %) [5 15 8]) ; => 15

some->#

(some-> x & forms)

Threads x through the forms like -> but stops when a form returns nil.

some->>#

(some->> x & forms)

Threads x through the forms like ->> but stops when a form returns nil.

some-fn#

(some-fn p & ps)

Takes a variadic set of predicates and returns a function f that, when called with any number of arguments, returns the first logical true value produced by applying any of the composing predicates to any of its arguments, and false when none match. The returned function short-circuits on the first truthy result: arguments after it are not inspected, and predicates after it are not tried. Predicates are consulted in the order supplied; for a given predicate, arguments are consulted left-to-right.

Example:

((some-fn even? nil?) 1 2) ; => true
((some-fn pos? even?) -3 -1) ; => false

some?#

(some? x)
(some? pred coll)

With 1 arg, returns true if x is not nil (Clojure semantics). With 2 args, returns true if pred is true for at least one element in coll.

Example:

(some? 1) ; => true
(some? even? [1 3 5 6 7]) ; => true

sort#

(sort coll)
(sort a b)

Returns a sorted vector. If no comparator is supplied compare is used.

Example:

(sort [3 1 4 1 5 9 2 6]) ; => [1 1 2 3 4 5 6 9]
(sort (fn [a b] (compare b a)) [1 2 3]) ; => [3 2 1]

sort-by#

(sort-by keyfn coll)
(sort-by keyfn comp-or-coll coll-or-comp)

Returns a sorted vector where the sort order is determined by comparing (keyfn item).

If no comparator is supplied compare is used.

Example:

(sort-by count ["aaa" "c" "bb"]) ; => ["c" "bb" "aaa"]
(sort-by count compare ["aaa" "c" "bb"]) ; => ["c" "bb" "aaa"]

sorted-map#

(sorted-map & xs)

Creates a new sorted map. Keys are in natural sorted order. The number of parameters must be even.

Example:

(sorted-map :c 3 :a 1 :b 2) ; keys iterate as :a :b :c

sorted-map-by#

(sorted-map-by comp & xs)

Creates a new sorted map using the given comparator for key ordering. The comparator takes two arguments and returns a negative integer, zero, or a positive integer.

Example:

(sorted-map-by (fn [a b] (compare b a)) :a 1 :b 2) ; keys iterate as :b :a

sorted-set#

(sorted-set & xs)

Creates a new sorted set. Elements are in natural sorted order.

Example:

(sorted-set 3 1 2) ; iterates as 1 2 3

sorted-set-by#

(sorted-set-by comp & xs)

Creates a new sorted set using the given comparator for element ordering.

Example:

(sorted-set-by (fn [a b] (compare b a)) 3 1 2) ; iterates as 3 2 1

sorted?#

(sorted? coll)

Returns true if coll is a sorted collection (sorted-map or sorted-set), false otherwise.

Example:

(sorted? (sorted-set 1 2 3)) ; => true

special-symbol?#

(special-symbol? s)

Returns true if s names a special form.

Example:

(special-symbol? 'def) ; => true
(special-symbol? 'map) ; => false

spit#

(spit filename data & [opts])

Writes data to file, returning number of bytest that were written or nil on failure. Accepts opts map for overriding default PHP file_put_contents arguments, as example to append to file use {:flags php/FILE_APPEND}.

See PHP's file_put_contents for more information.

split-at#

(split-at n coll)

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

Example:

(split-at 2 [1 2 3 4 5]) ; => [[1 2] [3 4 5]]

split-with#

(split-with f coll)

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

Example:

(split-with #(< % 4) [1 2 3 4 5 6]) ; => [[1 2 3] [4 5 6]]

sqrt#

(sqrt x)

Returns the square root of x as a float. Negative inputs return ##NaN (matches PHP's sqrt).

Example:

(sqrt 9) ; => 3.0
(sqrt 2) ; => 1.4142135623730951

str#

(str & args)

Creates a string by concatenating values together. If no arguments are provided an empty string is returned. Nil is represented as an empty string. Booleans are represented as "true" or "false" (matching Clojure semantics). Otherwise, it tries to call __toString.

str-contains?#

Deprecated: Use phel\string\contains?

(str-contains? str s)

Returns true if str contains s.

string?#

(string? x)

Returns true if x is a string, false otherwise.

struct?#

(struct? x)

Returns true if x is a struct, false otherwise.

subset?#

(subset? s1 s2)

Returns true if s1 is a subset of s2, i.e. every element in s1 is also in s2.

Example:

(subset? (hash-set 1 2) (hash-set 1 2 3)) ; => true

sum#

(sum xs)

Returns the sum of all elements is xs.

superset?#

(superset? s1 s2)

Returns true if s1 is a superset of s2, i.e. every element in s2 is also in s1.

Example:

(superset? (hash-set 1 2 3) (hash-set 1 2)) ; => true

swap!#

(swap! variable f & args)

Atomically swaps the value of the atom to (apply f current-value args).

Returns the new value after the swap.

Example:

(def counter (atom 0))

symbol#

(symbol name-or-ns & [name])

Returns a new symbol for the given name with an optional namespace.

With one argument, creates a symbol without namespace. Accepts a string, a keyword, another symbol, or a Var (in which case the result is a fully qualified symbol naming the var). With two arguments, creates a symbol in the given namespace; a nil namespace yields a symbol without a namespace.

Throws InvalidArgumentException for any other input (including functions, numbers, and collections).

Example:

(symbol "foo") ; => foo
(symbol :abc) ; => abc
(symbol nil "foo") ; => foo
(symbol #'phel.core/+) ; => phel.core/+

symbol?#

(symbol? x)

Returns true if x is a symbol, false otherwise.

symmetric-difference#

(symmetric-difference set & sets)

Symmetric difference between multiple sets into a new one.

take#

(take n & args)

Takes the first n elements of coll. When called with n only, returns a transducer.

take-last#

(take-last n coll)

Takes the last n elements of coll.

Example:

(take-last 3 [1 2 3 4 5]) ; => [3 4 5]

take-nth#

(take-nth n & args)

Returns every nth item in coll. Returns a lazy sequence. When called with n only, returns a transducer.

Example:

(take-nth 2 [0 1 2 3 4 5 6 7 8]) ; => (0 2 4 6 8)

take-while#

(take-while pred & args)

Takes all elements at the front of coll where (pred x) is true. Returns a lazy sequence. When called with pred only, returns a transducer.

Example:

(take-while #(< % 5) [1 2 3 4 5 6 3 2 1]) ; => (1 2 3 4)

tap>#

(tap> x)

Sends x to every registered tap. Exceptions thrown by individual taps are swallowed so one misbehaving tap does not affect the others. Returns true.

Example:

(add-tap println)
(tap> {:event :login :user "alice"})

thread-bound?#

(thread-bound? v)

Returns true when a fiber-local binding (or with-bindings) frame currently overrides the value of v on the calling fiber.

Example:

(binding [*foo* 1] (thread-bound? #'*foo*)) ; => true

throw#

(throw exception)

Throw an exception.

Example:

(throw (php/new \InvalidArgumentException "Invalid input"))

time#

(time expr)

Evaluates expr and prints the time it took. Returns the value of expr.

to-array#

(to-array coll)

Returns a PHP array containing the elements of coll. Accepts any collection (vector, list, set, map, PHP array) or nil, which yields an empty PHP array. Matches Clojure's to-array for .cljc interop, in Phel the result is a plain PHP array since PHP has no Object[].

Example:

(to-array [1 2 3]) ; => a PHP array [1, 2, 3]
(to-array nil) ; => a PHP array []

to-php-array#

Creates a PHP Array from a sequential data structure.

transduce#

(transduce xform f & args)

Reduce with a transformation of f (xf). If init is not supplied, (f) will be called to produce it. f should be a reducing function that returns the initial value when called with no arguments.

Example:

(transduce (map inc) + [1 2 3]) ; => 9

transient#

(transient coll)

Converts a persistent collection to a transient collection for efficient updates.

Transient collections provide faster performance for multiple sequential updates. Use persistent to convert back.

Example:

(def t (transient []))

tree-seq#

(tree-seq branch? children root)

Returns a vector of the nodes in the tree, via a depth-first walk. branch? is a function with one argument that returns true if the given node has children. children must be a function with one argument that returns the children of the node. root the root node of the tree.

true?#

(true? x)

Checks if value is exactly true (not just truthy).

Example:

(true? 1) ; => false

truthy?#

(truthy? x)

Checks if x is truthy. Same as x == true in PHP.

try#

(try expr* catch-clause* finally-clause?)

All expressions are evaluated and if no exception is thrown the value of the last expression is returned. If an exception occurs and a matching catch-clause is provided, its expression is evaluated and the value is returned. If no matching catch-clause can be found the exception is propagated out of the function. Before returning normally or abnormally the optionally finally-clause is evaluated.

Example:

(try (/ 1 0) (catch \Exception e "error"))

type#

(type x)

Returns the type of x. The following types can be returned:

  • :vector
  • :list
  • :struct
  • :hash-map
  • :map-entry
  • :set
  • :keyword
  • :symbol
  • :atom
  • :var
  • :int
  • :float
  • :ratio
  • :bigint
  • :bigdec
  • :uuid
  • :php/class
  • :queue
  • :string
  • :nil
  • :boolean
  • :function
  • :php/array
  • :php/resource
  • :php/object
  • :unknown

underive#

(underive child parent)
(underive h child parent)

Removes a parent/child relationship. With two arguments, mutates the global hierarchy and returns nil. With a hierarchy h, returns a new hierarchy without the relationship; the original is unchanged.

Example:

(underive :square :shape)

union#

(union & sets)

Union multiple sets into a new one.

unquote#

(unquote my-sym) ; Evaluates to my-sym
,my-sym          ; Shorthand for (same as above)

Values that should be evaluated in a macro are marked with the unquote function. Shortcut: ,

Example:

`(+ 1 ,(+ 2 3)) ; => (+ 1 5)

unquote-splicing#

(unquote-splicing my-sym) ; Evaluates to my-sym
,@my-sym                  ; Shorthand for (same as above)

Values that should be evaluated in a macro are marked with the unquote function. Shortcut: ,@

Example:

`(+ ,@[1 2 3]) ; => (+ 1 2 3)

unreduced#

(unreduced x)

If x is Reduced, returns the unwrapped value; otherwise returns x.

unset#

Deprecated: 0.25.0, Use dissoc instead

(unset ds key)

Returns ds without key.

unset-in#

Deprecated: 0.25.0, Use dissoc-in instead

(unset-in ds ks)

Removes a value from a nested data structure.

update#

(update ds k f & args)

Updates a value in a datastructure by applying f to the current value.

Example:

(update {:count 5} :count inc) ; => {:count 6}

update-in#

(update-in ds [k & ks] f & args)

Updates a value in a nested data structure by applying f to the value at path.

Example:

(update-in {:a {:b 5}} [:a :b] inc) ; => {:a {:b 6}}

update-keys#

(update-keys m f)

Returns a map with f applied to each key.

Example:

(update-keys {:a 1 :b 2} name) ; => {"a" 1 "b" 2}

update-vals#

(update-vals m f)

Returns a map with f applied to each value.

Example:

(update-vals {:a 1 :b 2} inc) ; => {:a 2 :b 3}

uuid-nil?#

(uuid-nil? x)

Returns true if x is the nil UUID (all zeros), false otherwise.

Example:

(uuid-nil? #uuid "00000000-0000-0000-0000-000000000000") ; => true

uuid-variant#

(uuid-variant x)

Returns a keyword describing the variant field of UUID x: :ncs, :rfc-4122, :microsoft, or :reserved. Returns nil if x is not a UUID value.

Example:

(uuid-variant #uuid "550e8400-e29b-41d4-a716-446655440000") ; => :rfc-4122

uuid-version#

(uuid-version x)

Returns the version digit (1-5) encoded in UUID x, or nil if x is not a UUID value.

Example:

(uuid-version #uuid "550e8400-e29b-41d4-a716-446655440000") ; => 4

uuid=#

(uuid= a b)

Returns true if a and b are Phel\Lang\UUID values with the same canonical form. Strings (or anything else) are rejected even if their textual content would match, coerce with parse-uuid first.

Example:

(uuid= #uuid "550e8400-e29b-41d4-a716-446655440000"
         #uuid "550E8400-E29B-41D4-A716-446655440000") ; => true

uuid?#

(uuid? x)

Returns true if x is a Phel\Lang\UUID value, false otherwise. Canonical UUID strings are rejected, wrap them with parse-uuid (or the #uuid "..." literal) to obtain a typed value.

Example:

(uuid? #uuid "550e8400-e29b-41d4-a716-446655440000") ; => true

val#

(val entry)

Returns the value of a map entry. Accepts a typed Phel\Lang\Collections\Map\MapEntry value or a 2-element vector [key value].

Example:

(val (first (pairs {:a 1}))) ; => 1

vals#

(vals coll)

Returns a sequence of all values in a map, or nil when the map is nil or empty.

Example:

(vals {:a 1 :b 2}) ; => (1 2)
(vals nil) ; => nil

values#

Deprecated: 0.32.0, Use vals instead

(values coll)

Returns a sequence of all values in a map.

Example:

(values {:a 1 :b 2}) ; => (1 2)

var-get#

(var-get x)
(var-get x not-found)

Resolves the value bound to a Var or to a fully-qualified symbol.

Accepts a Var instance (typically from (var sym) or #'sym) and returns its current root value. Accepts a fully-qualified symbol and reads the matching definition from the registry; tries the symbol name verbatim first, then the encoded form, so it pairs with both def and intern.

With one argument, returns nil when the symbol is not defined. With two arguments, returns not-found instead, which lets callers disambiguate a stored nil from a missing definition. Returns not-found for non-symbol or unqualified inputs.

Example:

(var-get #'phel.core/map) ; => <fn>
(var-get (intern "user" "x" 42)) ; => 42
(var-get 'user/missing ::none) ; => ::none

var-set#

(var-set v val)

Sets the value of the topmost active fiber-local binding frame for v to val. Throws when no binding (or with-bindings) frame is currently overriding v. Returns val.

Example:

(def ^:dynamic *x* 0)
(binding [*x* 1] (var-set #'*x* 2) *x*) ; => 2

var?#

(var? x)

Returns true if the given value is a Var, the first-class handle to a global definition produced by (var sym) and #'sym.

vary-meta#

Returns an object with (apply f (meta obj) args) as its new metadata.

vec#

(vec coll)

Coerces a collection to a vector. For hash-maps and structs, entries are returned as 2-element [key value] vectors, matching Clojure.

Example:

(vec {:a 1 :b 2}) ; => [[:a 1] [:b 2]]

vector#

(vector 1 2 3) ; => [1 2 3]

Creates a new vector. If no argument is provided, an empty vector is created. Shortcut: []

Example:

(vector 1 2 3) ; => [1 2 3]

vector?#

(vector? x)

Returns true if x is a vector. Map entries returned by iterating a hash map ((first {:a 1})) are vector-shaped two-element values, so this predicate also accepts the typed MapEntry.

volatile!#

(volatile! val)

Creates a volatile mutable reference with initial value val. Use for transducer state that needs fast mutation without watches.

volatile?#

(volatile? x)

Returns true if x is a Volatile.

vreset!#

(vreset! vol val)

Sets the value of volatile vol to val. Returns val.

vswap!#

(vswap! vol f & args)

Applies f to the current value of volatile vol plus args, and sets the new value. Returns the new value.

when#

(when test & body)

Evaluates body if test is true, otherwise returns nil.

Example:

(when (> 10 5) "greater") ; => "greater"

when-first#

(when-first bindings & body)

Binds name to the first element of coll. When the collection is non-empty (first returns non-nil), evaluates body with the binding.

when-let#

(when-let bindings & body)

When test is true, evaluates body with binding-form bound to the value of test

when-not#

(when-not test & body)

Evaluates body if test is false, otherwise returns nil.

Example:

(when-not (empty? [1 2 3]) "has items") ; => "has items"

when-some#

(when-some bindings & body)

Binds name to the value of test. When test is not nil, evaluates body with binding-form bound to the value of test. Unlike when-let, false and 0 are not treated as falsy, only nil causes the body to be skipped.

with-bindings#

(with-bindings m & body)

Like binding but takes a map of Var -> value instead of a binding vector. Same dynamic-only enforcement: throws when any key resolves to a non-dynamic var.

with-meta#

Returns obj with the given metadata meta attached.

with-output-buffer#

(with-output-buffer & body)

Everything that is printed inside the body will be stored in a buffer. The result of the buffer is returned.

with-redefs#

(with-redefs bindings & body)

Temporarily replaces the root values of vars while executing body.

Accepts any var, dynamic or not. The previous root values are captured before body runs and restored on exit, including when body throws. The replacement is process-global: every fiber sees the new root for the duration of the body, which makes this a convenient mocking primitive for tests but unsafe for concurrent production code. Use binding for fiber-local rebinding of ^:dynamic vars.

zero?#

(zero? x)

Checks if x is zero.

zipcoll#

(zipcoll a b)

Creates a map from two sequential data structures. Returns a new map.

Example:

(zipcoll [:a :b :c] [1 2 3]) ; => {:a 1 :b 2 :c 3}

zipmap#

(zipmap keys vals)

Returns a new map with the keys mapped to the corresponding values.

Stops when the shorter of keys or vals is exhausted. Works safely with infinite lazy sequences.

Example:

(zipmap [:a :b :c] [1 2 3]) ; => {:a 1 :b 2 :c 3}