Lispium Function Reference

v0.9.0 · every builtin and special form · try it in the playground · GitHub
0 entries
(step expr)
Evaluates expr while printing every reduction with its result (capped at 200 steps).
(step (fact 3))
(begin e1 e2 ...)
Evaluates expressions in order, returning the last.
(begin (print 1) (+ 2 3)) => 5
(cond (test result...) ... (else result...))
Multi-branch conditional; else always matches.
(cond ((< x 0) "neg") (else "non-neg"))
(quote expr) or 'expr
Returns expr unevaluated (data, not code).
'(+ 1 2) => (+ 1 2)
(quasiquote expr) or `expr
Like quote, but (unquote x) / ,x evaluates.
`(+ 1 ,(* 2 3)) => (+ 1 6)
(unquote expr) or ,expr
Evaluates expr inside a quasiquote template.
(defmacro (name params...) template)
Defines a macro: params bind to unevaluated arguments, the template builds code.
(defmacro (unless c a b) `(if ,c ,b ,a))
(try expr fallback)
Evaluates expr; on error evaluates fallback instead.
(try (/ 1 0) "fallback") => "fallback"
(time expr)
Evaluates expr and prints the wall-clock time taken.
(trace fn-name)
Toggles call/return tracing for a user-defined function.
(print a b ...)
Writes arguments separated by spaces, then a newline; strings print raw.
(print "x =" 42)
(read)
Reads one line from input and parses it as an expression; eof at end of input.
(define x (read))
(load "file.lspm")
Evaluates a file in the current environment; returns the statement count.
(args)
Command-line arguments after the script path, as a list of strings.
(exit) or (exit code)
Terminates the process with an optional status code.
(random) or (random n)
Uniform random float in [0,1), or integer in [0,n).
(random 6) => 0..5
(random-seed n)
Seeds the PRNG for reproducible sequences.
(sort lst)
Ascending sort of numbers, rationals, and strings.
(sort (list 3 1 2)) => (list 1 2 3)
(assoc key alist)
First (key value) pair matching key in a list of pairs, else 0.
(assoc 2 (list (list 1 "a") (list 2 "b"))) => (list 2 "b")
(unit name)
One SI or derived unit as a dimension-carrying quantity (m kg s A K mol cd, km cm mm g min h Hz N Pa J W C V).
(/ (* 100 (unit km)) (unit h)) => 27.78 m/s
(concat s1 s2 ...)
Concatenates strings; non-string arguments are rendered.
(concat "x = " (+ 1 2)) => "x = 3"
(substring s start end)
Characters [start, end) of a string.
(substring "hello world" 0 5) => "hello"
(string->number s)
Parses a number (or p/q rational) from a string.
(string->number "22/7") => 22/7
(number->string x)
Renders any expression to its printed form as a string.
(number->string 1/3) => "1/3"
(split s sep)
Splits a string on a separator, returning a list of strings.
(split "a,b" ",") => (list "a" "b")
(numer x)
Numerator of an exact rational (integers are n/1).
(numer 22/7) => 22
(denom x)
Denominator of an exact rational (integers are n/1).
(denom 22/7) => 7
(number? x)
True for numbers and exact rationals.
(integer? x)
True for integer-valued numbers.
(rational? x)
True for exact rationals and integers.
(symbol? x)
True for symbols.
(string? x)
True for strings.
(list? x)
True for lists.
(lambda? x)
True for functions.
(null? x)
True for the empty list.
(complex? x)
True for complex numbers.
(apply f arg-list)
Calls f with the elements of arg-list as arguments.
(apply + '(1 2 3)) => 6
(error "message" ...)
Raises a user error, printing the message.
(assert cond ["message"])
Errors when cond is false; the test runner counts failures.
(assert (= (+ 1 1) 2) "arithmetic works")
(define name value) or (define (name params...) body)
Binds a value, or defines a function (captures free variables by value).
(define (square x) (* x x))
(lambda (params...) body)
Creates an anonymous function (closure).
((lambda (x) (* x x)) 5) => 25
(let ((var val) ...) body)
Local bindings with lexical scope.
(let ((a 3) (b 4)) (+ a b)) => 7
(letrec ((var val) ...) body)
Recursive local bindings (functions can call themselves).
(letrec ((f (lambda (n) (if (= n 0) 1 (* n (f (- n 1))))))) (f 5)) => 120
(if condition then-expr [else-expr])
Conditional; stays symbolic when the condition is undecidable.
(if (> 2 1) "yes" "no")
(sum var start end body)
Summation of body for var from start to end.
(sum i 1 5 (* i i)) => 55
(product var start end body)
Product of body for var from start to end.
(product i 1 5 i) => 120
(+ a b c ...)
Addition (variadic; complex, vectors, matrices).
(- a b ...) or (- a)
Subtraction; unary form negates.
(* a b c ...)
Multiplication (variadic; complex, scalar·vector/matrix).
(/ a b) or (/ a)
Division; unary form is the reciprocal.
(^ base exp)
Exponentiation (complex base; negative base with fractional exponent gives the principal complex value).
(^ base exp)
Exponentiation (complex base; negative base with fractional exponent gives the principal complex value).
(abs x)
Absolute value (magnitude for complex).
(floor x)
Round down.
(ceil x)
Round up.
(round x)
Round to nearest.
(sign x)
-1, 0, or 1.
(simplify expr)
Algebraic simplification.
(simplify (+ x x)) => (* 2 x)
(evalf expr) or (N expr)
Numeric evaluation of constants (pi, e).
(evalf expr) or (N expr)
Numeric evaluation of constants (pi, e).
(diff expr var) or (diff expr var n)
Differentiation (nth derivative).
(diff (^ x 3) x) => (* 3 (^ x 2))
(integrate expr var) or (integrate expr var a b)
Integration (indefinite or definite).
(expand expr)
Expand products.
(expand (^ (+ x 1) 2)) => (+ (^ x 2) (* 2 x) 1)
(substitute expr var value)
Variable substitution.
(substitute (+ x y) x 3) => (+ 3 y)
(taylor expr var point order)
Taylor series expansion.
(taylor (exp x) x 0 4) => (+ 1 x (/ (^ x 2) 2) ...)
(solve expr var) or (solve (= left right) var)
Solve equation (linear/quadratic).
(solve (+ (^ x 2) (* -4 1)) x) => (solutions 2 -2)
(factor expr var)
Factor polynomial.
(factor (+ (^ x 2) (* -1 1)) x) => (* (- x 1) (+ x 1))
(partial-fractions expr var)
Partial fraction decomposition.
(collect expr var)
Collect like terms.
(collect (+ (* 2 x) (* 3 x) 5) x) => (+ (* 5 x) 5)
(limit expr var point)
Limit with L'Hôpital's rule.
(limit (/ (sin x) x) x 0) => 1
(sin x)
Sine.
(cos x)
Cosine.
(tan x)
Tangent.
(asin x)
Arc sine.
(acos x)
Arc cosine.
(atan x)
Arc tangent.
(atan2 y x)
Two-argument arc tangent.
(sinh x)
Hyperbolic sine.
(cosh x)
Hyperbolic cosine.
(tanh x)
Hyperbolic tangent.
(asinh x)
Inverse hyperbolic sine.
(acosh x)
Inverse hyperbolic cosine.
(atanh x)
Inverse hyperbolic tangent.
(exp x)
Exponential (e^x).
(ln x)
Natural logarithm.
(log x) or (log x base)
Logarithm of x (default base 10).
(log 100 10) => 2
(sqrt x)
Square root; (sqrt -4) => (complex 0 2).
(complex re im)
Create complex number.
(complex 3 4) => 3 + 4i
(real z)
Real part.
(imag z)
Imaginary part.
(conj z)
Complex conjugate.
(magnitude z)
Absolute value.
(arg z)
Argument (angle).
(rule pattern replacement)
Define rewrite rule.
(rule (double ?x) (* 2 ?x))
(rewrite expr)
Apply all defined rules.
(matrix (r1) (r2) ...)
Create matrix.
(matrix (1 2) (3 4)) => 2x2 matrix
(det M)
Determinant.
(transpose M)
Transpose.
(trace M)
Trace (sum of diagonal).
(matmul A B)
Matrix multiplication.
(inv M)
Matrix inverse.
(eigenvalues M)
Eigenvalues (2x2 only).
(eigenvectors M)
Eigenvectors (2x2 only).
(linsolve A b)
Solve linear system Ax=b.
(lu M)
LU decomposition.
(charpoly M var)
Characteristic polynomial.
(vector x y z ...)
Create vector.
(vector 1 2 3) => ⟨1, 2, 3⟩
(dot v1 v2)
Dot product.
(cross v1 v2)
Cross product (3D only).
(norm v)
Euclidean norm.
(gradient f vars)
Gradient of scalar field.
(gradient f vars)
Gradient of scalar field.
(gradient (+ (^ x 2) (^ y 2)) (vector x y))
(divergence F vars)
Divergence of vector field.
(curl F vars)
Curl of vector field (3D).
(laplacian f vars)
Laplacian of scalar field.
(and a b ...)
Logical AND (variadic).
(or a b ...)
Logical OR (variadic).
(not a)
Logical NOT.
(xor a b)
Exclusive OR.
(implies a b)
Logical implication.
(mod a b)
Modulo.
(gcd a b)
Greatest common divisor.
(lcm a b)
Least common multiple.
(modpow base exp mod)
Modular exponentiation.
(prime? n)
Primality test.
(factorize n)
Prime factorization.
(totient n)
Euler's totient function.
(extgcd a b)
Extended GCD (Bezout coefficients).
(crt (vector r1 r2 ...) (vector m1 m2 ...))
Chinese Remainder Theorem.
(factorial n) or (! n)
Factorial.
(factorial n) or (! n)
Factorial.
(binomial n k)
Binomial coefficient.
(binomial n k)
Binomial coefficient.
(permutations n r)
P(n,r); errors when r > n.
(combinations n r)
C(n,r).
(mean x1 x2 ...)
Arithmetic mean.
(variance x1 x2 ...)
Population variance.
(stddev x1 x2 ...)
Standard deviation.
(median x1 x2 ...)
Median.
(min x1 x2 ...)
Minimum.
(max x1 x2 ...)
Maximum.
(coeffs a b c ...)
Create coefficient list.
(polydiv (coeffs ...) (coeffs ...) var)
Polynomial division (coefficient lists).
(polygcd p1 p2)
Polynomial GCD.
(polylcm p1 p2)
Polynomial LCM.
(roots expr var)
Find polynomial roots.
(discriminant expr var)
Discriminant.
(assume var property)
Set assumption.
(is? var property)
Check assumption.
(= a b ...)
Equality (variadic; returns 1 or 0).
(< a b ...)
Chained less-than; symbolic args stay inert.
(> a b ...)
Chained greater-than; symbolic args stay inert.
(gamma x)
Gamma function Γ(x).
(beta a b)
Beta function B(a,b).
(erf x)
Error function.
(erfc x)
Complementary error function.
(besselj n x)
Bessel function of first kind J_n(x).
(bessely n x)
Bessel function of second kind Y_n(x).
(digamma x)
Digamma function ψ(x).
(dsolve (= (diff y x) rhs) y x)
Solve first-order ODE (special form: the equation is not pre-evaluated).
(fourier expr x n)
Fourier series: returns (fourier-series a0 ((a1 b1) ... (an bn))) with numerically computed (noise-snapped) coefficients.
(laplace expr t s)
Laplace transform.
(inv-laplace expr s t)
Inverse Laplace transform.
(tensor data)
Create tensor.
(tensor-rank T)
Get tensor rank.
(tensor-contract T i j)
Contract indices.
(tensor-product T1 T2)
Outer product.
(lagrange (list (vector x y) ...) var)
Lagrange interpolation.
(newton-interp (list (vector x y) ...) var)
Newton interpolation.
(newton-raphson expr var x0 tol)
Newton-Raphson method.
(bisection expr var a b tol)
Bisection method.
(to-cf x)
Convert to continued fraction.
(from-cf cf)
Convert from continued fraction.
(cf-convergent cf n)
Get nth convergent.
(cf-rational p q)
CF from rational p/q.
(car lst)
First element.
(cdr lst)
Rest of list.
(cons x lst)
Prepend element.
(list a b c ...)
Create list.
(length lst)
List length.
(nth lst n)
Get nth element.
(map fn lst)
Map function over list.
(map (lambda (x) (* x 2)) (list 1 2 3))
(filter fn lst)
Filter list by predicate.
(reduce fn init lst)
Reduce list.
(append lst1 lst2)
Concatenate lists.
(reverse lst)
Reverse list.
(range n) or (range start end) or (range start end step)
Generate range.
(memoize expr)
Cache expression result.
(memo-clear)
Clear memoization cache.
(memo-stats)
Get cache size.
(plot-ascii expr xmin xmax) or (plot-ascii expr xmin xmax height width)
ASCII plot.
(plot-svg expr xmin xmax) or (plot-svg expr xmin xmax height width)
SVG plot.
(plot-points points)
Plot discrete points.
(diff-steps expr var)
Differentiation with steps.
(integrate-steps expr var)
Integration with steps.
(simplify-steps expr)
Simplification with steps.
(solve-steps expr var)
Equation solving with steps.
(quat w x y z)
Create quaternion w + xi + yj + zk.
(quat+ q1 q2)
Quaternion addition.
(quat* q1 q2)
Hamilton product.
(quat-conj q)
Conjugate.
(quat-norm q)
Norm (magnitude).
(quat-inv q)
Multiplicative inverse.
(quat-scalar q)
Scalar part (w).
(quat-vector q)
Vector part (x, y, z).
(gf value prime)
Create element in GF(p); p must be prime.
(gf+ a b)
Addition in GF(p).
(gf- a b)
Subtraction in GF(p).
(gf* a b)
Multiplication in GF(p).
(gf/ a b)
Division in GF(p).
(gf^ a n)
Exponentiation in GF(p).
(gf-inv a)
Multiplicative inverse.
(gf-neg a)
Negation.
(latex expr)
Convert to LaTeX string.