core
Jump to function (545) ›
- %
- *
- *'
- **
- *argv*
- *assert*
- *build-mode*
- *file*
- *ns*
- *program*
- +
- +'
- -
- -'
- ->
- ->>
- ->closure
- /
- <
- <=
- <=>
- =
- ==
- >
- >=
- >=<
- NAN
- NaN?
- abs
- aclone
- add-tap
- add-watch
- aget
- alength
- all?
- alter-meta!
- alter-var-root
- ancestors
- and
- any?
- apply
- arity
- array-map
- as->
- aset
- assert
- assoc
- assoc!
- assoc-in
- associative?
- async
- atom
- atom?
- await
- await-all
- await-any
- bean
- bigdec
- bigdec?
- bigint
- bigint?
- biginteger
- binding
- bit-and
- bit-and-not
- bit-clear
- bit-flip
- bit-not
- bit-or
- bit-set
- bit-shift-left
- bit-shift-right
- bit-test
- bit-xor
- boolean
- boolean?
- bound?
- bounded-count
- break
- butlast
- byte
- canonical-ns
- case
- cat
- catch
- ceil
- char
- char?
- class
- class-name
- class?
- coerce-in
- coll?
- comment
- comp
- compact
- compare
- compare-and-set!
- compile
- complement
- completing
- concat
- cond
- cond->
- cond->>
- condp
- conj
- conj!
- cons
- constantly
- contains-value?
- contains?
- count
- counted?
- create-ns
- csv-seq
- cycle
- dbg
- dbg-write
- dec
- dec'
- decimal?
- declare
- dedupe
- deep-merge
- def
- def-
- defenum
- defexception
- defexception*
- definterface
- definterface*
- defmacro
- defmacro-
- defmethod
- defmulti
- defn
- defn-
- defonce
- defprotocol
- defrecord
- defstruct
- defstruct*
- deftype
- delay
- delay?
- deliver
- denominator
- deref
- derive
- descendants
- difference
- disj
- disj!
- display-ns
- dissoc
- dissoc!
- dissoc-in
- distinct
- distinct?
- do
- doall
- dofor
- dorun
- doseq
- doseq-iterable
- dotimes
- doto
- double
- double-array
- double?
- drop
- drop-last
- drop-while
- eduction
- empty
- empty?
- eval
- even?
- every-pred
- every?
- ex-cause
- ex-data
- ex-info
- ex-message
- extend-protocol
- extend-type
- extends?
- extreme
- false?
- ffirst
- file-seq
- filter
- filterv
- finally
- find
- find-hierarchy-method
- find-index
- find-ns
- find-var
- first
- flatten
- float
- float-array
- float?
- floor
- fn
- fn?
- fnext
- fnil
- for
- force
- foreach
- format
- frequencies
- full-name
- future
- future-call
- future-cancel
- future-cancelled?
- future-done?
- future-fiber
- future?
- gcd
- gensym
- get
- get-in
- get-validator
- group-by
- hash-map
- hash-set
- hydrate
- ident?
- identical?
- identity
- if
- if-let
- if-not
- if-some
- ifn?
- in-ns
- inc
- inc'
- index
- indexed?
- inf?
- infinite?
- instance?
- int
- int-array
- int?
- integer?
- interleave
- intern
- interpose
- intersection
- into
- into-array
- invert
- isa?
- iterate
- iteration
- iterator-seq
- juxt
- keep
- keep-indexed
- key
- keys
- keyword
- keyword?
- kvs
- last
- lazy-cat
- lazy-seq
- lazy-seq?
- lcm
- let
- letfn
- line-seq
- list
- list?
- load
- load-file
- loaded-namespaces
- long
- long-array
- loop
- macroexpand
- macroexpand-1
- make-hierarchy
- map
- map-entry
- map-entry?
- map-indexed
- map-invert
- map?
- mapcat
- mapv
- max
- max-key
- mean
- median
- memoize
- memoize-lru
- merge
- merge-with
- meta
- min
- min-key
- mod
- name
- namespace
- nan?
- nat-int?
- neg-int?
- neg?
- next
- nfirst
- nil?
- nnext
- not
- not-any?
- not-empty
- not-every?
- not=
- ns
- ns-aliases
- ns-interns
- ns-publics
- ns-refers
- nth
- nthnext
- nthrest
- number?
- numerator
- object-array
- odd?
- one?
- or
- pairs
- parents
- parse-boolean
- parse-double
- parse-long
- parse-uuid
- partial
- partition
- partition-all
- partition-by
- peek
- persistent
- persistent!
- phel->php
- php->phel
- php-array-to-map
- php-array?
- php-associative-array
- php-indexed-array
- php-invoke
- php-object?
- php-resource?
- pmap
- pop
- pop!
- pos-int?
- pos?
- pr
- pr-str
- prefer-method
- prefers
- prefers?
- print-str
- printf
- println
- println-str
- prn
- prn-str
- project
- promise
- protocol-type-key
- queue
- queue?
- quot
- quote
- rand
- rand-int
- rand-nth
- random-sample
- random-uuid
- range
- ratio?
- rational?
- rationalize
- re-find
- re-matches
- re-pattern
- re-seq
- read-file-lazy
- read-string
- realized?
- recur
- reduce
- reduce-kv
- reduced
- reduced?
- reductions
- register-protocol-implementor!
- reify
- rem
- remove
- remove-ns
- remove-tap
- remove-watch
- rename
- rename-keys
- repeat
- repeatedly
- reset!
- reset-meta!
- reset-vals!
- resolve
- rest
- reverse
- reversible?
- round
- rseq
- rsubseq
- run!
- satisfies?
- second
- select
- select-keys
- seq
- seq?
- seqable?
- sequence
- sequential?
- set
- set!
- set-validator!
- set-var
- set?
- short
- short-array
- shuffle
- simple-ident?
- simple-keyword?
- simple-symbol?
- slice
- slurp
- some
- some->
- some->>
- some-fn
- some?
- sort
- sort-by
- sorted-map
- sorted-map-by
- sorted-set
- sorted-set-by
- sorted?
- special-symbol?
- spit
- split-at
- split-with
- splitv-at
- sqrt
- str
- string?
- struct?
- subseq
- subset?
- subvec
- sum
- superset?
- swap!
- swap-vals!
- symbol
- symbol?
- symmetric-difference
- take
- take-last
- take-nth
- take-while
- tap>
- thread-bound?
- throw
- time
- to-array
- to-php-array
- trampoline
- transduce
- transient
- tree-seq
- true?
- truthy?
- try
- type
- underive
- union
- unquote
- unquote-splicing
- unreduced
- unsigned-bit-shift-right
- update
- update-in
- update-keys
- update-vals
- use
- uuid-nil?
- uuid-variant
- uuid-version
- uuid=
- uuid?
- val
- vals
- var
- var-get
- var-set
- var?
- variadic?
- vary-meta
- vec
- vector
- vector?
- volatile!
- volatile?
- vreset!
- vswap!
- when
- when-first
- when-let
- when-not
- when-some
- while
- with-bindings
- with-meta
- with-open
- with-output-buffer
- with-redefs
- zero?
- zipcoll
- zipmap
%#
(% dividend divisor)
Alias for rem. Returns the truncated remainder of dividend /
divisor. Result has the same sign as dividend.
Example:
(% 11 2) ; => 1
*#
(*)
(* x)
(* x y)
(* x y z)
(* x y z w)
(* x y z w & more)
Returns the product of all elements in xs. All elements in xs must be numbers. If xs is empty, return 1.
Example:
(* 2 3 4) ; => 24
*'#
(*' & xs)
Auto-promoting variant of *. Integer results are returned as
BigInt; floats and rationals pass through unchanged.
Example:
(*' 2 3) ; => 6
**#
(** a x)
Return a to the power of x.
Example:
(** 2 8) ; => 256
*argv*#
Vector of user arguments passed to the script (excludes program name). Use program to get the script path or namespace.
*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.
+#
(+)
(+ x)
(+ x y)
(+ x y z)
(+ x y z w)
(+ x y z w & more)
Returns the sum of all elements in xs. All elements xs must be numbers. If xs is empty, return 0.
Example:
(+ 1 2 3) ; => 6
+'#
(+' & 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) ; => 3
-#
(-)
(- x)
(- x y)
(- x y z)
(- x y z w)
(- x y z w & more)
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.
Example:
(- 10 3 2) ; => 5
(- 4) ; => -4
-'#
(-' & xs)
Auto-promoting variant of -. Integer results are returned as
BigInt; floats and rationals pass through unchanged.
Example:
(-' 5 2) ; => 3
->#
(-> 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)))
/#
(/)
(/ x)
(/ x y)
(/ x y & more)
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.
Example:
(/ 1 2) ; => 1/2
(/ 10 2) ; => 5
<#
(< a)
(< a b)
(< a b & more)
Checks if each argument is strictly less than the following argument.
Example:
(< 1 2 3 4) ; => true
<=#
(<= a)
(<= a b)
(<= a b & more)
Checks if each argument is less than or equal to the following argument. Returns a boolean.
Example:
(<= 1 1 2) ; => true
<=>#
(<=> 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.
Example:
(<=> 1 2) ; => -1
(<=> 2 2) ; => 0
=#
(= a)
(= a b)
(= a b & more)
Checks if all values are equal (value equality, not identity).
Example:
(= [1 2 3] [1 2 3]) ; => true
==#
(== a)
(== a b)
(== a b & 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)
(> a b)
(> a b & more)
Checks if each argument is strictly greater than the following argument.
Example:
(> 4 3 2 1) ; => true
>=#
(>= a)
(>= a b)
(>= a b & more)
Checks if each argument is greater than or equal to the following argument. Returns a boolean.
Example:
(>= 3 3 2) ; => true
>=<#
(>=< a b)
Alias for the spaceship PHP operator in descending order. Returns an int.
Example:
(>=< 1 2) ; => 1
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?.
Example:
(NaN? ##NaN) ; => true
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 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)) ; => <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 index)
(aget arr index & 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-indexed-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
arity#
(arity f)
Returns the number of required parameters of the function f. For a variadic function this is the number of parameters before &. A multi-arity function compiles to a single variadic dispatch, so it reports 0.
Example:
(arity inc) ; => 1
(arity swap!) ; => 2
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.
Example:
(as-> 1 x (+ x 2) (* x 3)) ; => 9
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-indexed-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)
(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)
(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.
Example:
(atom? (atom 1)) ; => true
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 in the same order as the input collection, regardless of which Future resolves first. 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)])
bean#
(bean obj)
Returns a Phel map of the public properties of PHP object obj, with keyword keys. Inverse of hydrate for public-property objects.
Example:
(bean (hydrate "My\\Dto" {:id 1})) ; => {:id 1}
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) ; => 42
(bigint 1.9) ; => 1
(bigint "123") ; => 123
bigint?#
(bigint? x)
Returns true when x is a Phel\Lang\BigInt value.
Example:
(bigint? (Phel.Lang.BigInt/fromInt 1)) ; => true
biginteger#
(biginteger x)
Alias for bigint. Coerces x to a Phel\Lang\BigInt.
Example:
(biginteger 42) ; => 42
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.
Example:
(bit-and 12 10) ; => 8
bit-and-not#
(bit-and-not x y & args)
Bitwise and with the complement of each subsequent argument: (bit-and-not x y) is x & ~y. Additional arguments are folded in left to right, clearing every bit that is set in any of them.
Example:
(bit-and-not 0xFF 0x0F) ; => 240
bit-clear#
(bit-clear x n)
Returns the integer x with the bit at index n (0-based, least significant first) cleared to 0.
Example:
(bit-clear 7 1) ; => 5
bit-flip#
(bit-flip x n)
Returns the integer x with the bit at index n (0-based, least significant first) toggled.
Example:
(bit-flip 5 1) ; => 7
bit-not#
(bit-not x)
Bitwise complement.
Example:
(bit-not 0) ; => -1
bit-or#
(bit-or x y & args)
Bitwise or.
Example:
(bit-or 12 10) ; => 14
bit-set#
(bit-set x n)
Returns the integer x with the bit at index n (0-based, least significant first) set to 1.
Example:
(bit-set 0 2) ; => 4
bit-shift-left#
(bit-shift-left x n)
Bitwise shift left.
Example:
(bit-shift-left 1 4) ; => 16
bit-shift-right#
(bit-shift-right x n)
Bitwise shift right.
Example:
(bit-shift-right 16 2) ; => 4
bit-test#
(bit-test x n)
Returns true if the bit at index n (0-based, least significant first) of the integer x is set, false otherwise.
Example:
(bit-test 5 0) ; => true
bit-xor#
(bit-xor x y & args)
Bitwise xor.
Example:
(bit-xor 12 10) ; => 6
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.
Example:
(boolean? true) ; => true
(boolean? nil) ; => false
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
bounded-count#
(bounded-count n coll)
Returns the number of items in coll, but counts at most n when coll is not counted?. If coll is counted? (its size is known in O(1)) the full count is returned, which may exceed n; otherwise the sequence is walked at most n steps.
Example:
(bounded-count 3 [1 2 3 4 5]) ; => 5
(bounded-count 3 (map inc (range 100))) ; => 3
break#
(break)
Pauses execution and opens an interactive debugger sub-REPL with access to the lexical locals in scope. Type (continue) to resume execution.
Example:
(let [x 41] (break)) ; opens the debugger with x in scopebutlast#
(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.
Example:
(transduce cat conj [] [[1 2] [3 4]]) ; => [1 2 3 4]
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 (new Exception "error")) (catch Exception e (.getMessage e)))
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 (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 (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.
Example:
(coerce-in 5 0 10) ; => 5
(coerce-in 15 0 10) ; => 10
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)
(comp outer)
(comp outer inner)
(comp outer inner & fs)
Takes a list of functions and returns a function that is the composition of those functions.
Example:
((comp inc (fn [x] (* x 2))) 3) ; => 7
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. Numbers are
compared across the numeric tower (int, float, Ratio, BigInt,
BigDecimal). Throws InvalidArgumentException when x and y come from
mutually incomparable categories (e.g. (compare 1 [])).
Example:
(compare 1 2) ; => -1
(compare :a :a) ; => 0
compare-and-set!#
(compare-and-set! variable old-value new-value)
Atomically sets the value of the atom variable to new-value if and only if its current value is identical (via identical?) to old-value. Returns true when the swap happened, false otherwise.
Example:
(def a (atom 1))
(compare-and-set! a 1 2) ; => true
(compare-and-set! a 1 3) ; => false
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.
Example:
((complement even?) 3) ; => true
completing#
(completing f)
(completing f cf)
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).
Example:
(transduce (filter even?) (completing conj) [] [1 2 3 4]) ; => [2 4]
concat#
(concat)
(concat coll)
(concat coll1 coll2)
(concat coll1 coll2 coll3)
(concat coll1 coll2 coll3 & 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.
Example:
((constantly 42) 1 2 3) ; => 42
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.
Throws for a lazily consumed source that has no size of its own, a transducer pipeline built by eduction, a PHP generator, an iterator. Counting one means draining it, which re-runs the whole pipeline (including its side effects) and still leaves nothing counted behind, so count refuses instead of doing it silently. Realize it first: (count (into [] coll)).
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)
dbg#
(dbg)
(dbg expr)
Prints [file:line] form => value to the standard error stream and returns the value unchanged, so it can wrap any subexpression without restructuring code. With no argument prints just [file:line] as a reached-here marker and returns nil.
Example:
(defn area [w h] (* (dbg w) h))
(area 3 4) ; stderr: [src/main.phel:12] w => 3
dbg-write#
(dbg-write message)
Writes message to the standard error stream. Output primitive behind the dbg macro; redefine it with with-redefs to capture debug output in tests.
Example:
(dbg-write "debug line\n")
dec#
(dec x)
Decrements x by one.
Example:
(dec 5) ; => 4
dec'#
(dec' x)
Auto-promoting variant of dec. Integer results are returned as
BigInt; floats and rationals pass through unchanged.
Example:
(dec' 1) ; => 0
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)
(dedupe coll)
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)
(deep-merge m)
(deep-merge m1 m2)
(deep-merge m1 m2 & args)
Recursively merges data structures.
Example:
(deep-merge {:a {:x 1}} {:a {:y 2}}) ; => {:a {:x 1, :y 2}}
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.
defenum#
(defenum name & cases)
Defines a native PHP enum. Each case is named by a keyword followed by an
optional scalar value (all int or all string); value-less cases produce a
pure enum. After the cases, an optional implementations tail (interface
symbols with their methods, and a :php block of plain/magic methods) is
parsed like defstruct, so an enum can implement interfaces and carry
methods. Also defines a Name? predicate.
(defenum Status :active "active" :inactive "inactive")
(Status? Status/active) # => true
(defenum Suit
:hearts :spades :clubs :diamonds
Describable
(describe [this] (.-name this))
:php
(label [this] (.-name this)))
defexception#
(defexception name & [parent])
Define a new exception. Optionally pass a parent class to extend (defaults to
Exception), so frameworks can catch it by type, e.g.
(defexception ProductNotFound RuntimeException). The parent takes any class
spelling: bare, dotted (My.Ns.Error), or an alias brought in with :use.
defexception*#
(defexception my-ex)
(defexception my-ex \RuntimeException)
Define a new exception, optionally extending a custom parent class (defaults to \Exception).
Example:
(defexception my-error \RuntimeException)
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.
defonce#
(defonce name meta? value)
Like def, but only binds the value when name is not already defined in the registry. Useful in REPL workflows where re-evaluating a file should not reset stateful holders (atoms, connections, caches).
Example:
(defonce app-state (atom {}))
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 (fromdefstruct)Name?, type predicate (fromdefstruct)->Name, positional factory, identical toNamemap->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 (fromdefstruct)Name?, type predicate (fromdefstruct)->Name, positional factory, identical toName
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.
Example:
(delay? (delay 1)) ; => true
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) ; => <function:map>
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.
Example:
(difference (hash-set 1 2 3) (hash-set 2)) ; => #{1 3}
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)
(dissoc ds k)
(dissoc ds k & 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)
(distinct coll)
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)
distinct?#
(distinct? x & more)
Returns true if no two of the arguments are =. Requires at least one argument.
Example:
(distinct? 1 2 3) ; => true
(distinct? 1 2 1) ; => false
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.
Example:
(deref (doto (atom 0) (reset! 5))) ; => 5
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.
Example:
(double? 1.0) ; => true
drop#
(drop n)
(drop n coll)
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)
(drop-while pred coll)
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.
A non-countable iterable (an eduction pipeline, a PHP generator) is answered by pulling a single element, never by counting it.
Example:
(empty? []) ; => true
(empty? [1]) ; => false
eval#
(eval form)
Evaluates a form and return the evaluated results.
Example:
(eval '(+ 1 2)) ; => 3
even?#
(even? x)
Checks if x is even.
Example:
(even? 4) ; => true
every-pred#
(every-pred)
(every-pred p & ps)
Takes a variadic set of predicates and returns a function f that, when called with any number of arguments, returns true if every composing predicate returns a logical true value against every argument, and false otherwise. The returned function short-circuits on the first logical false 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. With no arguments the returned function returns true.
Example:
((every-pred even? pos?) 2 4 6) ; => true
((every-pred even? pos?) 2 -4) ; => false
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.
Example:
(ex-cause (ex-info "boom" {})) ; => nil
ex-data#
(ex-data ex)
Returns the data map from an ex-info exception, or nil if not an ExceptionInfo.
Example:
(ex-data (ex-info "boom" {:a 1})) ; => {:a 1}
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.
Example:
(ex-message (ex-info "boom" {})) ; => "boom"
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:
nilfor the nil type- a type keyword matching what
typereturns::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.
Example:
(extreme > [1 5 2]) ; => 5
false?#
(false? x)
Checks if value is exactly false (not just falsy).
Example:
(false? nil) ; => false
ffirst#
(ffirst coll)
Same as (first (first coll)).
Example:
(ffirst [[1 2] [3 4]]) ; => 1
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)
(filter pred coll)
(filter pred coll & more)
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)
filterv#
(filterv pred coll)
Returns a vector of the items in coll for which (pred item) returns a logical true value. Like filter, but eager and returns a vector rather than a lazy sequence.
Example:
(filterv 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 (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.
A lazily consumed source with no indexed access of its own (an eduction pipeline, a PHP generator, an iterator) is answered by pulling a single element, the same way empty? answers it. count is the one that refuses such a source, because counting means draining it.
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. Non-numeric objects such as
keywords, vectors, or maps raise InvalidArgumentException instead of
leaking a raw PHP float-coercion warning.
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.
Example:
(float? 1.0) ; => true
(float? 1) ; => false
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.
Example:
(fn? inc) ; => true
(fn? 42) ; => false
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:
:rangeloop over a range by using the range function.:inloops over all values of a collection (including strings).:keysloops over all keys/indexes of a collection.:pairsloops 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:
:whilebreaks the loop if the expression is falsy.:letdefines additional bindings.:whenonly 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 intoaccumulator. Initiallyaccumulatoris bound toinitial-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.
Example:
(format "%d-%s" 1 "a") ; => "1-a"
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.
Example:
(full-name :foo/bar) ; => "foo/bar"
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
gcd#
(gcd a b)
Returns the greatest common divisor of a and b, computed with the
Euclidean algorithm. The result is always non-negative; (gcd 0 0) is 0.
Example:
(gcd 12 18) ; => 6
(gcd -12 18) ; => 6
gensym#
(gensym)
Generates a new unique symbol.
Example:
(gensym) ; => __phel_1
get#
(get ds k)
(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)
(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.
Example:
(get-validator (atom 1)) ; => 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-set#
(hash-set)
(hash-set a)
(hash-set a b)
(hash-set a b c)
(hash-set a b c & more)
Creates a new Set from the given arguments. Shortcut: #{}
Example:
(hash-set 1 2 3) ; => #{1 2 3}
hydrate#
(hydrate class-name m)
Creates an instance of PHP class class-name (a class-string) without invoking its constructor, then sets each declared property named by the keyword keys of map m. Mirrors how ORMs/serializers rebuild entities from raw data; pairs with bean for the reverse direction.
Example:
(hydrate "My\\Dto" {:id 1 :name "x"})
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)
(identical? a b)
(identical? a b & more)
Checks if all values are identical. Same as a === b in PHP.
Example:
(identical? :a :a) ; => true
identity#
(identity x)
Returns its argument.
Example:
(identity 42) ; => 42
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
Example:
(if-let [x (get {:a 1} :a)] x :none) ; => 1
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.
Example:
(if-some [x false] :yes :no) ; => :yes
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
in-ns#
(in-ns namespace)
Switches to an existing namespace without creating it. Two uses: at the REPL, to navigate into a namespace and inspect or test private functions; and as the first form of a file pulled in with (load ...), which must join its caller's namespace this way. Do not use it to switch namespace part-way through a file - the build system assumes one namespace per file.
Example:
(in-ns my-app.core)
inc#
(inc x)
Increments x by one.
Example:
(inc 1) ; => 2
inc'#
(inc' x)
Auto-promoting variant of inc. Integer results are returned as
BigInt; floats and rationals pass through unchanged.
Example:
(inc' 1) ; => 2
index#
(index xrel ks)
Returns a map that groups the maps in the relation xrel by their values for the keys in ks. Each key is (select-keys map ks) and each value is the set of maps sharing those key-values.
Example:
(index (hash-set {:name "a" :dept 1} {:name "b" :dept 1}) [:dept]) ; => {{:dept 1} #{{:name "a", :dept 1} {:name "b", :dept 1}}}
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
infinite?#
(infinite? x)
Checks if x is positive or negative infinity. Alias for inf?, matching Clojure's infinite? naming.
Example:
(infinite? php/INF) ; => true
(infinite? 1.0) ; => false
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 (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. Non-numeric objects such as keywords,
vectors, or maps raise InvalidArgumentException instead of leaking a
raw PHP int-coercion warning.
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 with0; given a sequence, coerces each element to int viaintval.(int-array size init-val-or-seq), wheninit-val-or-seqis 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 tosizeif 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.
Example:
(int? 1) ; => true
(int? 1.0) ; => false
integer?#
(integer? x)
Returns true if x is a mathematical integer: a fixed-precision PHP
int or a BigInt.
Example:
(integer? 1) ; => true
(integer? 1.0) ; => false
interleave#
(interleave coll1 coll2)
(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)
(interpose sep coll)
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.
Example:
(intersection (hash-set 1 2 3) (hash-set 2 3 4)) ; => #{2 3}
into#
(into to)
(into to from)
(into to xf from)
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]) ; => <PHP-Array [1, 2, 3]>
(into-array :Object [:a :b]) ; => <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})
iterator-seq#
(iterator-seq traversable)
Returns a lazy sequence over a PHP Traversable (Iterator, Generator, IteratorAggregate, ...), pulling one element at a time. Unlike the eager coercion that materialises a Traversable via iterator_to_array, this streams a large or infinite source (DB cursor, stream reader, paginated API), so take/map/filter only pull what they consume.
Example:
(take 3 (iterator-seq (new ArrayIterator (php-indexed-array 1 2 3 4 5)))) ; => (1 2 3)
juxt#
(juxt f)
(juxt f g)
(juxt f g h)
(juxt f g h & 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)
(keep pred coll)
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)
(keep-indexed pred coll)
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. A string is split on
the first / into namespace and name parts, like symbol.
Arity-2 builds a namespaced keyword from the namespace and name parts (taken
verbatim, without splitting); returns nil when name is nil. Non-string
parts are converted with PHP's strval rather than str, which is both
faster on this hot path and renders true as "1" and false as "".
Example:
(keyword "name") ; => :name
(keyword :abc) ; => :abc
(keyword "ns/name") ; => :ns/name
(keyword "ns" "name") ; => :ns/name
keyword?#
(keyword? x)
Returns true if x is a keyword, false otherwise.
Example:
(keyword? :a) ; => true
(keyword? 'a) ; => false
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
lcm#
(lcm a b)
Returns the least common multiple of a and b. The result is always
non-negative; when either argument is zero the result is 0.
Example:
(lcm 4 6) ; => 12
(lcm -4 6) ; => 12
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.
Example:
(list? '(1 2)) ; => true
(list? [1 2]) ; => false
load#
(load path)
Loads a Phel source file into the caller namespace at runtime. Path resolution follows the spirit of Clojure's clojure.core/load: a path beginning with a slash is classpath-absolute (searched against the configured load-classpath roots); otherwise it is resolved relative to the caller file's compile-time location, so mutations to the runtime *file* value cannot break resolution. Pass the path without an extension (no .phel) and without a relative prefix (no ./ or ../). Returns nil; the form runs for its side effects.
Example:
(load "core/meta") ; loads and evaluates core/meta into the current namespace
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.
Example:
(macroexpand-1 '(when true 1)) ; => (if true (do 1))
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.
Example:
(make-hierarchy) ; => {:parents {}, :descendants {}, :ancestors {}}
map#
(map f)
(map f coll)
(map f coll & more)
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.
When applied to a map, iterates over entries as [key value] pairs,
matching Clojure semantics.
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-invert#
(map-invert m)
Returns a map with the keys and values of m swapped. When several keys share a value, the one visited last in iteration order wins.
Example:
(map-invert {:a 1 :b 2}) ; => {1 :a, 2 :b}
map?#
(map? x)
Returns true if x is a hash map, false otherwise.
Example:
(map? {:a 1}) ; => true
(map? [1 2]) ; => false
mapcat#
(mapcat f)
(mapcat f coll)
(mapcat f coll & colls)
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)
mapv#
(mapv f coll & colls)
Returns a vector consisting of the result of applying f to the set of first items of each coll, followed by applying f to the set of second items in each coll, until any one of the colls is exhausted. Like map, but eager and returns a vector rather than a lazy sequence.
Example:
(mapv inc [1 2 3]) ; => [2 3 4]
max#
(max x)
(max x y)
(max x y z)
(max x y z w)
(max x y z w & more)
Returns the maximum of all arguments. Returns ##NaN whenever any numeric argument is ##NaN.
Example:
(max 3 1 2) ; => 3
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.
Example:
(mean [1 2 3]) ; => 2.0
median#
(median xs)
Returns the median of xs. With an even-sized collection the result is the float average of the two middle elements.
Example:
(median [3 1 2]) ; => 2
(median [1 2 3 4]) ; => 2.5
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)
(merge-with f m)
(merge-with f m1 m2)
(merge-with f m1 m2 & 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.
Example:
(merge-with + {:a 1 :b 2} {:a 10}) ; => {:a 11, :b 2}
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 x)
(min x y)
(min x y z)
(min x y z w)
(min x y z w & more)
Returns the minimum of all arguments. Returns ##NaN whenever any numeric argument is ##NaN.
Example:
(min 3 1 2) ; => 1
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.
Example:
(name :foo) ; => "foo"
(name 'bar) ; => "bar"
namespace#
(namespace x)
Return the namespace string of a symbol or keyword. Nil if not present.
Example:
(namespace :foo/bar) ; => "foo"
(namespace :foo) ; => nil
nan?#
(nan? x)
Checks if x is not a number.
Example:
(nan? ##NaN) ; => true
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.
Example:
(neg? -2) ; => true
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)).
Example:
(nfirst [[1 2 3] [4 5]]) ; => [2 3]
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)).
Example:
(nnext [1 2 3 4]) ; => [3 4]
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.
Example:
(not-any? even? [1 3 5]) ; => true
not-empty#
(not-empty coll)
Returns coll if it contains elements, otherwise nil.
Example:
(not-empty [1 2]) ; => [1 2]
(not-empty []) ; => 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.
Example:
(not-every? even? [2 3 4]) ; => true
not=#
(not= a)
(not= a b)
(not= a b & more)
Checks if all values are unequal. Same as a != b in PHP.
Example:
(not= 1 2) ; => true
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.
Example:
(number? 1) ; => true
(number? "a") ; => false
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 aget/aset) since PHP has no typed
array distinction.
Example:
(object-array 3) ; => <PHP-Array [nil, nil, nil]>
(object-array [1 2 3]) ; => <PHP-Array [1, 2, 3]>
odd?#
(odd? x)
Checks if x is odd.
Example:
(odd? 3) ; => true
one?#
(one? x)
Checks if x is one.
Example:
(one? 1) ; => true
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") ; => Infinity
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 the normal number of arguments to f, and returns a function that takes a variable number of additional arguments. When called, f will be invoked with the bound args prepended to the additional arguments.
Example:
((partial + 10) 1 2) ; => 13
partition#
(partition n coll)
(partition n step coll)
(partition n step pad coll)
Partitions coll into chunks of n elements.
With one collection argument, returns consecutive non-overlapping chunks and drops any incomplete final chunk. step (default n) is how far to advance between chunks, so a step smaller than n yields overlapping chunks. With a pad collection, a final incomplete chunk is filled from pad up to n elements (kept even when pad runs short); without pad the incomplete final chunk is dropped. Each chunk is a vector.
Example:
(partition 3 [1 2 3 4 5 6 7]) ; => ([1 2 3] [4 5 6])
(partition 2 1 [1 2 3]) ; => ([1 2] [2 3])
(partition 3 3 [:x] [1 2 3 4]) ; => ([1 2 3] [4 :x])
partition-all#
(partition-all n coll)
(partition-all n step coll)
Partitions collection into chunks of size n, including any incomplete trailing chunks. step (default n) is how far to advance between chunks, so a step smaller than n yields overlapping chunks. Each chunk is a vector.
Example:
(partition-all 3 [1 2 3 4 5 6 7]) ; => ([1 2 3] [4 5 6] [7])
(partition-all 3 2 [0 1 2 3 4]) ; => ([0 1 2] [2 3 4] [4])
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":<PHP-Array [1, 2, 3]>, "b":<PHP-Array ["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.
Example:
(php-array? (php-indexed-array 1 2)) ; => true
(php-array? [1 2]) ; => false
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-invoke#
(php-invoke target method & args)
Calls the method method on target, where the method name is a value
rather than a literal. target is either an object or a class-name string
for a static method. Matches ClojureScript's js-invoke; use the dot
syntax ((.format d "Y")) whenever the name is known at compile time.
Example:
(php-invoke (new DateTimeImmutable "2024-03-10") "format" "Y") ; => "2024"
(let [m "format"] (php-invoke (new DateTimeImmutable "2024-03-10") m "Y")) ; => "2024"
php-object?#
(php-object? x)
Returns true if x is a PHP object, false otherwise.
Example:
(php-object? (new stdClass)) ; => true
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.
Example:
(pop [1 2 3]) ; => [1 2]
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.
Example:
(pos? 3) ; => true
pr#
(pr & xs)
Same as print, but prints each value readably (strings quoted). Returns nil.
Example:
(pr "a" 1) ; prints "a" 1
pr-str#
(pr-str & xs)
Same as print-str, but prints each value readably: strings are quoted and escaped so the output can be read back. Phel has no dedicated char type, so character literals such as \A are single-character strings and print as "A" (ClojureScript-aligned; Clojure/JVM would print \A).
Example:
(pr-str "a" 1) ; => "\"a\" 1"
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#
(print-str & xs)
Same as print. But instead of writing it to an output stream, the resulting string is returned.
Example:
(print-str "a" 1) ; => "a 1"
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.
println-str#
(println-str & xs)
Same as println, but instead of writing to an output stream the resulting string is returned, with a trailing newline.
Example:
(println-str "a" "b") ; => "a b\n"
prn#
(prn & xs)
Same as pr followed by a newline. Returns nil.
Example:
(prn "a" 1) ; prints "a" 1 and a newline
prn-str#
(prn-str & xs)
Same as prn, but instead of writing to an output stream the resulting string is returned, with a trailing newline.
Example:
(prn-str "a" 1) ; => "\"a\" 1\n"
project#
(project xrel ks)
Returns a set of maps, keeping only the keys in ks from each map in the relation xrel.
Example:
(project (hash-set {:a 1 :b 2}) [:a]) ; => #{{:a 1}}
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.
Example:
(protocol-type-key "hi") ; => :string
(protocol-type-key 42) ; => :int
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) ; => <-(1 2 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.
Example:
(rand-int 100) ; => 42
rand-nth#
(rand-nth xs)
Returns a random item from xs.
Example:
(rand-nth [:a :b :c]) ; => :b
random-sample#
(random-sample prob)
(random-sample prob coll)
Returns the items of coll for which (rand) is less than prob, so each item is kept independently with probability prob (0 keeps nothing, 1 keeps everything). Lazy. Without a collection, returns a transducer.
Example:
(random-sample 0.5 (range 10)) ; => (1 4 5 9)
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)
(range end)
(range start end)
(range start end step)
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
rational?#
(rational? x)
Returns true if x is a rational number: an integer (int or BigInt), a Ratio, or a BigDecimal. Floating-point numbers (including ##Inf, ##-Inf, and ##NaN) are not rational.
Example:
(rational? 1/2) ; => true
(rational? 1.0) ; => 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.
Example:
(read-string "(+ 1 2)") ; => (+ 1 2)
realized?#
(realized? coll)
Returns true if a lazy sequence, delay, promise, or future has been realized, false otherwise.
Example:
(realized? (lazy-seq (cons 1 nil))) ; => 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 coll)
(reduce f init coll)
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
reduce-kv#
(reduce-kv f init coll)
Reduces an associative collection by applying f to the accumulator, key and value of each entry, starting with init. Vectors use the index as key. Respects early termination via (reduced val).
Example:
(reduce-kv (fn [m k v] (assoc m v k)) {} {:a 1 :b 2}) ; => {1 :a, 2 :b}
reduced#
(reduced x)
Wraps x in a Reduced, signaling early termination from reduce/transduce.
Example:
(reduce (fn [acc x] (if (= x 3) (reduced acc) (+ acc x))) 0 [1 2 3 4]) ; => 3
reduced?#
(reduced? x)
Returns true if x is a Reduced value.
Example:
(reduced? (reduced 1)) ; => true
reductions#
(reductions f coll)
(reductions f init coll)
Returns a lazy sequence of the intermediate values of the reduction (as per reduce) of coll by f, starting with init when supplied.
Example:
(reductions + [1 2 3 4]) ; => (1 3 6 10)
(reductions + 0 [1 2 3 4]) ; => (0 1 3 6 10)
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)
(remove pred coll)
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#
(rename xrel kmap)
Returns a set of maps like the relation xrel, with the keys of each map renamed according to kmap (a map of old-key to new-key).
Example:
(rename (hash-set {:a 1 :b 2}) {:a :x}) ; => #{{:x 1, :b 2}}
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 x)
(repeat n x)
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 f)
(repeatedly n f)
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})
reset-vals!#
(reset-vals! variable new-value)
Sets the value of the atom variable to new-value. Returns a vector [old-value new-value] of the values before and after the reset.
Example:
(def a (atom 1))
(reset-vals! a 2) ; => [1 2]
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)
rsubseq#
(rsubseq sc test bound-key)
(rsubseq sc start-test start-key end-test end-key)
Like subseq, but returns the matching entries in descending order. With one boundary, use < / <= to start from the top end and > / >= to stop; with two boundaries, returns the entries between them in reverse, e.g. (rsubseq sm >= 2 < 5).
Example:
(rsubseq (sorted-map 1 :a 2 :b 3 :c) <= 2) ; => ([2 :b] [1 :a])
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#
(select pred xset)
Returns a set of the elements of xset for which (pred element) is logical true.
Example:
(select even? (hash-set 1 2 3 4)) ; => #{2 4}
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)).
Example:
(seq? '(1 2)) ; => true
(seq? [1 2]) ; => false
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!#
(set! place value)
Sets place to value and returns value, covering all three shapes
Clojure's set! covers.
A property access ((.-prop obj)) assigns the property, as does any other
place php/oset accepts. A qualified symbol naming a member of a PHP
class (Foo/slot) assigns that static property. Any other symbol
names a dynamic var and assigns its current thread-local binding, throwing
when no binding frame is active, so it never writes the root by accident;
alter-var-root is the way to change a root.
A macro rather than a function because the place is a location, not a value.
Example:
(let [o (new ArrayObject)] (set! (.-y o) 2024)) ; => 2024
(def ^:dynamic *x* 0)
(binding [*x* 1] (set! *x* 2) *x*) ; => 2
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.
Example:
(set? (hash-set 1 2)) ; => true
(set? [1 2]) ; => false
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]) ; => [2 3 5 1 4]
simple-ident?#
(simple-ident? x)
Returns true if x is a symbol or keyword without a namespace.
Example:
(simple-ident? 'a) ; => true
(simple-ident? 'foo/bar) ; => false
simple-keyword?#
(simple-keyword? x)
Returns true if x is a keyword without a namespace.
Example:
(simple-keyword? :a) ; => true
(simple-keyword? :foo/bar) ; => false
simple-symbol?#
(simple-symbol? x)
Returns true if x is a symbol without a namespace.
Example:
(simple-symbol? 'a) ; => true
(simple-symbol? 'foo/bar) ; => false
slice#
(slice coll offset)
(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 an entire file, URL or stream 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.
Example:
(some-> {:a 1} :a inc) ; => 2
some->>#
(some->> x & forms)
Threads x through the forms like ->> but stops when a form returns nil.
Example:
(some->> 5 (+ 3) (* 2)) ; => 16
some-fn#
(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 bytes 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)]
splitv-at#
(splitv-at n coll)
Returns a vector [(vec (take n coll)) (vec (drop n coll))]. Like split-at, but eagerly returns vectors rather than lazy sequences.
Example:
(splitv-at 2 [1 2 3 4 5]) ; => [[1 2] [3 4 5]]
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.4142135623731
str#
(str)
(str x)
(str x y)
(str x y z)
(str x y z a)
(str x y z a b)
(str x y z a b & more)
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.
Example:
(str "a" "b" "c") ; => "abc"
(str 1 2 3) ; => "123"
(str 1 nil true) ; => "1true"
(str) ; => ""
string?#
(string? x)
Returns true if x is a string, false otherwise.
Example:
(string? "a") ; => true
(string? :a) ; => false
struct?#
(struct? x)
Returns true if x is a struct, false otherwise.
subseq#
(subseq sc test bound-key)
(subseq sc start-test start-key end-test end-key)
Returns a lazy sequence of the entries of the sorted collection sc (map entries for a sorted map, elements for a sorted set) whose keys satisfy the boundary test, in ascending order. With one boundary, use > / >= to start after or at bound-key and < / <= to stop before or at it. With two boundaries, returns the entries between them, e.g. (subseq sm >= 2 < 5). Boundaries respect the collection's own comparator (sorted-map-by / sorted-set-by).
Example:
(subseq (sorted-map 1 :a 2 :b 3 :c) >= 2) ; => ([2 :b] [3 :c])
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
subvec#
(subvec v start)
(subvec v start end)
Returns a persistent vector of the items in v from start (inclusive) to end (exclusive). end defaults to (count v). Non-integer indices truncate toward zero and NaN counts as 0, matching Clojure. The result shares structure with v. Throws an OutOfBoundsException when start or end is out of range or start is greater than end.
Example:
(subvec [1 2 3 4 5] 1 3) ; => [2 3]
(subvec [1 2 3 4 5] 2) ; => [3 4 5]
sum#
(sum xs)
Returns the sum of all elements is xs.
Example:
(sum [1 2 3]) ; => 6
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)
(swap! variable f a)
(swap! variable f a b)
(swap! variable f a b & 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))
swap-vals!#
(swap-vals! variable f)
(swap-vals! variable f a)
(swap-vals! variable f a b)
(swap-vals! variable f a b & args)
Atomically swaps the value of the atom variable to (apply f current-value args). Returns a vector [old-value new-value] of the values before and after the swap.
Example:
(def a (atom 1))
(swap-vals! a inc) ; => [1 2]
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.
Example:
(symbol? 'a) ; => true
(symbol? :a) ; => false
symmetric-difference#
(symmetric-difference set & sets)
Symmetric difference between multiple sets into a new one.
Example:
(symmetric-difference (hash-set 1 2) (hash-set 2 3)) ; => #{1 3}
take#
(take n)
(take n coll)
Takes the first n elements of coll. When called with n only, returns a transducer.
Example:
(take 2 [1 2 3 4]) ; => (1 2)
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)
(take-nth n coll)
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)
(take-while pred coll)
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 (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]) ; => <PHP-Array [1, 2, 3]>
(to-array nil) ; => <PHP-Array []>
to-php-array#
Creates a PHP Array from a sequential data structure.
trampoline#
(trampoline f & args)
Calls f with any supplied args. While the return value is a function, calls it with no arguments and repeats; returns the first non-function value. Use it for stack-safe mutual recursion: have the functions return a zero-argument function wrapping the next call instead of calling it directly. Only Phel functions bounce, keywords and collections, although callable, are returned as-is. To return a function as the final value, wrap it in a collection and unwrap it after trampoline returns.
Example:
(defn my-even? [n] (if (zero? n) true (fn [] (my-odd? (dec n)))))
(defn my-odd? [n] (if (zero? n) false (fn [] (my-even? (dec n)))))
(trampoline my-even? 10000) ; => true
transduce#
(transduce xform f coll)
(transduce xform f init coll)
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.
Example:
(tree-seq indexed? identity [1 [2 3]]) ; => [[1 [2 3]] 1 [2 3] 2 3]
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.
Example:
(truthy? 0) ; => true
(truthy? nil) ; => false
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
Example:
(type [1 2]) ; => :vector
(type :a) ; => :keyword
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)
(union s)
(union s1 s2)
(union s1 s2 & sets)
Union multiple sets into a new one.
Example:
(union (hash-set 1 2) (hash-set 2 3)) ; => #{1 2 3}
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)) ; => (phel.core/+ 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]) ; => (phel.core/+ 1 2 3)
unreduced#
(unreduced x)
If x is Reduced, returns the unwrapped value; otherwise returns x.
Example:
(unreduced (reduced 1)) ; => 1
(unreduced 1) ; => 1
unsigned-bit-shift-right#
(unsigned-bit-shift-right x n)
Bitwise shift right without sign extension: the vacated high bits are filled with zeros rather than copies of the sign bit. Unlike bit-shift-right, (unsigned-bit-shift-right -1 10) is a large positive number, not -1.
Example:
(unsigned-bit-shift-right -1 10) ; => 18014398509481983
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}
use#
(use ClassName [:as Alias])
Registers PHP class aliases in the current namespace without the full (ns ... (:use ...)) form. Intended for files that join an existing namespace via (in-ns ...) and only want to declare the imports they actually use. Pure compile-time registration; emits no runtime code.
Example:
(use DateTimeImmutable :as Date)
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
var#
(var sym)
Resolves sym against the current namespace, require aliases, and refers, yielding the first-class Var handle for that global definition. The reader shorthand #'sym expands to (var sym). Throws if sym does not resolve to a known global.
Example:
(var map) ; resolves to the Var for phel.core/map
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) ; => <function:map>
(var-get (intern "user" "x" 42)) ; => 42
(var-get 'user/missing ::none) ; => :user/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.
Example:
(var? #'map) ; => true
variadic?#
(variadic? f)
Returns true if the function f accepts a variable number of arguments. A multi-arity function compiles to a single variadic dispatch, so it always reports true.
Example:
(variadic? +) ; => true
(variadic? inc) ; => false
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.
Example:
(vector? [1 2]) ; => true
(vector? '(1 2)) ; => false
volatile!#
(volatile! val)
Creates a volatile mutable reference with initial value val. Use for transducer state that needs fast mutation without watches.
Example:
(let [v (volatile! 0)] (vreset! v 5) @v) ; => 5
volatile?#
(volatile? x)
Returns true if x is a Volatile.
Example:
(volatile? (volatile! 0)) ; => true
vreset!#
(vreset! vol val)
Sets the value of volatile vol to val. Returns val.
Example:
(let [v (volatile! 0)] (vreset! v 9)) ; => 9
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.
Example:
(let [v (volatile! 10)] (vswap! v + 5)) ; => 15
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.
Example:
(when-first [x [1 2 3]] x) ; => 1
when-let#
(when-let bindings & body)
When test is true, evaluates body with binding-form bound to the value of test
Example:
(when-let [x (get {:a 1} :a)] (* x 10)) ; => 10
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.
Example:
(when-some [x 0] (inc x)) ; => 1
while#
(while test & body)
Repeatedly evaluates body (for side effects) as long as test is logical true. Returns nil.
Example:
(while (pos? @counter) (swap! counter dec))
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-open#
(with-open bindings & body)
Evaluates body with the names bound as in let, then closes every bound
resource in a finally clause, in reverse binding order, even when the
body throws. Objects exposing a close method are closed by calling it,
stream resources with php/fclose; nil bindings are skipped.
Example:
(with-open [f (php/fopen "data.txt" "r")] (php/fgets f))
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.
Example:
(zero? 0) ; => true
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}