Builtin functions

	There is a large number of built-in functions.	Many of the
	functions work on several types of arguments, whereas some only
	work for the correct types (e.g., numbers or strings).	In the
	following description, this is indicated by whether or not the
	description refers to values or numbers.  This display is generated
	by the 'show builtin' command.

## Copyright (C) 1999  Landon Curt Noll
##
## Calc is open software; you can redistribute it and/or modify it under
## the terms of the version 2.1 of the GNU Lesser General Public License
## as published by the Free Software Foundation.
##
## Calc is distributed in the hope that it will be useful, but WITHOUT
## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
## or FITNESS FOR A PARTICULAR PURPOSE.	 See the GNU Lesser General
## Public License for more details.
##
## A copy of version 2.1 of the GNU Lesser General Public License is
## distributed with calc under the filename COPYING-LGPL.  You should have
## received a copy with calc; if not, write to Free Software Foundation, Inc.
## 59 Temple Place, Suite 330, Boston, MA  02111-1307, USA.
##
## @(#) $Revision: 29.2 $
## @(#) $Id: builtin.top,v 29.2 2000/06/07 14:02:33 chongo Exp $
## @(#) $Source: /usr/local/src/cmd/calc/help/RCS/builtin.top,v $
##
## Under source code control:	1995/07/10 01:17:53
## File existed as early as:	1995
##
## chongo <was here> /\oo/\	http://www.isthe.com/chongo/
## Share and enjoy!  :-)	http://www.isthe.com/chongo/tech/comp/calc/

	Name	Args	Description

	abs       1-2   absolute value within accuracy b
	access    1-2   determine accessibility of file a for mode b
	acos      1-2   arccosine of a within accuracy b
	acosh     1-2   inverse hyperbolic cosine of a within accuracy b
	acot      1-2   arccotangent of a within accuracy b
	acoth     1-2   inverse hyperbolic cotangent of a within accuracy b
	acsc      1-2   arccosecant of a within accuracy b
	acsch     1-2   inverse csch of a within accuracy b
	agd       1-2   inverse gudermannian function
	append    1+    append values to end of list
	appr      1-3   approximate a by multiple of b using rounding c
	arg       1-2   argument (the angle) of complex number
	argv      0-1   calc argc or argv string
	asec      1-2   arcsecant of a within accuracy b
	asech     1-2   inverse hyperbolic secant of a within accuracy b
	asin      1-2   arcsine of a within accuracy b
	asinh     1-2   inverse hyperbolic sine of a within accuracy b
	assoc     0     create new association array
	atan      1-2   arctangent of a within accuracy b
	atan2     2-3   angle to point (b,a) within accuracy c
	atanh     1-2   inverse hyperbolic tangent of a within accuracy b
	avg       0+    arithmetic mean of values
	base      0-1   set default output base
	base2     0-1   set default secondary output base
	bernoulli 1     Bernoulli number for index a
	bit       2     whether bit b in value a is set
	blk       0-3   block with or without name, octet number, chunksize
	blkcpy    2-5   copy value to/from a block: blkcpy(d,s,len,di,si)
	blkfree   1     free all storage from a named block
	blocks    0-1   named block with specified index, or null value
	bround    1-3   round value a to b number of binary places
	btrunc    1-2   truncate a to b number of binary places
	calc_tty  0     set tty for interactivity
	calclevel 0     current calculation level
	calcpath  0     current CALCPATH search path value
	catalan   1     catalan number for index a
	ceil      1     smallest integer greater than or equal to number
	cfappr    1-3   approximate a within accuracy b using
				continued fractions
	cfsim     1-2   simplify number using continued fractions
	char      1     character corresponding to integer value
	cmdbuf    0     command buffer
	cmp       2     compare values returning -1, 0, or 1
	comb      2     combinatorial number a!/b!(a-b)!
	config    1-2   set or read configuration value
	conj      1     complex conjugate of value
	copy      2-5   copy value to/from a block: copy(s,d,len,si,di)
	cos       1-2   cosine of value a within accuracy b
	cosh      1-2   hyperbolic cosine of a within accuracy b
	cot       1-2   cotangent of a within accuracy b
	coth      1-2   hyperbolic cotangent of a within accuracy b
	count     2     count listr/matrix elements satisfying some condition
	cp        2     cross product of two vectors
	csc       1-2   cosecant of a within accuracy b
	csch      1-2   hyperbolic cosecant of a within accuracy b
	ctime     0     date and time as string
	custom    0+    custom builtin function interface
	delete    2     delete element from list a at position b
	den       1     denominator of fraction
	det       1     determinant of matrix
	digit     2-3   digit at specified decimal place of number
	digits    1-2   number of digits in base b representation of a
	display   0-1   number of decimal digits for displaying numbers
	dp        2     dot product of two vectors
	epsilon   0-1   set or read allowed error for real calculations
	errcount  0-1   set or read error count
	errmax    0-1   set or read maximum for error count
	errno     0-1   set or read calc_errno
	error     0-1   generate error value
	estr      1     exact text string representation of value
	euler     1     Euler number
	eval      1     evaluate expression from string to value
	exp       1-2   exponential of value a within accuracy b
	factor    1-3   lowest prime factor < b of a, return c if error
	fcnt      2     count of times one number divides another
	fib       1     Fibonacci number F(n)
	forall    2     do function for all elements of list or matrix
	frem      2     number with all occurrences of factor removed
	fact      1     factorial
	fclose    0+    close file
	feof      1     whether EOF reached for file
	ferror    1     whether error occurred for file
	fflush    0+    flush output to file(s)
	fgetc     1     read next char from file
	fgetfield 1     read next white-space delimited field from file
	fgetfile  1     read to end of file
	fgetline  1     read next line from file, newline removed
	fgets     1     read next line from file, newline is kept
	fgetstr   1     read next null-terminated string from file, null
				character is kept
	files     0-1   return opened file or max number of opened files
	floor     1     greatest integer less than or equal to number
	fopen     2     open file name a in mode b
	fpathopen 2-3   open file name a in mode b, search for a along
				CALCPATH or path c
	fprintf   2+    print formatted output to opened file
	fputc     2     write a character to a file
	fputs     2+    write one or more strings to a file
	fputstr   2+    write one or more null-terminated strings to a file
	free      0+    free listed or all global variables
	freebernoulli 0     free stored Bernoulli numbers
	freeeuler 0     free stored Euler numbers
	freeglobals 0     free all global and visible static variables
	freeredc  0     free redc data cache
	freestatics 0     free all unscoped static variables
	freopen   2-3   reopen a file stream to a named file
	fscan     2+    scan a file for assignments to one or
				more variables
	fscanf    2+    formatted scan of a file for assignment to one
				or more variables
	fseek     2-3   seek to position b (offset from c) in file a
	fsize     1     return the size of the file
	ftell     1     return the file position
	frac      1     fractional part of value
	gcd       1+    greatest common divisor
	gcdrem    2     a divided repeatedly by gcd with b
	gd        1-2   gudermannian function
	getenv    1     value of environment variable (or NULL)
	hash      1+    return non-negative hash value for one or
				more values
	head      2     return list of specified number at head of a list
	highbit   1     high bit number in base 2 representation
	hmean     0+    harmonic mean of values
	hnrmod    4     v mod h*2^n+r, h>0, n>0, r = -1, 0 or 1
	hypot     2-3   hypotenuse of right triangle within accuracy c
	ilog      2     integral log of a to integral base b
	ilog10    1     integral log of a number base 10
	ilog2     1     integral log of a number base 2
	im        1     imaginary part of complex number
	indices   2     indices of a specified assoc or mat value
	inputlevel 0     current input depth
	insert    2+    insert values c ... into list a at position b
	int       1     integer part of value
	inverse   1     multiplicative inverse of value
	iroot     2     integer b'th root of a
	isassoc   1     whether a value is an association
	isatty    1     whether a file is a tty
	isblk     1     whether a value is a block
	isconfig  1     whether a value is a config state
	isdefined 1     whether a string names a function
	iserror   1     where a value is an error
	iseven    1     whether a value is an even integer
	isfile    1     whether a value is a file
	ishash    1     whether a value is a hash state
	isident   1     returns 1 if identity matrix
	isint     1     whether a value is an integer
	islist    1     whether a value is a list
	ismat     1     whether a value is a matrix
	ismult    2     whether a is a multiple of b
	isnull    1     whether a value is the null value
	isnum     1     whether a value is a number
	isobj     1     whether a value is an object
	isobjtype 1     whether a string names an object type
	isodd     1     whether a value is an odd integer
	isoctet   1     whether a value is an octet
	isprime   1-2   whether a is a small prime, return b if error
	isptr     1     whether a value is a pointer
	isqrt     1     integer part of square root
	isrand    1     whether a value is a additive 55 state
	israndom  1     whether a value is a Blum state
	isreal    1     whether a value is a real number
	isrel     2     whether two numbers are relatively prime
	isstr     1     whether a value is a string
	issimple  1     whether value is a simple type
	issq      1     whether or not number is a square
	istype    2     whether the type of a is same as the type of b
	jacobi    2     -1 => a is not quadratic residue mod b
				1 => b is composite, or a is quad residue of b
	join      1+    join one or more lists into one list
	lcm       1+    least common multiple
	lcmfact   1     lcm of all integers up till number
	lfactor   2     lowest prime factor of a in first b primes
	links     1     links to number or string value
	list      0+    create list of specified values
	ln        1-2   natural logarithm of value a within accuracy b
	log       1-2   base 10 logarithm of value a within accuracy b
	lowbit    1     low bit number in base 2 representation
	ltol      1-2   leg-to-leg of unit right triangle (sqrt(1 - a^2))
	makelist  1     create a list with a null elements
	matdim    1     number of dimensions of matrix
	matfill   2-3   fill matrix with value b (value c on diagonal)
	matmax    2     maximum index of matrix a dim b
	matmin    2     minimum index of matrix a dim b
	matsum    1     sum the numeric values in a matrix
	mattrace  1     return the trace of a square matrix
	mattrans  1     transpose of matrix
	max       0+    maximum value
	md5       0+    MD5 Hash Algorithm
	memsize   1     number of octets used by the value, including overhead
	meq       3     whether a and b are equal modulo c
	min       0+    minimum value
	minv      2     inverse of a modulo b
	mmin      2     a mod b value with smallest abs value
	mne       3     whether a and b are not equal modulo c
	mod       2-3   residue of a modulo b, rounding type c
	modify    2     modify elements of a list or matrix
	name      1     name assigned to block or file
	near      2-3   sign of (abs(a-b) - c)
	newerror  0-1   create new error type with message a
	nextcand  1-5   smallest value == d mod e > a, ptest(a,b,c) true
	nextprime 1-2   return next small prime, return b if err
	norm      1     norm of a value (square of absolute value)
	null      0+    null value
	num       1     numerator of fraction
	ord       1     integer corresponding to character value
	param     1     value of parameter n (or parameter count if n
				is zero)
	perm      2     permutation number a!/(a-b)!
	prevcand  1-5   largest value == d mod e < a, ptest(a,b,c) true
	prevprime 1-2   return previous small prime, return b if err
	pfact     1     product of primes up till number
	pi        0-1   value of pi accurate to within epsilon
	pix       1-2   number of primes <= a < 2^32, return b if error
	places    1-2   places after "decimal" point (-1 if infinite)
	pmod      3     mod of a power (a ^ b (mod c))
	polar     2-3   complex value of polar coordinate (a * exp(b*1i))
	poly      1+    evaluates a polynomial given its coefficients
				or coefficient-list
	pop       1     pop value from front of list
	popcnt    1-2   number of bits in a that match b (or 1)
	power     2-3   value a raised to the power b within accuracy c
	protect   1-3   read or set protection level for variable
	ptest     1-3   probabilistic primality test
	printf    1+    print formatted output to stdout
	prompt    1     prompt for input line using value a
	push      1+    push values onto front of list
	putenv    1-2   define an environment variable
	quo       2-3   integer quotient of a by b, rounding type c
	quomod    4-5   set c and d to quotient and remainder of a
				divided by b
	rand      0-2   additive 55 random number [0,2^64), [0,a), or [a,b)
	randbit   0-1   additive 55 random number [0,2^a)
	random    0-2   Blum-Blum-Shub random number [0,2^64), [0,a), or [a,b)
	randombit 0-1   Blum-Blum-Sub random number [0,2^a)
	randperm  1     random permutation of a list or matrix
	rcin      2     convert normal number a to REDC number mod b
	rcmul     3     multiply REDC numbers a and b mod c
	rcout     2     convert REDC number a mod b to normal number
	rcpow     3     raise REDC number a to power b mod c
	rcsq      2     square REDC number a mod b
	re        1     real part of complex number
	remove    1     remove value from end of list
	reverse   1     reverse a copy of a matrix or list
	rewind    0+    rewind file(s)
	rm        1+    remove file(s), -f turns off no-such-file errors
	root      2-3   value a taken to the b'th root within accuracy c
	round     1-3   round value a to b number of decimal places
	rsearch   2-4   reverse search matrix or list for value b
				starting at index c
	runtime   0     user and kernel mode cpu time in seconds
	saveval   1     set flag for saving values
	scale     2     scale value up or down by a power of two
	scan      1+    scan standard input for assignment to one
				or more variables
	scanf     2+    formatted scan of standard input for assignment
				to variables
	search    2-4   search matrix or list for value b starting
				at index c
	sec       1-2   sec of a within accuracy b
	sech      1-2   hyperbolic secant of a within accuracy b
	seed      0     return a 64 bit seed for a psuedo-random generator
	segment   2-3   specified segment of specified list
	select    2     form sublist of selected elements from list
	setbit    2-3   set specified bit in string
	sgn       1     sign of value (-1, 0, 1)
	sha       0+    old Secure Hash Algorithm (SHS FIPS Pub 180)
	sha1      0+    Secure Hash Algorithm (SHS-1 FIPS Pub 180-1)
	sin       1-2   sine of value a within accuracy b
	sinh      1-2   hyperbolic sine of a within accuracy b
	size      1     total number of elements in value
	sizeof    1     number of octets used to hold the value
	sleep     0-1   suspend operation for a seconds
	sort      1     sort a copy of a matrix or list
	sqrt      1-3   square root of value a within accuracy b
	srand     0-1   seed the rand() function
	srandom   0-4   seed the random() function
	ssq       1+    sum of squares of values
	stoponerror 0-1   assign value to stoponerror flag
	str       1     simple value converted to string
	strcat    1+    concatenate strings together
	strcmp    2     compare two strings
	strcpy    2     copy string to string
	strerror  0-1   string describing error type
	strlen    1     length of string
	strncmp   3     compare strings a, b to c characters
	strncpy   3     copy up to c characters from string to string
	strpos    2     index of first occurrence of b in a
	strprintf 1+    return formatted output as a string
	strscan   2+    scan a string for assignments to one or more variables
	strscanf  2+    formatted scan of string for assignments to variables
	substr    3     substring of a from position b for c chars
	sum       0+    sum of list or object sums and/or other terms
	swap      2     swap values of variables a and b (can be dangerous)
	system    1     call Unix command
	systime   0     kernel mode cpu time in seconds
	tail      2     retain list of specified number at tail of list
	tan       1-2   tangent of a within accuracy b
	tanh      1-2   hyperbolic tangent of a within accuracy b
	test      1     test that value is nonzero
	time      0     number of seconds since 00:00:00 1 Jan 1970 UTC
	trunc     1-2   truncate a to b number of decimal places
	ungetc    2     unget char read from file
	usertime  0     user mode cpu time in seconds
	version   0     calc version string
	xor       1+    logical xor


	The config function sets or reads the value of a configuration
	parameter.  The first argument is a string which names the parameter
	to be set or read.  If only one argument is given, then the current
	value of the named parameter is returned.  If two arguments are given,
	then the named parameter is set to the value of the second argument,
	and the old value of the parameter is returned.	 Therefore you can
	change a parameter and restore its old value later.  The possible
	parameters are explained in the next section.

	The scale function multiplies or divides a number by a power of 2.
	This is used for fractional calculations, unlike the << and >>
	operators, which are only defined for integers.	 For example,
	scale(6, -3) is 3/4.

	The quomod function is used to obtain both the quotient and remainder
	of a division in one operation.	 The first two arguments a and b are
	the numbers to be divided.  The last two arguments c and d are two
	variables which will be assigned the quotient and remainder.  For
	nonnegative arguments, the results are equivalent to computing a//b
	and a%b.  If a is negative and the remainder is nonzero, then the
	quotient will be one less than a//b.  This makes the following three
	properties always hold:	 The quotient c is always an integer.  The
	remainder d is always 0 <= d < b.  The equation a = b * c + d always
	holds.	This function returns 0 if there is no remainder, and 1 if
	there is a remainder.  For examples, quomod(10, 3, x, y) sets x to 3,
	y to 1, and returns the value 1, and quomod(-4, 3.14159, x, y) sets x
	to -2, y to 2.28318, and returns the value 1.

	The eval function accepts a string argument and evaluates the
	expression represented by the string and returns its value.
	The expression can include function calls and variable references.
	For example, eval("fact(3) + 7") returns 13.  When combined with
	the prompt function, this allows the calculator to read values from
	the user.  For example, x=eval(prompt("Number: ")) sets x to the
	value input by the user.

	The digit and bit functions return individual digits of a number,
	either in base 10 or in base 2, where the lowest digit of a number
	is at digit position 0.	 For example, digit(5678, 3) is 5, and
	bit(0b1000100, 2) is 1.	 Negative digit positions indicate places
	to the right of the decimal or binary point, so that for example,
	digit(3.456, -1) is 4.

	The ptest builtin is a primality testing function.  The
	1st argument is the suspected prime to be tested.  The
	absolute value of the 2nd argument is an iteration count.

	If ptest is called with only 2 args, the 3rd argument is
	assumed to be 0.  If ptest is called with only 1 arg, the
	2nd argument is assumed to be 1.  Thus, the following
	calls are equivalent:

		ptest(a)
		ptest(a,1)
		ptest(a,1,0)

	Normally ptest performs a some checks to determine if the
	value is divisable by some trivial prime.  If the 2nd
	argument is < 0, then the trivial check is omitted.

	For example, ptest(a,10) performs the same work as:

		ptest(a,-3)	(7 tests without trivial check)
		ptest(a,-7,3)	(3 more tests without the trivial check)

	The ptest function returns 0 if the number is definitely not
	prime, and 1 is the number is probably prime.  The chance
	of a number which is probably prime being actually composite
	is less than 1/4 raised to the power of the iteration count.
	For example, for a random number p, ptest(p, 10) incorrectly
	returns 1 less than once in every million numbers, and you
	will probably never find a number where ptest(p, 20) gives
	the wrong answer.

	The first 3 args of nextcand and prevcand functions are the same
	arguments as ptest.  But unlike ptest, nextcand and prevcand return
	the next and previous values for which ptest is true.

	For example, nextcand(2^1000) returns 2^1000+297 because
	2^1000+297 is the smallest value x > 2^1000 for which
	ptest(x,1) is true.  And for example, prevcand(2^31-1,10,5)
	returns 2147483629 (2^31-19) because 2^31-19 is the largest
	value y < 2^31-1 for which ptest(y,10,5) is true.

	The nextcand and prevcand functions also have a 5 argument form:

		nextcand(num, count, skip, modval, modulus)
		prevcand(num, count, skip, modval, modulus)

	return the smallest (or largest) value ans > num (or < num) that
	is also == modval % modulus for which ptest(ans,count,skip) is true.

	The builtins nextprime(x) and prevprime(x) return the
	next and previous primes with respect to x respectively.
	As of this release, x must be < 2^32.  With one argument, they
	will return an error if x is out of range.  With two arguments,
	they will not generate an error but instead will return y.

	The builtin function pix(x) returns the number of primes <= x.
	As of this release, x must be < 2^32.  With one argument, pix(x)
	will return an error if x is out of range.  With two arguments,
	pix(x,y) will not generate an error but instead will return y.

	The builtin function factor may be used to search for the
	smallest factor of a given number.  The call factor(x,y)
	will attempt to find the smallest factor of x < min(x,y).
	As of this release, y must be < 2^32.  If y is omitted, y
	is assumed to be 2^32-1.

	If x < 0, factor(x,y) will return -1.  If no factor <
	min(x,y) is found, factor(x,y) will return 1.  In all other
	cases, factor(x,y) will return the smallest prime factor
	of x.  Note except for the case when abs(x) == 1, factor(x,y)
	will not return x.

	If factor is called with y that is too large, or if x or y
	is not an integer, calc will report an error.  If a 3rd argument
	is given, factor will return that value instead.  For example,
	factor(1/2,b,c) will return c instead of issuing an error.

	The builtin lfactor(x,y) searches a number of primes instead
	of below a limit.  As of this release, y must be <= 203280221
	(y <= pix(2^32-1)).  In all other cases, lfactor is operates
	in the same way as factor.

	If lfactor is called with y that is too large, or if x or y
	is not an integer, calc will report an error.  If a 3rd argument
	is given, lfactor will return that value instead.  For example,
	lfactor(1/2,b,c) will return c instead of issuing an error.

	The lfactor function is slower than factor.  If possible factor
	should be used instead of lfactor.

	The builtin isprime(x) will attempt to determine if x is prime.
	As of this release, x must be < 2^32.  With one argument, isprime(x)
	will return an error if x is out of range.  With two arguments,
	isprime(x,y) will not generate an error but instead will return y.

	The functions rcin, rcmul, rcout, rcpow, and rcsq are used to
	perform modular arithmetic calculations for large odd numbers
	faster than the usual methods.	To do this, you first use the
	rcin function to convert all input values into numbers which are
	in a format called REDC format.	 Then you use rcmul, rcsq, and
	rcpow to multiply such numbers together to produce results also
	in REDC format.	 Finally, you use rcout to convert a number in
	REDC format back to a normal number.  The addition, subtraction,
	negation, and equality comparison between REDC numbers are done
	using the normal modular methods.  For example, to calculate the
	value 13 * 17 + 1 (mod 11), you could use:

		p = 11;
		t1 = rcin(13, p);
		t2 = rcin(17, p);
		t3 = rcin(1, p);
		t4 = rcmul(t1, t2, p);
		t5 = (t4 + t3) % p;
		answer = rcout(t5, p);

	The swap function exchanges the values of two variables without
	performing copies.  For example, after:

		x = 17;
		y = 19;
		swap(x, y);

	then x is 19 and y is 17.  This function should not be used to
	swap a value which is contained within another one.  If this is
	done, then some memory will be lost.  For example, the following
	should not be done:

		mat x[5];
		swap(x, x[0]);

	The hash function returns a relatively small non-negative integer
	for one or more input values.  The hash values should not be used
	across runs of the calculator, since the algorithms used to generate
	the hash value may change with different versions of the calculator.

	The base function allows one to specify how numbers should be
	printer.  The base function provides a numeric shorthand to the
	config("mode") interface.  With no args, base() will return the
	current mode.  With 1 arg, base(val) will set the mode according to
	the arg and return the previous mode.

	The following convention is used to declare modes:

		 base	 config
		value	 string

		   2	"binary"	binary fractions
		   8	"octal"		octal fractions
		  10	"real"		decimal floating point
		  16	"hex"		hexadecimal fractions
		 -10	"int"		decimal integer
		 1/3	"frac"		decimal fractions
		1e20	"exp"		decimal exponential

	For convenience, any non-integer value is assumed to mean "frac",
	and any integer >= 2^64 is assumed to mean "exp".

## Copyright (C) 1999  Landon Curt Noll
##
## Calc is open software; you can redistribute it and/or modify it under
## the terms of the version 2.1 of the GNU Lesser General Public License
## as published by the Free Software Foundation.
##
## Calc is distributed in the hope that it will be useful, but WITHOUT
## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
## or FITNESS FOR A PARTICULAR PURPOSE.	 See the GNU Lesser General
## Public License for more details.
##
## A copy of version 2.1 of the GNU Lesser General Public License is
## distributed with calc under the filename COPYING-LGPL.  You should have
## received a copy with calc; if not, write to Free Software Foundation, Inc.
## 59 Temple Place, Suite 330, Boston, MA  02111-1307, USA.
##
## @(#) $Revision: 29.2 $
## @(#) $Id: builtin.end,v 29.2 2000/06/07 14:02:33 chongo Exp $
## @(#) $Source: /usr/local/src/cmd/calc/help/RCS/builtin.end,v $
##
## Under source code control:	1995/07/10 01:17:53
## File existed as early as:	1995
##
## chongo <was here> /\oo/\	http://www.isthe.com/chongo/
## Share and enjoy!  :-)	http://www.isthe.com/chongo/tech/comp/calc/
