Janet 1.38.0-73334f3 Documentation
(Other Versions: 1.37.1 1.36.0 1.35.0 1.34.0 1.31.0 1.29.1 1.28.0 1.27.0 1.26.0 1.25.1 1.24.0 1.23.0 1.22.0 1.21.0 1.20.0 1.19.0 1.18.1 1.17.1 1.16.1 1.15.0 1.13.1 1.12.2 1.11.1 1.10.1 1.9.1 1.8.1 1.7.0 1.6.0 1.5.1 1.5.0 1.4.0 1.3.1 )

Top Level Bindings

All of the core functions, macros, and bindings that are not part of any module.

Index

% %= * *= *args* *current-file* *debug* *defdyn-prefix* *doc-color* *doc-width* *err* *err-color* *executable* *exit* *exit-value* *ffi-context* *lint-error* *lint-levels* *lint-warn* *macro-form* *macro-lints* *module-cache* *module-loaders* *module-loading* *module-make-env* *module-paths* *out* *peg-grammar* *pretty-format* *profilepath* *redef* *repl-prompt* *syspath* *task-id* + ++ += - -- -= -> ->> -?> -?>> / /= < <= = > >= abstract? accumulate accumulate2 all all-bindings all-dynamics and any? apply array array? as-> as-macro as?-> asm assert assertf bad-compile bad-parse band blshift bnot boolean? bor brshift brushift buffer buffer? bxor bytes? cancel case catseq cfunction? chr cli-main cmp comment comp compare compare< compare<= compare= compare> compare>= compif compile complement comptime compwhen cond coro count curenv debug debugger debugger-env debugger-on-status dec deep-not= deep= def- default default-peg-grammar defdyn defer defglobal defmacro defmacro- defn defn- delay describe dictionary? disasm distinct div doc doc* doc-format doc-of dofile drop drop-until drop-while dyn each eachk eachp edefer eflush empty? env-lookup eprin eprinf eprint eprintf error errorf eval eval-string even? every? extreme false? fiber-fn fiber? filter find find-index first flatten flatten-into flush flycheck for forever forv freeze frequencies from-pairs function? gccollect gcinterval gcsetinterval generate gensym geomean get get-in getline getproto group-by has-key? has-value? hash idempotent? identity if-let if-not if-with import import* in inc index-of indexed? int? interleave interpose invert juxt juxt* keep keep-syntax keep-syntax! keys keyword keyword? kvs label last length lengthable? let load-image load-image-dict loop macex macex1 maclintf make-env make-image make-image-dict map mapcat marshal match max max-of mean memcmp merge merge-into merge-module min min-of mod nan? nat? native neg? next nil? not not= number? odd? one? or pairs parse parse-all partial partition partition-by pos? postwalk pp prewalk prin prinf print printf product prompt propagate protect put put-in quit range reduce reduce2 repeat repl require resume return reverse reverse! root-env run-context sandbox scan-number seq setdyn short-fn signal slice slurp some sort sort-by sorted sorted-by spit stderr stdin stdout string string? struct struct? sum symbol symbol? table table? tabseq take take-until take-while thaw toggle trace tracev true? truthy? try tuple tuple? type unless unmarshal untrace update update-in use values var- varfn varglobal walk warn-compile when when-let when-with with with-dyns with-env with-syms with-vars xprin xprinf xprint xprintf yield zero? zipcoll


% function

(% & xs)

Returns the remainder of dividing the first value of xs by each remaining value.

EXAMPLES
(% 10 3) # -> 1
(% -10 3) # -> -1
(% 10 -3) # -> 1
(% -10 -3) # -> -1
(% 1.4 1) # -> 0.4
(% -1.4 1) # -> -0.4
(% 1.4 -1) # -> 0.4
(% -1.4 -1) # -> -0.4
(nan? (% 1.4 0)) # -> true
(nan? (% -1.4 0)) # -> true

Community Examples

%= macro source

(%= x & ns)

Shorthand for (set x (% x n)).

EXAMPLES
(var x 10) # -> 10
(%= x 3) # -> 1
x # -> 1
Community Examples

* function

(* & xs)

Returns the product of all elements in xs. If xs is empty, returns 1.

EXAMPLES
(*) # -> 1
(* 10) # -> 10
(* 10 20) # -> 200
(* 1 2 3 4 5 6 7) # -> 5040

# Can take product of array with splice, but 'product' is better
(* ;(range 1 20)) # -> 1.21645100408832e+17
(product (range 1 20)) # -> 1.21645100408832e+17
Community Examples

*= macro source

(*= x & ns)

Shorthand for (set x (* x n)).

EXAMPLES
(var x 100) # -> 100
x # -> 100
(*= x 10) # -> 1000
x # -> 1000
Community Examples

*args* keyword source

Dynamic bindings that will contain command line arguments at program start.

Community Examples

*current-file* keyword source

Bound to the name of the currently compiling file.

Community Examples

*debug* keyword source

Enables a built in debugger on errors and other useful features for debugging in a repl.

Community Examples

*defdyn-prefix* keyword source

Optional namespace prefix to add to keywords declared with defdyn. Use this to prevent keyword collisions between dynamic bindings.

Community Examples

*doc-color* keyword source

Whether or not to colorize documentation printed with doc-format.

Community Examples

*doc-width* keyword source

Width in columns to print documentation printed with doc-format.

Community Examples

*err* keyword source

Where error printing prints output to.

Community Examples

*err-color* keyword source

Whether or not to turn on error coloring in stacktraces and other error messages.

Community Examples

*executable* keyword source

Name of the interpreter executable used to execute this program. Corresponds to argv[0] in the call to int main(int argc, char **argv);.

Community Examples

*exit* keyword source

When set, will cause the current context to complete. Can be set to exit from repl (or file), for example.

Community Examples

*exit-value* keyword source

Set the return value from run-context upon an exit.

Community Examples

*ffi-context* keyword source

Current native library for ffi/bind and other settings

Community Examples

*lint-error* keyword source

The current lint error level. The error level is the lint level at which compilation will exit with an error and not continue.

Community Examples

*lint-levels* keyword source

A table of keyword alias to numbers denoting a lint level. Can be used to provided custom aliases for numeric lint levels.

Community Examples

*lint-warn* keyword source

The current lint warning level. The warning level is the lint level at which and error will be printed but compilation will continue as normal.

Community Examples

*macro-form* keyword source

Inside a macro, is bound to the source form that invoked the macro

Community Examples

*macro-lints* keyword source

Bound to an array of lint messages that will be reported by the compiler inside a macro. To indicate an error or warning, a macro author should use maclintf.

Community Examples

*module-cache* keyword source

Dynamic binding for overriding module/cache

Community Examples

*module-loaders* keyword source

Dynamic binding for overriding module/loaders

Community Examples

*module-loading* keyword source

Dynamic binding for overriding module/loading

Community Examples

*module-make-env* keyword source

Dynamic binding for creating new environments for import, require, and dofile. Overrides make-env.

Community Examples

*module-paths* keyword source

Dynamic binding for overriding module/paths

Community Examples

*out* keyword source

Where normal print functions print output to.

Community Examples

*peg-grammar* keyword source

The implicit base grammar used when compiling PEGs. Any undefined keywords found when compiling a peg will use lookup in this table (if defined).

Community Examples

*pretty-format* keyword source

Format specifier for the pp function

Community Examples

*profilepath* keyword source

Path to profile file loaded when starting up the repl.

Community Examples

*redef* keyword source

When set, allow dynamically rebinding top level defs. Will slow generated code and is intended to be used for development.

Community Examples

*repl-prompt* keyword source

Allow setting a custom prompt at the default REPL. Not all REPLs will respect this binding.

EXAMPLES
(var ncmd 0)

(defn my-prompt
  `Takes a single argument p, the parser, and returns a prompt string.`
  [p]
  (++ ncmd)
  (string/format "[%d]> " ncmd))

(setdyn :repl-prompt my-prompt)
Community Examples

*syspath* keyword source

Path of directory to load system modules from.

Community Examples

*task-id* keyword source

When spawning a thread or fiber, the task-id can be assigned for concurrency control.

Community Examples

+ function

(+ & xs)

Returns the sum of all xs. xs must be integers or real numbers only. If xs is empty, return 0.

EXAMPLES
(+) # -> 0
(+ 10) # -> 10
(+ 1 2) # -> 3
(+ 1.4 -4.5) # -> -3.1
(+ 1 2 3 4 5 6 7 8 9 10) # -> 55

# Splice can be used to sum arrays, but 'sum' is better
(+ ;(range 101)) # -> 5050
(sum (range 101)) # -> 5050

# Janet can add types that support the :+ or :r+ method
(+ (int/s64 "10") 10) # -> <core/s64 20>

# Bad types give errors
(+ nil 10) # -> error: could not find method :+ for nil, or :r+ for 10
Community Examples

++ macro source

(++ x)

Increments the var x by 1.

EXAMPLES
(var a 0) # -> 0
(set a (+ a 1)) # -> 1
(++ a) # -> 2 (same effect as above)
Community Examples

+= macro source

(+= x & ns)

Increments the var x by n.

EXAMPLES
(var x 100) # -> 100
x # -> 100
(+= x 10) # -> 110
x # -> 110
Community Examples

- function

(- & xs)

Returns the difference of xs. If xs is empty, returns 0. If xs has one element, returns the negative value of that element. Otherwise, returns the first element in xs minus the sum of the rest of the elements.

EXAMPLES
(-) # -> 0
(- 10) # -> -10
(- 1 2) # -> -1
(- 1.4 -4.5) # -> 5.9

# Equivalent to (- first (+ ;rest))
(- 1 2 3 4 5 6 7 8 9 10) # -> -53

# Janet can subtract types that support the :- or :r- method
(- (int/s64 "10") 10) # -> <core/s64 0>
Community Examples

-- macro source

(-- x)

Decrements the var x by 1.

EXAMPLES
(var a 10) # -> 10
(set a (- a 1)) # -> 9
(-- a) # -> 8 (same effect as above)
Community Examples

-= macro source

(-= x & ns)

Decrements the var x by n.

EXAMPLES
(var x 10) # -> 10
(-= x 20) # -> -10
x # -> -10
Community Examples

-> macro source

(-> x & forms)

Threading macro. Inserts x as the second value in the first form in forms, and inserts the modified first form into the second form in the same manner, and so on. Useful for expressing pipelines of data.

EXAMPLES
(-> {:a [1 2 3] :b [4 5 6]}
    (get :a)
    (sum)
    ((fn [x y] (/ x y)) 2)) # The 6 from the sum is threaded first and binds to x, then 2 binds to y.
# -> 3
Community Examples

->> macro source

(->> x & forms)

Threading macro. Inserts x as the last value in the first form in forms, and inserts the modified first form into the second form in the same manner, and so on. Useful for expressing pipelines of data.

Community Examples

-?> macro source

(-?> x & forms)

Short circuit threading macro. Inserts x as the second value in the first form in forms, and inserts the modified first form into the second form in the same manner, and so on. The pipeline will return nil if an intermediate value is nil. Useful for expressing pipelines of data.

Community Examples

-?>> macro source

(-?>> x & forms)

Short circuit threading macro. Inserts x as the last value in the first form in forms, and inserts the modified first form into the second form in the same manner, and so on. The pipeline will return nil if an intermediate value is nil. Useful for expressing pipelines of data.

Community Examples

/ function

(/ & xs)

Returns the quotient of xs. If xs is empty, returns 1. If xs has one value x, returns the reciprocal of x. Otherwise return the first value of xs repeatedly divided by the remaining values.

EXAMPLES
(/) # -> 1
(/ 10) # -> 0.1
(/ 10 5) # -> 2
(/ 10 5 4) # -> 0.5
(/ 10 5 4 5) # -> 0.1

# More arguments is the same as repeated division.
(/ ;(range 1 20)) # -> 8.22064e-18
Community Examples

/= macro source

(/= x & ns)

Shorthand for (set x (/ x n)).

EXAMPLES
(var x 10) # -> 10
(/= x 5) # -> 2
x # -> 2
(/= x 0.2) # -> 10
x # -> 10
Community Examples

< function

(< & xs)

Check if xs is in ascending order. Returns a boolean.

Community Examples

<= function

(<= & xs)

Check if xs is in non-descending order. Returns a boolean.

Community Examples

= function

(= & xs)

Check if all values in xs are equal. Returns a boolean.

Community Examples

> function

(> & xs)

Check if xs is in descending order. Returns a boolean.

Community Examples

>= function

(>= & xs)

Check if xs is in non-ascending order. Returns a boolean.

Community Examples

abstract? cfunction source

(abstract? x)

Check if x is an abstract type.

Community Examples

accumulate function source

(accumulate f init ind)

Similar to reduce, but accumulates intermediate values into an array. The last element in the array is what would be the return value from reduce. The init value is not added to the array (the return value will have the same number of elements as ind). Returns a new array.

EXAMPLES
(reduce + 0 [1 2 3 4]) # -> 10
(accumulate + 0 [1 2 3 4]) # -> @[1 3 6 10]

(reduce + 0 []) # -> 0
(accumulate + 0 []) # -> @[]

(reduce string "" ["J" "a" "n" "e" "t"]) # -> "Janet"
(accumulate string "" ["J" "a" "n" "e" "t"]) # -> @["J" "Ja" "Jan" "Jane" "Janet"]
Community Examples

accumulate2 function source

(accumulate2 f ind)

The 2-argument version of accumulate that does not take an initialization value. The first value in ind will be added to the array as is, so the length of the return value will be (length ind).

Community Examples

all function source

(all pred ind & inds)

Returns true if (pred item) is truthy for every item in ind. Otherwise, returns the first falsey result encountered. Returns true if ind is empty.

EXAMPLES
(all pos? [1 2 3]) # -> true
(all pos? [1 2 -3]) # -> false

(all pos? []) # -> true
(all neg? []) # -> true

(all truthy? [1 2 3]) # -> true
(all truthy? [1 2 nil]) # -> false

# multiple data structures can be handled
(all (fn [x y] (pos? (* x y))) [-1 2] [-2 1]) # -> true

# predicate may not be applied to all values (e.g. 43)
(all |(neg? (+ $0 $1 $2)) [-2 2] [1 -8] [0 1 43]) # -> true

Community Examples

all-bindings function source

(all-bindings &opt env local)

Get all symbols available in an environment. Defaults to the current fiber's environment. If local is truthy, will not show inherited bindings (from prototype tables).

Community Examples

all-dynamics function source

(all-dynamics &opt env local)

Get all dynamic bindings in an environment. Defaults to the current fiber's environment. If local is truthy, will not show inherited bindings (from prototype tables).

Community Examples

and macro source

(and & forms)

Evaluates to the last argument if all preceding elements are truthy, otherwise evaluates to the first falsey argument.

Community Examples

any? function source

(any? ind)

Evaluates to the last element of ind if all preceding elements are falsey, otherwise evaluates to the first truthy element.

Community Examples

apply function

(apply f & args)

Applies a function f to a variable number of arguments. Each element in args is used as an argument to f, except the last element in args, which is expected to be an array or a tuple. Each element in this last argument is then also pushed as an argument to f.

EXAMPLES
(apply + (range 10)) # -> 45
(apply + []) # -> 0
(apply + 1 2 3 4 5 6 7 [8 9 10]) # -> 55
(apply + 1 2 3 4 5 6 7 8 9 10) # -> error: expected array or tuple, got 10

# Can also be used to call macros like functions.
# Will return the macro expanded code of the original macro.
(apply for 'x 0 10 ['(print x)])
# -> (do (var _000000 0) (def _000001 10) (while ...
Community Examples

array cfunction source

(array & items)

Create a new array that contains items. Returns the new array.

Community Examples

array? function source

(array? x)

Check if x is an array.

Community Examples

as-> macro source

(as-> x as & forms)

Thread forms together, replacing as in forms with the value of the previous form. The first form is the value x. Returns the last value.

Community Examples

as-macro macro source

(as-macro f & args)

Use a function or macro literal f as a macro. This lets any function be used as a macro. Inside a quasiquote, the idiom (as-macro ,my-custom-macro arg1 arg2...) can be used to avoid unwanted variable capture of my-custom-macro.

Community Examples

as?-> macro source

(as?-> x as & forms)

Thread forms together, replacing as in forms with the value of the previous form. The first form is the value x. If any intermediate values are falsey, return nil; otherwise, returns the last value.

Community Examples

asm cfunction source

(asm assembly)

Returns a new function that is the compiled result of the assembly. The syntax for the assembly can be found on the Janet website, and should correspond to the return value of disasm. Will throw an error on invalid assembly.

Community Examples

assert macro source

(assert x &opt err)

Throw an error if x is not truthy. Will not evaluate err if x is truthy.

Community Examples

assertf macro source

(assertf x fmt & args)

Convenience macro that combines assert and string/format.

Community Examples

bad-compile function source

(bad-compile msg macrof where &opt line col)

Default handler for a compile error.

Community Examples

bad-parse function source

(bad-parse p where)

Default handler for a parse error.

Community Examples

band function

(band & xs)

Returns the bit-wise and of all values in xs. Each x in xs must be an integer.

Community Examples

blshift function

(blshift x & shifts)

Returns the value of x bit shifted left by the sum of all values in shifts. x and each element in shift must be an integer.

Community Examples

bnot function

(bnot x)

Returns the bit-wise inverse of integer x.

Community Examples

boolean? function source

(boolean? x)

Check if x is a boolean.

Community Examples

bor function

(bor & xs)

Returns the bit-wise or of all values in xs. Each x in xs must be an integer.

Community Examples

brshift function

(brshift x & shifts)

Returns the value of x bit shifted right by the sum of all values in shifts. x and each element in shift must be an integer.

Community Examples

brushift function

(brushift x & shifts)

Returns the value of x bit shifted right by the sum of all values in shifts. x and each element in shift must be an integer. The sign of x is not preserved, so for positive shifts the return value will always be positive.

Community Examples

buffer cfunction source

(buffer & xs)

Creates a buffer by concatenating the elements of xs together. If an element is not a byte sequence, it is converted to bytes via describe. Returns the new buffer.

Community Examples

buffer? function source

(buffer? x)

Check if x is a buffer.

Community Examples

bxor function

(bxor & xs)

Returns the bit-wise xor of all values in xs. Each in xs must be an integer.

Community Examples

bytes? cfunction source

(bytes? x)

Check if x is a string, symbol, keyword, or buffer.

Community Examples

cancel function

(cancel fiber err)

Resume a fiber but have it immediately raise an error. This lets a programmer unwind a pending fiber. Returns the same result as resume.

Community Examples

case macro source

(case dispatch & pairs)

Select the body that equals the dispatch value. When pairs has an odd number of elements, the last is the default expression. If no match is found, returns nil.

Community Examples

catseq macro source

(catseq head & body)

Similar to loop, but concatenates each element from the loop body into an array and returns that. See loop for details.

Community Examples

cfunction? function source

(cfunction? x)

Check if x a cfunction.

Community Examples

chr macro source

(chr c)

Convert a string of length 1 to its byte (ascii) value at compile time.

Community Examples

cli-main function source

(cli-main args)

Entrance for the Janet CLI tool. Call this function with the command line arguments as an array or tuple of strings to invoke the CLI interface.

Community Examples

cmp function

(cmp x y)

Returns -1 if x is strictly less than y, 1 if y is strictly greater than x, and 0 otherwise. To return 0, x and y must be the exact same type.

Community Examples

comment macro source

(comment &)

Ignores the body of the comment.

Community Examples

comp function source

(comp & functions)

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

Community Examples

compare function source

(compare x y)

Polymorphic compare. Returns -1, 0, 1 for x < y, x = y, x > y respectively. Differs from the primitive comparators in that it first checks to see whether either x or y implement a compare method which can compare x and y. If so, it uses that method. If not, it delegates to the primitive comparators.

Community Examples

compare< function source

(compare< & xs)

Equivalent of < but using polymorphic compare instead of primitive comparator.

Community Examples

compare<= function source

(compare<= & xs)

Equivalent of <= but using polymorphic compare instead of primitive comparator.

Community Examples

compare= function source

(compare= & xs)

Equivalent of = but using polymorphic compare instead of primitive comparator.

Community Examples

compare> function source

(compare> & xs)

Equivalent of > but using polymorphic compare instead of primitive comparator.

Community Examples

compare>= function source

(compare>= & xs)

Equivalent of >= but using polymorphic compare instead of primitive comparator.

Community Examples

compif macro source

(compif cnd tru &opt fals)

Check the condition cnd at compile time -- if truthy, compile tru, else compile fals.

Community Examples

compile cfunction source

(compile ast &opt env source lints)

Compiles an Abstract Syntax Tree (ast) into a function. Pair the compile function with parsing functionality to implement eval. Returns a new function and does not modify ast. Returns an error struct with keys :line, :column, and :error if compilation fails. If a lints array is given, linting messages will be appended to the array. Each message will be a tuple of the form (level line col message).

Community Examples

complement function source

(complement f)

Returns a function that is the complement to the argument.

Community Examples

comptime macro source

(comptime x)

Evals x at compile time and returns the result. Similar to a top level unquote.

Community Examples

compwhen macro source

(compwhen cnd & body)

Check the condition cnd at compile time -- if truthy, compile (upscope ;body), else compile nil.

Community Examples

cond macro source

(cond & pairs)

Evaluates conditions sequentially until the first true condition is found, and then executes the corresponding body. If there are an odd number of forms, and no forms are matched, the last expression is executed. If there are no matches, returns nil.

Community Examples

coro macro source

(coro & body)

A wrapper for making fibers that may yield multiple values (coroutine). Same as (fiber/new (fn [] ;body) :yi).

Community Examples

count function source

(count pred ind & inds)

Count the number of items in ind for which (pred item) is true.

Community Examples

curenv function source

(curenv &opt n)

Get the current environment table. Same as (fiber/getenv (fiber/current)). If n is provided, gets the nth prototype of the environment table.

Community Examples

debug function

(debug &opt x)

Throws a debug signal that can be caught by a parent fiber and used to inspect the running state of the current fiber. Returns the value passed in by resume.

Community Examples

debugger function source

(debugger fiber &opt level)

Run a repl-based debugger on a fiber. Optionally pass in a level to differentiate nested debuggers.

Community Examples

debugger-env table source

An environment that contains dot prefixed functions for debugging.

Community Examples

debugger-on-status function source

(debugger-on-status env &opt level is-repl)

Create a function that can be passed to run-context's :on-status argument that will drop into a debugger on errors. The debugger will only start on abnormal signals if the env table has the :debug dyn set to a truthy value.

Community Examples

dec function source

(dec x)

Returns x - 1.

Community Examples

deep-not= function source

(deep-not= x y)

Like not=, but mutable types (arrays, tables, buffers) are considered equal if they have identical structure. Much slower than not=.

Community Examples

deep= function source

(deep= x y)

Like =, but mutable types (arrays, tables, buffers) are considered equal if they have identical structure. Much slower than =.

Community Examples

def- macro source

(def- name & more)

Define a private value that will not be exported.

EXAMPLES
# In a file module.janet
(def- private-thing :encapsulated)
(def public-thing :exposed)

# In a file main.janet
(import module)

module/private-thing # -> Unknown symbol
module/public-thing # -> :exposed

# Same as normal def with :private metadata
(def private-thing :private :encapsulated)
Community Examples

default macro source

(default sym val)

Define a default value for an optional argument. Expands to (def sym (if (= nil sym) val sym)).

Community Examples

default-peg-grammar table source

The default grammar used for pegs. This grammar defines several common patterns that should make it easier to write more complex patterns.

Community Examples

defdyn macro source

(defdyn alias & more)

Define an alias for a keyword that is used as a dynamic binding. The alias is a normal, lexically scoped binding that can be used instead of a keyword to prevent typos. defdyn does not set dynamic bindings or otherwise replace dyn and setdyn. The alias _must_ start and end with the * character, usually called "earmuffs".

Community Examples

defer macro source

(defer form & body)

Run form unconditionally after body, even if the body throws an error. Will also run form if a user signal 0-4 is received.

EXAMPLES
# Evaluates to 6 after printing "scope left!"
(defer (print "scope left!")
  (+ 1 2 3))

# cleanup will always be called, even if there is a failure
(defer (cleanup)
  (step-1)
  (step-2)
  (if (< 0.1 (math/random)) (error "failure"))
  (step-3))
Community Examples

defglobal function source

(defglobal name value)

Dynamically create a global def.

Community Examples

defmacro macro source

(defmacro name & more)

Define a macro.

Community Examples

defmacro- macro source

(defmacro- name & more)

Define a private macro that will not be exported.

Community Examples

defn macro source

(defn name & more)

Define a function. Equivalent to (def name (fn name [args] ...)).

EXAMPLES
(defn simple
  [x]
  (print (+ x 1)))

# prints 11
(simple 10) # -> nil

(defn long-body
  [y]
  (print y)
  (print (+ y 1))
  (print (+ y 2))
  (+ y 3))

(defn with-docstring
  "This function has a docstring"
  []
  (print "hello!"))

(defn with-tags
  :tag1 :tag2 :private
  "Also has a docstring and a variadic argument 'more'!"
  [x y z & more]
  [x y z more])

(with-tags 1 2) # compile error: <function with-tags> expects at least 3 arguments, got 2
(with-tags 1 2 3) # -> (1 2 3 ())
(with-tags 1 2 3 4) # -> (1 2 3 (4))
(with-tags 1 2 3 4 5) # -> (1 2 3 (4 5))

# Tags (and other metadata) are (usually) visible in the environment.
(dyn 'with-tags) # -> @{:tag2 true :value <function with-tags> :doc "(with-tags x y z & more)\n\nAlso has a docstring..." :source-map ("repl" 4 1) :tag1 true :private true}

Community Examples

defn- macro source

(defn- name & more)

Define a private function that will not be exported.

EXAMPLES
# In a file module.janet
(defn- not-exposed-fn
  [x]
  (+ x x))
(not-exposed-fn 10) # -> 20

# In a file main.janet
(import module)

(module/not-exposed-fn 10) # -> compile error: unknown symbol module/not-exposed-fn

# Same as
(defn not-exposed-fn
  :private
  [x]
  (+ x x))
Community Examples

delay macro source

(delay & forms)

Lazily evaluate a series of expressions. Returns a function that returns the result of the last expression. Will only evaluate the body once, and then memoizes the result.

EXAMPLES
(def setup-once
  (let [setup |(print "running setup")]
    (delay
     (setup)
     "setup complete")))

# first run will print "running setup" followed by "setup complete"
(printf "first run: %s" (setup-once))

# after that, only prints cached value "setup complete"
(printf "second run: %s" (setup-once))
Community Examples

describe cfunction source

(describe x)

Returns a string that is a human-readable description of x. For recursive data structures, the string returned contains a pointer value from which the identity of x can be determined.

Community Examples

dictionary? cfunction source

(dictionary? x)

Check if x is a table or struct.

Community Examples

disasm cfunction source

(disasm func &opt field)

Returns assembly that could be used to compile the given function. func must be a function, not a c function. Will throw on error on a badly typed argument. If given a field name, will only return that part of the function assembly. Possible fields are:

  • :arity - number of required and optional arguments.
  • :min-arity - minimum number of arguments function can be called with.
  • :max-arity - maximum number of arguments function can be called with.
  • :vararg - true if function can take a variable number of arguments.
  • :bytecode - array of parsed bytecode instructions. Each instruction is a tuple.
  • :source - name of source file that this function was compiled from.
  • :name - name of function.
  • :slotcount - how many virtual registers, or slots, this function uses. Corresponds to stack space used by function.
  • :symbolmap - all symbols and their slots.
  • :constants - an array of constants referenced by this function.
  • :sourcemap - a mapping of each bytecode instruction to a line and column in the source file.
  • :environments - an internal mapping of which enclosing functions are referenced for bindings.
  • :defs - other function definitions that this function may instantiate.
Community Examples

distinct function source

(distinct xs)

Returns an array of the deduplicated values in xs.

EXAMPLES
(distinct @[1 2 3 2 1]) # -> @[1 2 3]

(distinct [1 2 3 2 1]) # -> @[1 2 3]

(distinct "bookkeeper") # -> @[98 111 107 101 112 114]

(sort (map string/from-bytes
           (distinct "bookkeeper"))) # -> @["b" "e" "k" "o" "p" "r"]
Community Examples

div function

(div & xs)

Returns the floored division of xs. If xs is empty, returns 1. If xs has one value x, returns the reciprocal of x. Otherwise return the first value of xs repeatedly divided by the remaining values.

Community Examples

doc macro source

(doc &opt sym)

Shows documentation for the given symbol, or can show a list of available bindings. If sym is a symbol, will look for documentation for that symbol. If sym is a string or is not provided, will show all lexical and dynamic bindings in the current environment containing that string (all bindings will be shown if no string is given).

Community Examples

doc* function source

(doc* &opt sym)

Get the documentation for a symbol in a given environment. Function form of doc.

Community Examples

doc-format function source

(doc-format str &opt width indent colorize)

Reformat a docstring to wrap a certain width. Docstrings can either be plaintext or a subset of markdown. This allows a long single line of prose or formatted text to be a well-formed docstring. Returns a buffer containing the formatted text.

Community Examples

doc-of function source

(doc-of x)

Searches all loaded modules in module/cache for a given binding and prints out its documentation. This does a search by value instead of by name. Returns nil.

Community Examples

dofile function source

(dofile path &named exit env source expander evaluator read parser)

Evaluate a file, file path, or stream and return the resulting environment. :env, :expander, :source, :evaluator, :read, and :parser are passed through to the underlying run-context call. If exit is true, any top level errors will trigger a call to (os/exit 1) after printing the error.

Community Examples

drop function source

(drop n ind)

Drop the first n elements in an indexed or bytes type. Returns a new tuple or string instance, respectively. If n is negative, drops the last n elements instead.

Community Examples

drop-until function source

(drop-until pred ind)

Same as (drop-while (complement pred) ind).

Community Examples

drop-while function source

(drop-while pred ind)

Given a predicate, remove elements from an indexed or bytes type that satisfy the predicate, and abort on first failure. Returns a new tuple or string, respectively.

Community Examples

dyn cfunction source

(dyn key &opt default)

Get a dynamic binding. Returns the default value (or nil) if no binding found.

Community Examples

each macro source

(each x ds & body)

Loop over each value in ds. Returns nil.

EXAMPLES
# prints 12345
(each x [1 2 3 4 5] (prin x)) # -> nil

# prints 12345
(each y @[1 2 3 4 5] (prin y)) # -> nil

# prints values from struct in an unspecified order
# 21 -or- 12
(each x {:a 1 :b 2} (prin x)) # -> nil
Community Examples

eachk macro source

(eachk x ds & body)

Loop over each key in ds. Returns nil.

EXAMPLES
# keys for tuple/array are 0-based index
# prints 0 1 2 3 4
(eachk i [:a :b :c :d :e] (prin i " ")) # -> nil

# prints 0 1 2 3 4
(eachk i @["a" "b" "c" "d" "e"] (prin i " ")) # -> nil

# prints keys in table/struct in an unspecified order
# prints :b :a
(eachk k {:a 1 :b 2} (prinf "%v " k)) # -> nil

# prints :foo :bar
(eachk k @{:foo "A" :bar "B"} (prinf "%v " k)) # -> nil
Community Examples

eachp macro source

(eachp x ds & body)

Loop over each (key, value) pair in ds. Returns nil.

EXAMPLES
# keys for tuple/array are 0-based index
# prints 0->:a 1->:b 2->:c 3->:d 4->:e
(eachp [i x] [:a :b :c :d :e] (prinf "%v->%v " i x)) # -> nil

# prints 0->"a" 1->"b" 2->"c" 3->"d" 4->"e"
(eachp [i x] @["a" "b" "c" "d" "e"] (prinf "%v->%v " i x)) # -> nil

# key, value from table/struct in an unspecified order
# prints :b -> 2 :a -> 1
(eachp [k v] {:a 1 :b 2} (prinf "%v -> %v " k v)) # -> nil

# prints :foo -> "A" :bar -> "B"
(eachp [k v] @{:foo "A" :bar "B"} (prinf "%v -> %v " k v)) # -> nil
Community Examples

edefer macro source

(edefer form & body)

Run form after body in the case that body terminates abnormally (an error or user signal 0-4). Otherwise, return last form in body.

EXAMPLES
# Half of the time, return "ok", the other
# half of the time, print there was an error and throw "oops".
(edefer (print "there was an error")
  (if (< (math/random) 0.5)
    (error "oops")
    "ok"))
Community Examples

eflush cfunction source

(eflush)

Flush (dyn :err stderr) if it is a file, otherwise do nothing.

Community Examples

empty? function source

(empty? xs)

Check if xs is empty.

EXAMPLES
(empty? []) # -> true

(empty? [1]) # -> false

(empty? @[]) # -> true

(empty? @{}) # -> true

(empty? "") # -> true

(empty? 0) # -> error: expected iterable type, got 0
Community Examples

env-lookup cfunction source

(env-lookup env)

Creates a forward lookup table for unmarshalling from an environment. To create a reverse lookup table, use the invert function to swap keys and values in the returned table.

Community Examples

eprin cfunction source

(eprin & xs)

Same as prin, but uses (dyn :err stderr) instead of (dyn :out stdout).

Community Examples

eprinf cfunction source

(eprinf fmt & xs)

Like eprintf but with no trailing newline.

Community Examples

eprint cfunction source

(eprint & xs)

Same as print, but uses (dyn :err stderr) instead of (dyn :out stdout).

Community Examples

eprintf cfunction source

(eprintf fmt & xs)

Prints output formatted as if with (string/format fmt ;xs) to (dyn :err stderr) with a trailing newline.

Community Examples

error function

(error e)

Throws an error e that can be caught and handled by a parent fiber.

Community Examples

errorf function source

(errorf fmt & args)

A combination of error and string/format. Equivalent to (error (string/format fmt ;args)).

Community Examples

eval function source

(eval form &opt env)

Evaluates a form in the current environment. If more control over the environment is needed, use run-context. Optionally pass in an env table with available bindings.

EXAMPLES
(eval '(+ 1 2 3)) # -> 6
(eval '(error :oops)) # -> error :oops
(eval '(+ nil nil)) # -> error: could not find method :+ for nil or :r+ for nil
Community Examples

eval-string function source

(eval-string str &opt env)

Evaluates a string in the current environment. If more control over the environment is needed, use run-context. Optionally pass in an env table with available bindings.

EXAMPLES
(eval-string "(+ 1 2 3 4)") # -> 10
(eval-string ")") # -> error: unexpected closing delimiter )
(eval-string "(bloop)") # -> error: unknown symbol bloop
(eval-string "(+ nil nil)") # -> error: could not find method :+ for nil or :r+ for nil
Community Examples

even? function source

(even? x)

Check if x is even.

Community Examples

every? function source

(every? ind)

Evaluates to the last element of ind if all preceding elements are truthy, otherwise evaluates to the first falsey element.

Community Examples

extreme function source

(extreme order args)

Returns the most extreme value in args based on the function order. order should take two values and return true or false (a comparison). Returns nil if args is empty.

Community Examples

false? function source

(false? x)

Check if x is false.

Community Examples

fiber-fn macro source

(fiber-fn flags & body)

A wrapper for making fibers. Same as (fiber/new (fn [] ;body) flags).

Community Examples

fiber? function source

(fiber? x)

Check if x is a fiber.

Community Examples

filter function source

(filter pred ind)

Given a predicate, take only elements from an array or tuple for which (pred element) is truthy. Returns a new array.

EXAMPLES
(filter pos? [1 2 3 0 -4 5 6]) # -> @[1 2 3 5 6]

(filter |(> (length $) 3) ["hello" "goodbye" "hi"]) # -> @["hello" "goodbye"]

(filter |(< (chr "A") $) "foo01bar") # -> @[102 111 111 98 97 114]

(string/from-bytes ;(filter |(< (chr "A") $) "foo01bar")) # -> "foobar"
Community Examples

find function source

(find pred ind &opt dflt)

Find the first value in an indexed collection that satisfies a predicate. Returns dflt if not found.

Community Examples

find-index function source

(find-index pred ind &opt dflt)

Find the index of indexed type for which pred is true. Returns dflt if not found.

Community Examples

first function source

(first xs)

Get the first element from an indexed data structure.

Community Examples

flatten function source

(flatten xs)

Takes a nested array (tree) xs and returns the depth first traversal of it. Returns a new array.

Community Examples

flatten-into function source

(flatten-into into xs)

Takes a nested array (tree) xs and appends the depth first traversal of xs to array into. Returns into.

Community Examples

flush cfunction source

(flush)

Flush (dyn :out stdout) if it is a file, otherwise do nothing.

Community Examples

flycheck function source

(flycheck path &keys kwargs)

Check a file for errors without running the file. Found errors will be printed to stderr in the usual format. Macros will still be executed, however, so arbitrary execution is possible. Other arguments are the same as dofile. path can also be a file value such as stdin. Returns nil.

Community Examples

for macro source

(for i start stop & body)

Do a C-style for-loop for side effects. Returns nil.

Community Examples

forever macro source

(forever & body)

Evaluate body forever in a loop, or until a break statement.

Community Examples

forv macro source

(forv i start stop & body)

Do a C-style for-loop for side effects. The iteration variable i can be mutated in the loop, unlike normal for. Returns nil.

Community Examples

freeze function source

(freeze x)

Freeze an object (make it immutable) and do a deep copy, making child values also immutable. Closures, fibers, and abstract types will not be recursively frozen, but all other types will.

Community Examples

frequencies function source

(frequencies ind)

Get the number of occurrences of each value in an indexed data structure.

Community Examples

from-pairs function source

(from-pairs ps)

Takes a sequence of pairs and creates a table from each pair. It is the inverse of pairs on a table. Returns a new table.

Community Examples

function? function source

(function? x)

Check if x is a function (not a cfunction).

Community Examples

gccollect cfunction source

(gccollect)

Run garbage collection. You should probably not call this manually.

Community Examples

gcinterval cfunction source

(gcinterval)

Returns the integer number of bytes to allocate before running an iteration of garbage collection.

Community Examples

gcsetinterval cfunction source

(gcsetinterval interval)

Set an integer number of bytes to allocate before running garbage collection. Low values for interval will be slower but use less memory. High values will be faster but use more memory.

Community Examples

generate macro source

(generate head & body)

Create a generator expression using the loop syntax. Returns a fiber that yields all values inside the loop in order. See loop for details.

EXAMPLES
# An infinite stream of random numbers, but doubled.
(def g (generate [_ :iterate true :repeat 2] (math/random)))
# -> <fiber 0x5562863141E0>

(resume g) # -> 0.487181
(resume g) # -> 0.487181
(resume g) # -> 0.507917
(resume g) # -> 0.507917
# ...
Community Examples

gensym cfunction source

(gensym)

Returns a new symbol that is unique across the runtime. This means it will not collide with any already created symbols during compilation, so it can be used in macros to generate automatic bindings.

Community Examples

geomean function source

(geomean xs)

Returns the geometric mean of xs. If empty, returns NaN.

Community Examples

get function

(get ds key &opt dflt)

Get the value mapped to key in data structure ds, and return dflt or nil if not found. Similar to in, but will not throw an error if the key is invalid for the data structure unless the data structure is an abstract type. In that case, the abstract type getter may throw an error.

Community Examples

get-in function source

(get-in ds ks &opt dflt)

Access a value in a nested data structure. Looks into the data structure via a sequence of keys. If value is not found, and dflt is provided, returns dflt.

Community Examples

getline cfunction source

(getline &opt prompt buf env)

Reads a line of input into a buffer, including the newline character, using a prompt. An optional environment table can be provided for auto-complete. Returns the modified buffer. Use this function to implement a simple interface for a terminal program.

Community Examples

getproto cfunction source

(getproto x)

Get the prototype of a table or struct. Will return nil if x has no prototype.

Community Examples

group-by function source

(group-by f ind)

Group elements of ind by a function f and put the results into a new table. The keys of the table are the distinct return values from calling f on the elements of ind. The values of the table are arrays of all elements of ind for which f called on the element equals that corresponding key.

Community Examples

has-key? function source

(has-key? ds key)

Check if a data structure ds contains the key key.

EXAMPLES
# tables
(has-key? @{} 0) # -> false
(has-key? @{:key1 "foo" :key2 "bar"} :key1) # -> true
(has-key? @{:key1 "foo" :key2 "bar"} :key3) # -> false

# structs
(has-key? {} 0) # -> false
(has-key? {:key1 "foo" :key2 "bar"} :key1) # -> true
(has-key? {:key1 "foo" :key2 "bar"} :key3) # -> false

# buffers, tuples and arrays check for index as key
(has-key? "" 0) # -> false
(has-key? "a" 0) # -> true
(has-key? "a" 1) # -> false

(has-key? [] 0) # -> false
(has-key? ["a" "b" "c"] 1) # -> true
(has-key? ["a" "b" "c"] 4) # -> false

(has-key? @[] 0) # -> false
(has-key? @["a" "b" "c"] 1) # -> true
(has-key? @["a" "b" "c"] 4) # -> false
Community Examples

has-value? function source

(has-value? ds value)

Check if a data structure ds contains the value value. Will run in time proportional to the size of ds.

EXAMPLES
# tables
(has-value? @{} 0) # -> false
(has-value? @{:key1 "foo" :key2 "bar"} "foo") # -> true
(has-value? @{:key1 "foo" :key2 "bar"} "hello") # -> false
(has-value? @{:key1 "foo" :key2 "bar"} nil) # -> false

# structs
(has-value? {} 0) # -> false
(has-value? {:key1 "foo" :key2 "bar"} "foo") # -> true
(has-value? {:key1 "foo" :key2 "bar"} "hello") # -> false
(has-value? {:key1 "foo" :key2 "bar"} nil) # -> false

# buffers - individual values are bytes
(has-value? "" 0) # -> false
(has-value? "" nil) # -> false
(has-value? "abc" 97) # -> true
(has-value? "abc" "a") # -> false
(has-value? "abc" 'a) # -> false

# tuples
(has-value? [] 0) # -> false
(has-value? ["a" "b" "c"] "a") # -> true
(has-value? ["a" "b" "c"] 'a) # -> false
(has-value? ["a" "b" "c"] 97) # -> false

# arrays
(has-value? @[] 0) # -> false
(has-value? @["a" "b" "c"] "a") # -> true
(has-value? @["a" "b" "c"] 'a) # -> false
(has-value? @["a" "b" "c"] 97) # -> false
Community Examples

hash cfunction source

(hash value)

Gets a hash for any value. The hash is an integer can be used as a cheap hash function for all values. If two values are strictly equal, then they will have the same hash value.

Community Examples

idempotent? function source

(idempotent? x)

Check if x is a value that evaluates to itself when compiled.

Community Examples

identity function source

(identity x)

A function that returns its argument.

Community Examples

if-let macro source

(if-let bindings tru &opt fal)

Make multiple bindings, and if all are truthy, evaluate the tru form. If any are false or nil, evaluate the fal form. Bindings have the same syntax as the let macro.

Community Examples

if-not macro source

(if-not condition then &opt else)

Shorthand for (if (not condition) else then).

Community Examples

if-with macro source

(if-with [binding ctor dtor] truthy &opt falsey)

Similar to with, but if binding is false or nil, evaluates the falsey path. Otherwise, evaluates the truthy path. In both cases, ctor is bound to binding.

Community Examples

import macro source

(import path & args)

Import a module. First requires the module, and then merges its symbols into the current environment, prepending a given prefix as needed. (use the :as or :prefix option to set a prefix). If no prefix is provided, use the name of the module as a prefix. One can also use ":export true" to re-export the imported symbols. If ":exit true" is given as an argument, any errors encountered at the top level in the module will cause (os/exit 1) to be called. Dynamic bindings will NOT be imported. Use :fresh to bypass the module cache. Use :only [foo bar baz] to only import select bindings into the current environment.

Community Examples

import* function source

(import* path & args)

Function form of import. Same parameters, but the path and other symbol parameters should be strings instead.

Community Examples

in function

(in ds key &opt dflt)

Get value in ds at key, works on associative data structures. Arrays, tuples, tables, structs, strings, symbols, and buffers are all associative and can be used. Arrays, tuples, strings, buffers, and symbols must use integer keys that are in bounds or an error is raised. Structs and tables can take any value as a key except nil and will return nil or dflt if not found.

Community Examples

inc function source

(inc x)

Returns x + 1.

Community Examples

index-of function source

(index-of x ind &opt dflt)

Find the first key associated with a value x in a data structure, acting like a reverse lookup. Will not look at table prototypes. Returns dflt if not found.

Community Examples

indexed? cfunction source

(indexed? x)

Check if x is an array or tuple.

Community Examples

int? cfunction source

(int? x)

Check if x can be exactly represented as a 32 bit signed two's complement integer.

Community Examples

interleave function source

(interleave & cols)

Returns an array of the first elements of each col, then the second elements, etc.

Community Examples

interpose function source

(interpose sep ind)

Returns a sequence of the elements of ind separated by sep. Returns a new array.

Community Examples

invert function source

(invert ds)

Given an associative data structure ds, returns a new table where the keys of ds are the values, and the values are the keys. If multiple keys in ds are mapped to the same value, only one of those values will become a key in the returned table.

Community Examples

juxt macro source

(juxt & funs)

Macro form of juxt*. Same behavior but more efficient.

Community Examples

juxt* function source

(juxt* & funs)

Returns the juxtaposition of functions. In other words, ((juxt* a b c) x) evaluates to [(a x) (b x) (c x)].

Community Examples

keep function source

(keep pred ind & inds)

Given a predicate pred, return a new array containing the truthy results of applying pred to each element in the indexed collection ind. This is different from filter which returns an array of the original elements where the predicate is truthy.

EXAMPLES
# returns an array of truthy results of predicate
(keep identity [false :x nil true]) # -> @[:x true]

# keep values > 1, equivalent to filter
(keep (fn [x] (when (> x 1) x)) @[0 1 2 3]) # -> @[2 3]

# for all members > 2, keep the square
(keep (fn [x] (when (> x 2) (* x x))) [0 1 3 4 5]) # -> @[9 16 25]

Community Examples

keep-syntax function source

(keep-syntax before after)

Creates a tuple with the tuple type and sourcemap of before but the elements of after. If either one of its arguments is not a tuple, returns after unmodified. Useful to preserve syntactic information when transforming an ast in macros.

Community Examples

keep-syntax! function source

(keep-syntax! before after)

Like keep-syntax, but if after is an array, it is coerced into a tuple. Useful to preserve syntactic information when transforming an ast in macros.

Community Examples

keys function source

(keys x)

Get the keys of an associative data structure.

Community Examples

keyword cfunction source

(keyword & xs)

Creates a keyword by concatenating the elements of xs together. If an element is not a byte sequence, it is converted to bytes via describe. Returns the new keyword.

Community Examples

keyword? function source

(keyword? x)

Check if x is a keyword.

Community Examples

kvs function source

(kvs dict)

Takes a table or struct and returns and array of key value pairs like @[k v k v ...]. Returns a new array.

Community Examples

label macro source

(label name & body)

Set a label point that is lexically scoped. name should be a symbol that will be bound to the label.

Community Examples

last function source

(last xs)

Get the last element from an indexed data structure.

Community Examples

length function

(length ds)

Returns the length or count of a data structure in constant time as an integer. For structs and tables, returns the number of key-value pairs in the data structure.

Community Examples

lengthable? cfunction source

(lengthable? x)

Check if x is a bytes, indexed, or dictionary.

Community Examples

let macro source

(let bindings & body)

Create a scope and bind values to symbols. Each pair in bindings is assigned as if with def, and the body of the let form returns the last value.

Community Examples

load-image function source

(load-image image)

The inverse operation to make-image. Returns an environment.

Community Examples

load-image-dict table source

A table used in combination with unmarshal to unmarshal byte sequences created by make-image, such that (load-image bytes) is the same as (unmarshal bytes load-image-dict).

Community Examples

loop macro source

(loop head & body)

A general purpose loop macro. This macro is similar to the Common Lisp loop macro, although intentionally much smaller in scope. The head of the loop should be a tuple that contains a sequence of either bindings or conditionals. A binding is a sequence of three values that define something to loop over. Bindings are written in the format:

        binding :verb object/expression

where binding is a binding as passed to def, :verb is one of a set of keywords, and object is any expression. Each subsequent binding creates a nested loop within the loop created by the previous binding.

The available verbs are:

  • :iterate -- repeatedly evaluate and bind to the expression while it is truthy.

  • :range -- loop over a range. The object should be a two-element tuple with a start and end value, and an optional positive step. The range is half open, [start, end).

  • :range-to -- same as :range, but the range is inclusive [start, end].

  • :down -- loop over a range, stepping downwards. The object should be a two-element tuple with a start and (exclusive) end value, and an optional (positive!) step size.

  • :down-to -- same as :down, but the range is inclusive [start, end].

  • :keys -- iterate over the keys in a data structure.

  • :pairs -- iterate over the key-value pairs as tuples in a data structure.

  • :in -- iterate over the values in a data structure or fiber.

loop also accepts conditionals to refine the looping further. Conditionals are of the form:

        :modifier argument

where :modifier is one of a set of keywords, and argument is keyword-dependent. :modifier can be one of:

  • :while expression -- breaks from the current loop if expression is falsey.

  • :until expression -- breaks from the current loop if expression is truthy.

  • :let bindings -- defines bindings inside the current loop as passed to the let macro.

  • :before form -- evaluates a form for a side effect before the next inner loop.

  • :after form -- same as :before, but the side effect happens after the next inner loop.

  • :repeat n -- repeats the next inner loop n times.

  • :when condition -- only evaluates the current loop body when condition is truthy.

  • :unless condition -- only evaluates the current loop body when condition is falsey.

The loop macro always evaluates to nil.

EXAMPLES
# prints 0123456789 (not followed by newline)
(loop [x :range [0 10]]
  (prin x)) # -> nil

# Cartesian product (nested loops)

# prints 00010203101112132021222330313233
# Same as (for x 0 4 (for y 0 4 (prin x y)))
(loop [x :range [0 4]
       y :range [0 4]]
  (prin x y)) # -> nil

# prints bytes of "hello, world" as numbers
(loop [character :in "hello, world"]
  (print character)) # -> nil

# prints 1, 2, and 3, in an unspecified order
(loop [value :in {:a 1 :b 2 :c 3}]
  (print value)) # -> nil

# prints 0 to 99 inclusive
(loop [x :in (range 100)]
  (print x)) # -> nil

# Complex body
(loop [x :in (range 10)]
  (print x)
  (print (inc x))
  (print (+ x 2))) # -> nil
# prints n, n+1, n+2 (for n = 0 through 9) each time through the loop
# 0
# 1
# 2
# ...
# 9
# 10
# 11

# Iterate over keys
(loop [k :keys {:a 1 :b 2 :c 3}]
  (print k)) # -> nil
# print a, b, and c in an unspecified order

(loop [index :keys [:a :b :c :d]]
  (print index)) # -> nil
# print 0, 1, 2, and 3 in order.

(defn print-pairs
  [x]
  (loop [[k v] :pairs x]
    (printf "[%v]=%v" k v)))

(print-pairs [:a :b :c]) # -> nil
# prints
# [0]=:a
# [1]=:b
# [2]=:c

(print-pairs {:a 1 :b 2 :c 3}) # -> nil
# prints
# [:a]=1
# [:b]=2
# [:c]=3

# Some modifiers - allow early termination and conditional execution
# of the loop

(loop [x :range [0 100] :when (even? x)]
  (print x)) # -> nil
# prints even numbers 0, 2, 4, ..., 98

(loop [x :range [1 100] :while (pos? (% x 7))]
  (print x)) # -> nil
# prints 1, 2, 3, 4, 5, 6

# Consume fibers as generators
(def f
  (fiber/new
    (fn []
      (for i 0 100
        (yield i)))))

(loop [x :in f]
  (print x)) # -> nil
# print 0, 1, 2, ... 99

# Modifiers in nested loops
(loop [x :range [0 10]
      :after (print)
       y :range [0 x]]
  (prin y " ")) # -> nil
# prints
# 0
# 0 1
# 0 1 2
# 0 1 2 3
# 0 1 2 3 4
# 0 1 2 3 4 5
# 0 1 2 3 4 5 6
# 0 1 2 3 4 5 6 7
# 0 1 2 3 4 5 6 7 8

Community Examples

macex function source

(macex x &opt on-binding)

Expand macros completely. on-binding is an optional callback for whenever a normal symbolic binding is encountered. This allows macros to easily see all bindings used by their arguments by calling macex on their contents. The binding itself is also replaced by the value returned by on-binding within the expanded macro.

Community Examples

macex1 function source

(macex1 x &opt on-binding)

Expand macros in a form, but do not recursively expand macros. See macex docs for info on on-binding.

Community Examples

maclintf function source

(maclintf level fmt & args)

When inside a macro, call this function to add a linter warning. Takes a fmt argument like string/format, which is used to format the message.

Community Examples

make-env function source

(make-env &opt parent)

Create a new environment table. The new environment will inherit bindings from the parent environment, but new bindings will not pollute the parent environment.

Community Examples

make-image function source

(make-image env)

Create an image from an environment returned by require. Returns the image source as a string.

Community Examples

make-image-dict table source

A table used in combination with marshal to marshal code (images), such that (make-image x) is the same as (marshal x make-image-dict).

Community Examples

map function source

(map f ind & inds)

Map a function over every value in a data structure and return an array of the results.

EXAMPLES
# inc is applied to every value of the input data structure
(map inc [7 8 9]) # -> @[8 9 10]

# multiple data structures can be handled
(map array [:x :y] [-1 1]) # -> @[@[:x -1] @[:y 1]]

# result array has length of the shortest input data structure
(map |(pos? (+ ;$&)) [1 2 3] [-1 -2 -3] [0 1]) # -> @[false true]

Community Examples

mapcat function source

(mapcat f ind & inds)

Map a function over every element in an array or tuple and use array/concat to concatenate the results.

Community Examples

marshal cfunction source

(marshal x &opt reverse-lookup buffer no-cycles)

Marshal a value into a buffer and return the buffer. The buffer can then later be unmarshalled to reconstruct the initial value. Optionally, one can pass in a reverse lookup table to not marshal aliased values that are found in the table. Then a forward lookup table can be used to recover the original value when unmarshalling.

Community Examples

match macro source

(match x & cases)

Pattern matching. Match an expression x against any number of cases. Each case is a pattern to match against, followed by an expression to evaluate to if that case is matched. Legal patterns are:

  • symbol -- a pattern that is a symbol will match anything, binding x's value to that symbol.

  • array or bracket tuple -- an array or bracket tuple will match only if all of its elements match the corresponding elements in x. Use & rest at the end of an array or bracketed tuple to bind all remaining values to rest.

  • table or struct -- a table or struct will match if all values match with the corresponding values in x.

  • tuple -- a tuple pattern will match if its first element matches, and the following elements are treated as predicates and are true.

  • _ symbol -- the last special case is the _ symbol, which is a wildcard that will match any value without creating a binding.

While a symbol pattern will ordinarily match any value, the pattern (@ <sym>), where <sym> is any symbol, will attempt to match x against a value already bound to <sym>, rather than matching and rebinding it.

Any other value pattern will only match if it is equal to x. Quoting a pattern with ' will also treat the value as a literal value to match against.

Community Examples

max function source

(max & args)

Returns the numeric maximum of the arguments.

Community Examples

max-of function source

(max-of args)

Returns the numeric maximum of the argument sequence.

Community Examples

mean function source

(mean xs)

Returns the mean of xs. If empty, returns NaN.

Community Examples

memcmp cfunction source

(memcmp a b &opt len offset-a offset-b)

Compare memory. Takes two byte sequences a and b, and return 0 if they have identical contents, a negative integer if a is less than b, and a positive integer if a is greater than b. Optionally take a length and offsets to compare slices of the bytes sequences.

Community Examples

merge function source

(merge & colls)

Merges multiple tables/structs into one new table. If a key appears in more than one collection in colls, then later values replace any previous ones. Returns the new table.

Community Examples

merge-into function source

(merge-into tab & colls)

Merges multiple tables/structs into table tab. If a key appears in more than one collection in colls, then later values replace any previous ones. Returns tab.

Community Examples

merge-module function source

(merge-module target source &opt prefix export only)

Merge a module source into the target environment with a prefix, as with the import macro. This lets users emulate the behavior of import with a custom module table. If export is truthy, then merged functions are not marked as private. Returns the modified target environment. If a tuple or array only is passed, only merge keys in only.

Community Examples

min function source

(min & args)

Returns the numeric minimum of the arguments.

Community Examples

min-of function source

(min-of args)

Returns the numeric minimum of the argument sequence.

Community Examples

mod function

(mod & xs)

Returns the result of applying the modulo operator on the first value of xs with each remaining value. (mod x 0) is defined to be x.

Community Examples

nan? function source

(nan? x)

Check if x is NaN.

Community Examples

nat? cfunction source

(nat? x)

Check if x can be exactly represented as a non-negative 32 bit signed two's complement integer.

Community Examples

native cfunction source

(native path &opt env)

Load a native module from the given path. The path must be an absolute or relative path on the file system, and is usually a .so file on Unix systems, and a .dll file on Windows. Returns an environment table that contains functions and other values from the native module.

Community Examples

neg? function source

(neg? x)

Check if x is less than 0.

Community Examples

next function

(next ds &opt key)

Gets the next key in a data structure. Can be used to iterate through the keys of a data structure in an unspecified order. Keys are guaranteed to be seen only once per iteration if the data structure is not mutated during iteration. If key is nil, next returns the first key. If next returns nil, there are no more keys to iterate through.

Community Examples

nil? function source

(nil? x)

Check if x is nil.

Community Examples

not cfunction source

(not x)

Returns the boolean inverse of x.

Community Examples

not= function

(not= & xs)

Check if any values in xs are not equal. Returns a boolean.

Community Examples

number? function source

(number? x)

Check if x is a number.

Community Examples

odd? function source

(odd? x)

Check if x is odd.

Community Examples

one? function source

(one? x)

Check if x is equal to 1.

Community Examples

or macro source

(or & forms)

Evaluates to the last argument if all preceding elements are falsey, otherwise evaluates to the first truthy element.

Community Examples

pairs function source

(pairs x)

Get the key-value pairs of an associative data structure.

Community Examples

parse function source

(parse str)

Parse a string and return the first value. For complex parsing, such as for a repl with error handling, use the parser api.

Community Examples

parse-all function source

(parse-all str)

Parse a string and return all parsed values. For complex parsing, such as for a repl with error handling, use the parser api.

Community Examples

partial function source

(partial f & more)

Partial function application.

Community Examples

partition function source

(partition n ind)

Partition an indexed data structure ind into tuples of size n. Returns a new array.

Community Examples

partition-by function source

(partition-by f ind)

Partition elements of a sequential data structure by a representative function f. Partitions split when (f x) changes values when iterating to the next element x of ind. Returns a new array of arrays.

Community Examples

pos? function source

(pos? x)

Check if x is greater than 0.

Community Examples

postwalk function source

(postwalk f form)

Do a post-order traversal of a data structure and call (f x) on every visitation.

Community Examples

pp function source

(pp x)

Pretty-print to stdout or (dyn *out*). The format string used is (dyn *pretty-format* "%q").

Community Examples

prewalk function source

(prewalk f form)

Similar to postwalk, but do pre-order traversal.

Community Examples

prin cfunction source

(prin & xs)

Same as print, but does not add trailing newline.

Community Examples

prinf cfunction source

(prinf fmt & xs)

Like printf but with no trailing newline.

Community Examples

print cfunction source

(print & xs)

Print values to the console (standard out). Value are converted to strings if they are not already. After printing all values, a newline character is printed. Use the value of (dyn :out stdout) to determine what to push characters to. Expects (dyn :out stdout) to be either a core/file or a buffer. Returns nil.

Community Examples

printf cfunction source

(printf fmt & xs)

Prints output formatted as if with (string/format fmt ;xs) to (dyn :out stdout) with a trailing newline.

Community Examples

product function source

(product xs)

Returns the product of xs. If xs is empty, returns 1.

EXAMPLES
(product []) # -> 1
(product @[1 2 3]) # -> 6
(product [0 1 2 3]) # -> 0
(product (range 1 10)) # -> 362880

# Product over byte values [0-255] in a string
(product "hello") # -> 13599570816

# Product over values in a table or struct
(product {:a 1 :b 2 :c 4}) # -> 8
Community Examples

prompt macro source

(prompt tag & body)

Set up a checkpoint that can be returned to. tag should be a value that is used in a return statement, like a keyword.

Community Examples

propagate function

(propagate x fiber)

Propagate a signal from a fiber to the current fiber and set the last value of the current fiber to x. The signal value is then available as the status of the current fiber. The resulting stack trace from the current fiber will include frames from fiber. If fiber is in a state that can be resumed, resuming the current fiber will first resume fiber. This function can be used to re-raise an error without losing the original stack trace.

Community Examples

protect macro source

(protect & body)

Evaluate expressions, while capturing any errors. Evaluates to a tuple of two elements. The first element is true if successful, false if an error, and the second is the return value or error.

Community Examples

put function

(put ds key value)

Associate a key with a value in any mutable associative data structure. Indexed data structures (arrays and buffers) only accept non-negative integer keys, and will expand if an out of bounds value is provided. In an array, extra space will be filled with nils, and in a buffer, extra space will be filled with 0 bytes. In a table, putting a key that is contained in the table prototype will hide the association defined by the prototype, but will not mutate the prototype table. Putting a value nil into a table will remove the key from the table. Returns the data structure ds.

Community Examples

put-in function source

(put-in ds ks v)

Put a value into a nested data structure ds. Looks into ds via a sequence of keys. Missing data structures will be replaced with tables. Returns the modified, original data structure.

Community Examples

quit function source

(quit &opt value)

Tries to exit from the current repl or run-context. Does not always exit the application. Works by setting the :exit dynamic binding to true. Passing a non-nil value here will cause the outer run-context to return that value.

Community Examples

range cfunction source

(range & args)

Create an array of values [start, end) with a given step. With one argument, returns a range [0, end). With two arguments, returns a range [start, end). With three, returns a range with optional step size.

EXAMPLES
(range 10) # -> @[0 1 2 3 4 5 6 7 8 9]
(range 5 10) # -> @[5 6 7 8 9]
(range 5 10 2) # -> @[5 7 9]
(range 5 11 2) # -> @[5 7 9]
(range 10 0 -1) # -> @[10 9 8 7 6 5 4 3 2 1]
Community Examples

reduce function source

(reduce f init ind)

Reduce, also know as fold-left in many languages, transforms an indexed type (array, tuple) with a function to produce a value by applying f to each element in order. f is a function of 2 arguments, (f accum el), where accum is the initial value and el is the next value in the indexed type ind. f returns a value that will be used as accum in the next call to f. reduce returns the value of the final call to f.

Community Examples

reduce2 function source

(reduce2 f ind)

The 2-argument version of reduce that does not take an initialization value. Instead, the first element of the array is used for initialization. If ind is empty, will evaluate to nil.

Community Examples

repeat macro source

(repeat n & body)

Evaluate body n times. If n is negative, body will be evaluated 0 times. Evaluates to nil.

Community Examples

repl function source

(repl &opt chunks onsignal env parser read)

Run a repl. The first parameter is an optional function to call to get a chunk of source code that should return nil for end of file. The second parameter is a function that is called when a signal is caught. One can provide an optional environment table to run the repl in, as well as an optional parser or read function to pass to run-context.

Community Examples

require function source

(require path & args)

Require a module with the given name. Will search all of the paths in module/paths. Returns the new environment returned from compiling and running the file.

Community Examples

resume function

(resume fiber &opt x)

Resume a new or suspended fiber and optionally pass in a value to the fiber that will be returned to the last yield in the case of a pending fiber, or the argument to the dispatch function in the case of a new fiber. Returns either the return result of the fiber's dispatch function, or the value from the next yield call in fiber.

Community Examples

return function source

(return to &opt value)

Return to a prompt point.

Community Examples

reverse function source

(reverse t)

Reverses the order of the elements in a given array or tuple and returns a new array. If a string or buffer is provided, returns a buffer instead.

EXAMPLES
(reverse [1 2 3]) # -> @[3 2 1]
(reverse "abcdef") # -> @"fedcba"

Community Examples

reverse! function source

(reverse! t)

Reverses the order of the elements in a given array or buffer and returns it mutated.

Community Examples

root-env table

The root environment used to create environments with (make-env).

Community Examples

run-context function source

(run-context opts)

Run a context. This evaluates expressions in an environment, and encapsulates the parsing, compilation, and evaluation. Returns (in environment :exit-value environment) when complete. opts is a table or struct of options. The options are as follows:

  • :chunks -- callback to read into a buffer - default is getline

  • :on-parse-error -- callback when parsing fails - default is bad-parse

  • :env -- the environment to compile against - default is the current env

  • :source -- source path for better errors (use keywords for non-paths) - default is :<anonymous>

  • :on-compile-error -- callback when compilation fails - default is bad-compile

  • :on-compile-warning -- callback for any linting error - default is warn-compile

  • :evaluator -- callback that executes thunks. Signature is (evaluator thunk source env where)

  • :on-status -- callback when a value is evaluated - default is debug/stacktrace.

  • :fiber-flags -- what flags to wrap the compilation fiber with. Default is :ia.

  • :expander -- an optional function that is called on each top level form before being compiled.

  • :parser -- provide a custom parser that implements the same interface as Janet's built-in parser.

  • :read -- optional function to get the next form, called like (read env source). Overrides all parsing.

Community Examples

sandbox cfunction source

(sandbox & forbidden-capabilities)

Disable feature sets to prevent the interpreter from using certain system resources. Once a feature is disabled, there is no way to re-enable it. Capabilities can be:

  • :all - disallow all (except IO to stdout, stderr, and stdin)
  • :env - disallow reading and write env variables
  • :ffi - disallow FFI (recommended if disabling anything else)
  • :ffi-define - disallow loading new FFI modules and binding new functions
  • :ffi-jit - disallow calling ffi/jitfn
  • :ffi-use - disallow using any previously bound FFI functions and memory-unsafe functions.
  • :fs - disallow access to the file system
  • :fs-read - disallow read access to the file system
  • :fs-temp - disallow creating temporary files
  • :fs-write - disallow write access to the file system
  • :hrtime - disallow high-resolution timers
  • :modules - disallow load dynamic modules (natives)
  • :net - disallow network access
  • :net-connect - disallow making outbound network connections
  • :net-listen - disallow accepting inbound network connections
  • :sandbox - disallow calling this function
  • :signal - disallow adding or removing signal handlers
  • :subprocess - disallow running subprocesses
Community Examples

scan-number cfunction source

(scan-number str &opt base)

Parse a number from a byte sequence and return that number, either an integer or a real. The number must be in the same format as numbers in janet source code. Will return nil on an invalid number. Optionally provide a base - if a base is provided, no radix specifier is expected at the beginning of the number.

Community Examples

seq macro source

(seq head & body)

Similar to loop, but accumulates the loop body into an array and returns that. See loop for details.

EXAMPLES
(seq [x :range [0 5]] (* 2 x)) # -> @[0 2 4 6 8]
Community Examples

setdyn cfunction source

(setdyn key value)

Set a dynamic binding. Returns value.

Community Examples

short-fn macro source

(short-fn arg &opt name)

Shorthand for fn. Arguments are given as $n, where n is the 0-indexed argument of the function. $ is also an alias for the first (index 0) argument. The $& symbol will make the anonymous function variadic if it appears in the body of the function, and can be combined with positional arguments.

EXAMPLES
# a function that doubles its arguments
((fn [n] (+ n n)) 10) # -> 20
((short-fn (+ $ $)) 10) # -> 20

# pipe reader macro offers terser expression
(|(+ $ $) 10) # -> 20

# $0 is also the first (zero-th) argument
(|(+ $0 $0) 10) # -> 20

# handling multiple arguments: $0, $1, ...
(|(string $0 $1) "hi" "ho") # -> "hiho"

# variadic function
(|(apply + $&) 1 2 3) # -> 6

# structs and some other things work too
(|{:a 1}) # -> {:a 1}

Community Examples

signal cfunction source

(signal what x)

Raise a signal with payload x. what can be an integer from 0 through 7 indicating user(0-7), or one of:

  • :ok
  • :error
  • :debug
  • :yield
  • :user(0-7)
  • :interrupt
  • :await
Community Examples

slice cfunction source

(slice x &opt start end)

Extract a sub-range of an indexed data structure or byte sequence.

EXAMPLES
(slice @[1 2 3]) # -> (1 2 3)
(slice @[:a :b :c] 1) # -> (:b :c)
(slice [:a :b :c :d :e] 2 4) # -> (:c :d)
(slice [:a :b :c :d :e] 2 -1) # -> (:c :d :e)
(slice [:a :b :c :d :e] 2 -2) # -> (:c :d)
(slice [:a :b :c :d :e] 2 -4) # -> ()
(slice [:a :b :c :d :e] 2 -10) # -> error: end index -10 out of range [-6,5]
(slice "abcdefg" 0 2) # -> "ab"
(slice @"abcdefg" 0 2) # -> "ab"

Community Examples

slurp function source

(slurp path)

Read all data from a file with name path and then close the file.

Community Examples

some function source

(some pred ind & inds)

Returns nil if (pred item) is false or nil for every item in ind. Otherwise, returns the first truthy result encountered.

Community Examples

sort function source

(sort ind &opt before?)

Sorts ind in-place, and returns it. Uses quick-sort and is not a stable sort. If a before? comparator function is provided, sorts elements using that, otherwise uses <.

Community Examples

sort-by function source

(sort-by f ind)

Sorts ind in-place by calling a function f on each element and comparing the result with <.

Community Examples

sorted function source

(sorted ind &opt before?)

Returns a new sorted array without modifying the old one. If a before? comparator function is provided, sorts elements using that, otherwise uses <.

Community Examples

sorted-by function source

(sorted-by f ind)

Returns a new sorted array that compares elements by invoking a function f on each element and comparing the result with <.

Community Examples

spit function source

(spit path contents &opt mode)

Write contents to a file at path. Can optionally append to the file.

Community Examples

stderr core/file source

The standard error file.

Community Examples

stdin core/file source

The standard input file.

Community Examples

stdout core/file source

The standard output file.

Community Examples

string cfunction source

(string & xs)

Creates a string by concatenating the elements of xs together. If an element is not a byte sequence, it is converted to bytes via describe. Returns the new string.

Community Examples

string? function source

(string? x)

Check if x is a string.

Community Examples

struct cfunction source

(struct & kvs)

Create a new struct from a sequence of key value pairs. kvs is a sequence k1, v1, k2, v2, k3, v3, ... If kvs has an odd number of elements, an error will be thrown. Returns the new struct.

Community Examples

struct? function source

(struct? x)

Check if x a struct.

Community Examples

sum function source

(sum xs)

Returns the sum of xs. If xs is empty, returns 0.

EXAMPLES
(sum []) # -> 0
(sum @[1]) # -> 1
(sum (range 100)) # -> 4950

# Sum over bytes values [0-255] in a string
(sum "hello") # -> 532

# Sum over values in a table or struct
(sum {:a 1 :b 2 :c 4}) # -> 7
Community Examples

symbol cfunction source

(symbol & xs)

Creates a symbol by concatenating the elements of xs together. If an element is not a byte sequence, it is converted to bytes via describe. Returns the new symbol.

Community Examples

symbol? function source

(symbol? x)

Check if x is a symbol.

Community Examples

table cfunction source

(table & kvs)

Creates a new table from a variadic number of keys and values. kvs is a sequence k1, v1, k2, v2, k3, v3, ... If kvs has an odd number of elements, an error will be thrown. Returns the new table.

Community Examples

table? function source

(table? x)

Check if x a table.

Community Examples

tabseq macro source

(tabseq head key-body & value-body)

Similar to loop, but accumulates key value pairs into a table. See loop for details.

Community Examples

take function source

(take n ind)

Take the first n elements of a fiber, indexed or bytes type. Returns a new array, tuple or string, respectively. If n is negative, takes the last n elements instead.

Community Examples

take-until function source

(take-until pred ind)

Same as (take-while (complement pred) ind).

Community Examples

take-while function source

(take-while pred ind)

Given a predicate, take only elements from a fiber, indexed, or bytes type that satisfy the predicate, and abort on first failure. Returns a new array, tuple, or string, respectively.

Community Examples

thaw function source

(thaw ds)

Thaw an object (make it mutable) and do a deep copy, making child value also mutable. Closures, fibers, and abstract types will not be recursively thawed, but all other types will

Community Examples

toggle macro source

(toggle value)

Set a value to its boolean inverse. Same as (set value (not value)).

Community Examples

trace cfunction source

(trace func)

Enable tracing on a function. Returns the function.

Community Examples

tracev macro source

(tracev x)

Print to stderr a value and a description of the form that produced that value. Evaluates to x.

Community Examples

true? function source

(true? x)

Check if x is true.

Community Examples

truthy? function source

(truthy? x)

Check if x is truthy.

Community Examples

try macro source

(try body catch)

Try something and catch errors. body is any expression, and catch should be a form, the first element of which is a tuple. This tuple should contain a binding for errors and an optional binding for the fiber wrapping the body. Returns the result of body if no error, or the result of catch if an error.

Community Examples

tuple cfunction source

(tuple & items)

Creates a new tuple that contains items. Returns the new tuple.

Community Examples

tuple? function source

(tuple? x)

Check if x is a tuple.

Community Examples

type cfunction source

(type x)

Returns the type of x as a keyword. x is one of:

  • :nil

  • :boolean

  • :number

  • :array

  • :tuple

  • :table

  • :struct

  • :string

  • :buffer

  • :symbol

  • :keyword

  • :function

  • :cfunction

  • :fiber

or another keyword for an abstract type.

EXAMPLES
(type nil) # -> :nil
(type true) # -> :boolean
(type false) # -> :boolean
(type 1) # -> :number
(type :key) # -> :keyword
(type (int/s64 "100")) # -> :core/s64
Community Examples

unless macro source

(unless condition & body)

Shorthand for (when (not condition) ;body).

Community Examples

unmarshal cfunction source

(unmarshal buffer &opt lookup)

Unmarshal a value from a buffer. An optional lookup table can be provided to allow for aliases to be resolved. Returns the value unmarshalled from the buffer.

Community Examples

untrace cfunction source

(untrace func)

Disables tracing on a function. Returns the function.

Community Examples

update function source

(update ds key func & args)

For a given key in data structure ds, replace its corresponding value with the result of calling func on that value. If args are provided, they will be passed along to func as well. Returns ds, updated.

Community Examples

update-in function source

(update-in ds ks f & args)

Update a value in a nested data structure ds. Looks into ds via a sequence of keys, and replaces the value found there with f applied to that value. Missing data structures will be replaced with tables. Returns the modified, original data structure.

Community Examples

use macro source

(use & modules)

Similar to import, but imported bindings are not prefixed with a module identifier. Can also import multiple modules in one shot.

Community Examples

values function source

(values x)

Get the values of an associative data structure.

Community Examples

var- macro source

(var- name & more)

Define a private var that will not be exported.

Community Examples

varfn macro source

(varfn name & body)

Create a function that can be rebound. varfn has the same signature as defn, but defines functions in the environment as vars. If a var name already exists in the environment, it is rebound to the new function. Returns a function.

Community Examples

varglobal function source

(varglobal name init)

Dynamically create a global var.

Community Examples

walk function source

(walk f form)

Iterate over the values in ast and apply f to them. Collect the results in a data structure. If ast is not a table, struct, array, or tuple, returns form.

Community Examples

warn-compile function source

(warn-compile msg level where &opt line col)

Default handler for a compile warning.

Community Examples

when macro source

(when condition & body)

Evaluates the body when the condition is true. Otherwise returns nil.

Community Examples

when-let macro source

(when-let bindings & body)

Same as (if-let bindings (do ;body)).

Community Examples

when-with macro source

(when-with [binding ctor dtor] & body)

Similar to with, but if binding is false or nil, returns nil without evaluating the body. Otherwise, the same as with.

Community Examples

with macro source

(with [binding ctor dtor] & body)

Evaluate body with some resource, which will be automatically cleaned up if there is an error in body. binding is bound to the expression ctor, and dtor is a function or callable that is passed the binding. If no destructor (dtor) is given, will call :close on the resource.

EXAMPLES
# Print all of poetry.txt, and close the file when done,
# even when there is an error.
(with [f (file/open "poetry.txt")]
  (print (:read f :all)))
Community Examples

with-dyns macro source

(with-dyns bindings & body)

Run a block of code in a new fiber that has some dynamic bindings set. The fiber will not mask errors or signals, but the dynamic bindings will be properly unset, as dynamic bindings are fiber-local.

Community Examples

with-env macro source

(with-env env & body)

Run a block of code with a given environment table

Community Examples

with-syms macro source

(with-syms syms & body)

Evaluates body with each symbol in syms bound to a generated, unique symbol.

Community Examples

with-vars macro source

(with-vars vars & body)

Evaluates body with each var in vars temporarily bound. Similar signature to let, but each binding must be a var.

Community Examples

xprin cfunction source

(xprin to & xs)

Print to a file or other value explicitly (no dynamic bindings). The value to print to is the first argument, and is otherwise the same as prin. Returns nil.

Community Examples

xprinf cfunction source

(xprinf to fmt & xs)

Like prinf but prints to an explicit file or value to. Returns nil.

Community Examples

xprint cfunction source

(xprint to & xs)

Print to a file or other value explicitly (no dynamic bindings) with a trailing newline character. The value to print to is the first argument, and is otherwise the same as print. Returns nil.

Community Examples

xprintf cfunction source

(xprintf to fmt & xs)

Like printf but prints to an explicit file or value to. Returns nil.

Community Examples

yield function

(yield &opt x)

Yield a value to a parent fiber. When a fiber yields, its execution is paused until another thread resumes it. The fiber will then resume, and the last yield call will return the value that was passed to resume.

Community Examples

zero? function source

(zero? x)

Check if x is zero.

Community Examples

zipcoll function source

(zipcoll ks vs)

Creates a table from two arrays/tuples. Returns a new table.

Community Examples