hongo /\oo/\ http://www.isthe.com/chongo/ ## Share and enjoy! :-) http://www.isthe.com/chongo/tech/comp/calc/ Command sequence This is a sequence of any the following command formats, where each command is terminated by a semicolon or newline. Long command lines can be extended by using a back-slash followed by a newline character. When this is done, the prompt shows a double angle bracket to indicate that the line is still in progress. Certain cases will automatically prompt for more input in a similar manner, even without the back-slash. The most common case for this is when a function is being defined, but is not yet completed. Each command sequence terminates only on an end of file. In addition, commands can consist of expression sequences, which are described in the next section. define a function ----------------- define function(params) { body } define function(params) = expression This first form defines a full function which can consist of declarations followed by many statements which implement the function. The second form defines a simple function which calculates the specified expression value from the specified parameters. The expression cannot be a statement. However, the comma and question mark operators can be useful. Examples of simple functions are: define sumcubes(a, b) = a^3 + b^3 define pimod(a) = a % pi() define printnum(a, n, p) { if (p == 0) { print a: "^": n, "=", a^n; } else { print a: "^": n, "mod", p, "=", pmod(a,n,p); } } read calc commands ------------------ read $var read -once $var read filename read -once filename This reads definitions from the specified calc resource filename. In the 1st and 2nd forms, if var is a global variable string value, then the value of that variable is used as a filename. The following is equivalent to read lucas.cal or read "lucas.cal": global var = "lucas.cal"; read $var; In the 3rd or 4th forms, the filename argument is treated as a literal string, not a variable. In these forms, the name can be quoted if desired. The calculator uses the CALCPATH environment variable to search through the specified directories for the filename, similarly to the use of the PATH environment variable. If CALCPATH is not defined, then a default path which is usually ":/usr/local/lib/calc" is used. The ".cal" extension is defaulted for input files, so that if "filename" is not found, then "filename.cal" is then searched for. The contents of the filename are command sequences which can consist of expressions to evaluate or functions to define, just like at the top level command level. When -once is given, the read command acts like the regular read expect that it will ignore filename if is has been previously read. The read -once form is particularly useful in a resource file that needs to read a 2nd resource file. By using the READ -once command, one will not reread that 2nd resource file, nor will once risk entering into a infinite READ loop (where that 2nd resource file directly or indirectly does a READ of the first resource file). If the -m mode disallows opening of files for reading, this command will be disabled. write calc commands ------------------- write $var write filename This writes the values of all global variables to the specified filename, in such a way that the file can be later read in order to recreate the variable values. For speed reasons, values are written as hex fractions. This command currently only saves simple types, so that matrices, lists, and objects are not saved. Function definitions are also not saved. In the 1st form, if var is a global variable string value, then the value of that variable is used as a filename. The following is equivalent to write dump.out or write "dump.out": global var = "dump.out"; write $var; In the 2nd form, the filename argument is treated as a literal string, not a variable. In this form, the name can be quoted if desired. If the -m mode disallows opening of files for writing, this command will be disabled. quit or exit ------------ quit quit string exit exit string The action of these commands depends on where they are used. At the interactive level, they will cause calc it edit. This is the normal way to leave the calculator. In any other use, they will stop the current calculation as if an error had occurred. If a string is given, then the string is printed as the reason for quitting, otherwise a general quit message is printed. The routine name and line number which executed the quit is also printed in either case. Exit is an alias for quit. Quit is useful when a routine detects invalid arguments, in order to stop a calculation cleanly. For example, for a square root routine, an error can be given if the supplied parameter was a negative number, as in: define mysqrt(n) { if (! isnum(n)) quit "non-numeric argument"; if (n < 0) quit "Negative argument"; return sqrt(n); } See 'more information about abort and quit' below for more information. abort ----- abort abort string This command behaves like QUIT except that it will attempt to return to the interactive level if permitted, otherwise calc exit. See 'more information about abort and quit' below for more information. change current directory ------------------------ cd cd dir Change the current directory to 'dir'. If 'dir' is ommitted, change the current directory to the home directory, if $HOME is set in the environment. show information ---------------- show item This command displays some information where 'item' is one of the following: blocks unfreed named blocks builtin built in functions config config parameters and values constants cache of numeric constants custom custom functions if calc -C was used errors new error-values created files open files, file position and sizes function user-defined functions globaltypes global variables objfunctions possible object functions objtypes defined objects opcodes func internal opcodes for function `func' sizes size in octets of calc value types realglobals numeric global variables statics unscoped static variables numbers calc number cache redcdata REDC data defined strings calc string cache literals calc literal cache Only the first 4 characters of item are examined, so: show globals show global show glob do the same thing. calc help --------- help $var help name This displays a help related to 'name' or general help of none is given. In the 1st form, if var is a global variable string value, then the value of that variable is used as a name. The following is equivalent to help command or help "command": global var = "command"; help $var; In the 2nd form, the filename argument is treated as a literal string, not a variable. In this form, the name can be quoted if desired. =-= more information about abort and quit ===================================== Consider the following calc file called myfile.cal: print "start of myfile.cal"; define q() {quit "quit from q()"; print "end of q()"} define a() {abort "abort from a()"} x = 3; {print "start #1"; if (x > 1) q()} print "after #1"; {print "start #2"; if (x > 1) a()} print "after #2"; {print "start #3"; if (x > 1) quit "quit from 3rd statement"} print "end of myfile.cal"; The command: calc read myfile will produce: q() defined a() defined start statment #1 quit from q() after statment #1 start statment #2 abort from a() The QUIT within the q() function prevented the ``end of q()'' statement from being evaluated. This QUIT command caused control to be returned to just after the place where q() was called. Notice that unlike QUIT, the ABORT inside function a() halts the processing of statements from the input source (myfile.cal). Because calc was not interactive, ABORT causes calc to exit. The command: calc -i read myfile will produce: q() defined a() defined start statment #1 quit from q() after statment #1 start statment #2 abort from a() ; <==== calc interactive prompt because the '-i' calc causes ABORT to drop into an interactive prompt. However typing a QUIT or ABORT at the interactive prompt level will always calc to exit, even when calc is invoked with '-i'. Also observe that both of these commands: cat myfile.cal | calc cat myfile.cal | calc -i will produce: q() defined a() defined start statment #1 quit from q() after statment #1 start statment #2 abort from a() The ABORT inside function a() halts the processing of statements from the input source (standard input). Because standard input is not a terminal, using '-i' does not force it to drop into an interactive prompt. If one were to type in the contents of myfile.cal interactively, calc will produce: ; print "start of myfile.cal"; start of myfile.cal ; define q() {quit "quit from q()"; print "end of q()"} q() defined ; define a() {abort "abort from a()"} a() defined ; x = 3; ; {print "start #1"; if (x > 1) q()} print "after #1"; start statment #1 quit from q() after statment #1 ; {print "start #2"; if (x > 1) a()} print "after #2"; start statment #2 abort from a() ; {print "start #3"; if (x > 1) quit "quit from 3rd statement"} start #3 quit from 3rd statement The ABORT from within the a() function returned control to the interactive level. The QUIT (after the if (x > 1) ...) will cause calc to exit because it was given at the interactive prompt level. =-= Also see the help topic: statement flow control and declaration statements usage how to invoke the calc command and calc -options ## Copyright (C) 1999-2006 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. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ## ## @(#) $Revision: 30.1 $ ## @(#) $Id: command,v 30.1 2007/03/16 11:10:42 chongo Exp $ ## @(#) $Source: /usr/local/src/cmd/calc/help/RCS/command,v $ ## ## Under source code control: 1991/07/21 04:37:17 ## File existed as early as: 1991 ## ## chongo /\oo/\ http://www.isthe.com/chongo/ ## Share and enjoy! :-) http://www.isthe.com/chongo/tech/comp/calc/ NAME append - append one or more values to end of list SYNOPSIS append(x, y_0, y_1, ...) TYPES x lvalue whose value is a list y_0, ... any return null value DESCRIPTION If after evaluation of y_0, y_1, ..., x is a list with contents (x_0, x_1, ...), then after append(x, y_0, y_1, ...), x has contents (x_0, x_1, ..., y_0, y_1, ...). If after evaluation of y_0, y_1, ..., x has size n, append(x, y_0, y_1, ...) is equivalent to insert(x, n, y_0, y_1, ...). EXAMPLE ; x = list(2,3,4) ; append(x, 5, 6) ; print x list (5 elements, 5 nonzero): [[0]] = 2 [[1]] = 3 [[2]] = 4 [[3]] = 5 [[4]] = 6 ; append(x, pop(x), pop(x)) ; print x list (5 elements, 5 nonzero): [[0]] = 4 [[1]] = 5 [[2]] = 6 [[3]] = 2 [[4]] = 3 ; append(x, (remove(x), 7)) ; print x list (5 elements, 5 nonzero): [[0]] = 4 [[1]] = 5 [[2]] = 6 [[3]] = 2 [[4]] = 7 LIMITS append() can have at most 100 arguments LINK LIBRARY none SEE ALSO delete, insert, islist, pop, push, remove, rsearch, search, select, size ## Copyright (C) 1999-2006 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. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ## ## @(#) $Revision: 30.1 $ ## @(#) $Id: append,v 30.1 2007/03/16 11:10:42 chongo Exp $ ## @(#) $Source: /usr/local/src/cmd/calc/help/RCS/append,v $ ## ## Under source code control: 1994/03/19 03:13:17 ## File existed as early as: 1994 ## ## chongo /\oo/\ http://www.isthe.com/chongo/ ## Share and enjoy! :-) http://www.isthe.com/chongo/tech/comp/calc/ NAME segment - segment from and to specified elements of a list SYNOPSIS segment(x, y, z) TYPES x list y, z int return list DESCRIPTION For 0 <= y < size(x) and 0 <= z < size(x), segment(x, y, z) returns a list for which the values of the elements are those of the segment of x from x[[y]] to x[[z]]. If y < z, the new list is in the same order as x; if y > z, the order is reversed. If y < z, x == join(head(x,y), segment(x,y,z), tail(x, size(x) - z - 1)). EXAMPLE ; A = list(2, 3, 5, 7, 11) ; segment(A, 1, 3) list (3 members, 3 nonzero): [[0]] = 3 [[1]] = 5 [[2]] = 7 ; segment(A, 3, 1) list (3 members, 3 nonzero): [[0]] = 7 [[1]] = 5 [[2]] = 3 LIMITS 0 <= y < size(x) 0 <= z < size(x) LINK LIBRARY none SEE ALSO head, tail ## 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. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ## ## @(#) $Revision: 30.1 $ ## @(#) $Id: segment,v 30.1 2007/03/16 11:10:42 chongo Exp $ ## @(#) $Source: /usr/local/src/cmd/calc/help/RCS/segment,v $ ## ## Under source code control: 1995/07/10 02:09:31 ## File existed as early as: 1995 ## ## chongo /\oo/\ http://www.isthe.com/chongo/ ## Share and enjoy! :-) http://www.isthe.com/chongo/tech/comp/calc/ NAME files - return a file or the maximum number of open files SYNOPSIS files([fnum]) TYPES fnum int return files, int or null DESCRIPTION This function, when given the argument fnum, will use it as an index into an internal table of open file and return a file value. If that entry in the table is not in use, then the null value is returned instead. When no args are given, the maximum number of open files is returned. If you overwrite a variable containing a file value or don't save the result of an 'fopen', the opened file still remains open. Such 'lost' files can be recovered by using the 'files' function. The first 3 file entries always refer to standard input, output and error respectively. (see the example below) These three files are already open by the calculator and cannot be closed. When calc starts up, it scans for open file descriptors above stderr (2) and below MAXFILES (20). Any open descriptor found is assumed to be an open file opened in an unknown mode. Calc will try to read and write to this file when directed. Consider the following commands shell commands: echo "A line of text in the file on descriptor 5" > datafile calc 5 /\oo/\ http://www.isthe.com/chongo/ ## Share and enjoy! :-) http://www.isthe.com/chongo/tech/comp/calc/ ************* * intro ************* What is calc? Calc is an interactive calculator which provides for easy large numeric calculations, but which also can be easily programmed for difficult or long calculations. It can accept a command line argument, in which case it executes that single command and exits. Otherwise, it enters interactive mode. In this mode, it accepts commands one at a time, processes them, and displays the answers. In the simplest case, commands are simply expressions which are evaluated. For example, the following line can be input: 3 * (4 + 1) and the calculator will print: 15 Calc as the usual collection of arithmetic operators +, -, /, * as well as ^ (exponentiation), % (modulus) and // (integer divide). For example: 3 * 19^43 - 1 will produce: 29075426613099201338473141505176993450849249622191102976 Notice that calc values can be very large. For example: 2^23209-1 will print: 402874115778988778181873329071 ... many digits ... 3779264511 The special '.' symbol (called dot), represents the result of the last command expression, if any. This is of great use when a series of partial results are calculated, or when the output mode is changed and the last result needs to be redisplayed. For example, the above result can be modified by typing: . % (2^127-1) and the calculator will print: 47385033654019111249345128555354223304 For more complex calculations, variables can be used to save the intermediate results. For example, the result of adding 7 to the previous result can be saved by typing: curds = 15 whey = 7 + 2*curds Functions can be used in expressions. There are a great number of pre-defined functions. For example, the following will calculate the factorial of the value of 'old': fact(whey) and the calculator prints: 13763753091226345046315979581580902400000000 The calculator also knows about complex numbers, so that typing: (2+3i) * (4-3i) cos(.) will print: 17+6i -55.50474777265624667147+193.9265235748927986537i The calculator can calculate transcendental functions, and accept and display numbers in real or exponential format. For example, typing: config("display", 70) epsilon(1e-70) sin(1) prints: 0.8414709848078965066525023216302989996225630607983710656727517099919104 Calc can output values in terms of fractions, octal or hexadecimal. For example: config("mode", "fraction"), (17/19)^23 base(16), (19/17)^29 will print: 19967568900859523802559065713/257829627945307727248226067259 0x9201e65bdbb801eaf403f657efcf863/0x5cd2e2a01291ffd73bee6aa7dcf7d1 All numbers are represented as fractions with arbitrarily large numerators and denominators which are always reduced to lowest terms. Real or exponential format numbers can be input and are converted to the equivalent fraction. Hex, binary, or octal numbers can be input by using numbers with leading '0x', '0b' or '0' characters. Complex numbers can be input using a trailing 'i', as in '2+3i'. Strings and characters are input by using single or double quotes. Commands are statements in a C-like language, where each input line is treated as the body of a procedure. Thus the command line can contain variable declarations, expressions, labels, conditional tests, and loops. Assignments to any variable name will automatically define that name as a global variable. The other important thing to know is that all non-assignment expressions which are evaluated are automatically printed. Thus, you can evaluate an expression's value by simply typing it in. Many useful built-in mathematical functions are available. Use the: help builtin command to list them. You can also define your own functions by using the 'define' keyword, followed by a function declaration very similar to C. define f2(n) { local ans; ans = 1; while (n > 1) ans *= (n -= 2); return ans; } Thus the input: f2(79) will produce; 1009847364737869270905302433221592504062302663202724609375 Functions which only need to return a simple expression can be defined using an equals sign, as in the example: define sc(a,b) = a^3 + b^3 Thus the input: sc(31, 61) will produce; 256772 Variables in functions can be defined as either 'global', 'local', or 'static'. Global variables are common to all functions and the command line, whereas local variables are unique to each function level, and are destroyed when the function returns. Static variables are scoped within single input files, or within functions, and are never destroyed. Variables are not typed at definition time, but dynamically change as they are used. For more information about the calc language and features, try: help overview In particular, check out the other help functions listed in the overview help file. ## 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. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ## ## @(#) $Revision: 30.1 $ ## @(#) $Id: intro,v 30.1 2007/03/16 11:10:42 chongo Exp $ ## @(#) $Source: /usr/local/src/cmd/calc/help/RCS/intro,v $ ## ## Under source code control: 1991/07/21 04:37:21 ## File existed as early as: 1991 ## ## chongo /\oo/\ http://www.isthe.com/chongo/ ## Share and enjoy! :-) http://www.isthe.com/chongo/tech/comp/calc/ ************* * overview ************* CALC - An arbitrary precision calculator. by David I. Bell This is a calculator program with arbitrary precision arithmetic. All numbers are represented as fractions with arbitrarily large numerators and denominators which are always reduced to lowest terms. Real or exponential format numbers can be input and are converted to the equivalent fraction. Hex, binary, or octal numbers can be input by using numbers with leading '0x', '0b' or '0' characters. Complex numbers can be input using a trailing 'i', as in '2+3i'. Strings and characters are input by using single or double quotes. Commands are statements in a C-like language, where each input line is treated as the body of a procedure. Thus the command line can contain variable declarations, expressions, labels, conditional tests, and loops. Assignments to any variable name will automatically define that name as a global variable. The other important thing to know is that all non-assignment expressions which are evaluated are automatically printed. Thus, you can evaluate an expression's value by simply typing it in. Many useful built-in mathematical functions are available. Use the 'show builtins' command to list them. You can also define your own functions by using the 'define' keyword, followed by a function declaration very similar to C. Functions which only need to return a simple expression can be defined using an equals sign, as in the example 'define sc(a,b) = a^3 + b^3'. Variables in functions can be defined as either 'global', 'local', or 'static'. Global variables are common to all functions and the command line, whereas local variables are unique to each function level, and are destroyed when the function returns. Static variables are scoped within single input files, or within functions, and are never destroyed. Variables are not typed at definition time, but dynamically change as they are used. So you must supply the correct type of variable to those functions and operators which only work for a subset of types. Calc has a help command that will produce information about every builtin function, command as well as a number of other aspects of calc usage. Try the command: help help for and overview of the help system. The command: help builtin provides information on built-in mathematical functions, whereas: help asinh will provides information a specific function. The following help files: help command help define help operator help statement help variable provide a good overview of the calc language. If you are familiar with C, you should also try: help unexpected It contains information about differences between C and calc that may surprize you. To learn about calc standard resource files, try: help resource To learn how to invoke the calc command and about calc -flags, try: help usage To learn about calc shell scripts, try: help script A full and extensive overview of calc may be obtained by: help full By default, arguments to functions are passed by value (even matrices). For speed, you can put an ampersand before any variable argument in a function call, and that variable will be passed by reference instead. However, if the function changes its argument, the variable will change. Arguments to built-in functions and object manipulation functions are always called by reference. If a user-defined function takes more arguments than are passed, the undefined arguments have the null value. The 'param' function returns function arguments by argument number, and also returns the number of arguments passed. Thus functions can be written to handle an arbitrary number of arguments. The mat statement is used to create a matrix. It takes a variable name, followed by the bounds of the matrix in square brackets. The lower bounds are zero by default, but colons can be used to change them. For example 'mat foo[3, 1:10]' defines a two dimensional matrix, with the first index ranging from 0 to 3, and the second index ranging from 1 to 10. The bounds of a matrix can be an expression calculated at runtime. Lists of values are created using the 'list' function, and values can be inserted or removed from either the front or the end of the list. List elements can be indexed directly using double square brackets. The obj statement is used to create an object. Objects are user-defined values for which user-defined routines are implicitly called to perform simple actions such as add, multiply, compare, and print. Objects types are defined as in the example 'obj complex {real, imag}', where 'complex' is the name of the object type, and 'real' and 'imag' are element names used to define the value of the object (very much like structures). Variables of an object type are created as in the example 'obj complex x,y', where 'x' and 'y' are variables. The elements of an object are referenced using a dot, as in the example 'x.real'. All user-defined routines have names composed of the object type and the action to perform separated by an underscore, as in the example 'complex_add'. The command 'show objfuncs' lists all the definable routines. Object routines which accept two arguments should be prepared to handle cases in which either one of the arguments is not of the expected object type. These are the differences between the normal C operators and the ones defined by the calculator. The '/' operator divides fraction  !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~s, so that '7 / 2' evaluates to 7/2. The '//' operator is an integer divide, so that '7 // 2' evaluates to 3. The '^' operator is a integral power function, so that 3^4 evaluates to 81. Matrices of any dimension can be treated as a zero based linear array using double square brackets, as in 'foo[[3]]'. Matrices can be indexed by using commas between the indices, as in foo[3,4]. Object and list elements can be referenced by using double square brackets. The print statement is used to print values of expressions. Separating values by a comma puts one space between the output values, whereas separating values by a colon concatenates the output values. A trailing colon suppresses printing of the end of line. An example of printing is 'print \"The square of\", x, \"is\", x^2\'. The 'config' function is used to modify certain parameters that affect calculations or the display of values. For example, the output display mode can be set using 'config(\"mode\", type)', where 'type' is one of 'frac', 'int', 'real', 'exp', 'hex', 'oct', or 'bin'. The default output mode is real. For the integer, real, or exponential formats, a leading '~' indicates that the number was truncated to the number of decimal places specified by the default precision. If the '~' does not appear, then the displayed number is the exact value. The number of decimal places printed is set by using 'config(\"display\", n)'. The default precision for real-valued functions can be set by using 'epsilon(x)', where x is the required precision (such as 1e-50). There is a command stack feature so that you can easily re-execute previous commands and expressions from the terminal. You can also edit the current command before it is completed. Both of these features use emacs-like commands. Files can be read in by using the 'read filename' command. These can contain both functions to be defined, and expressions to be calculated. Global variables which are numbers can be saved to a file by using the 'write filename' 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. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ## ## @(#) $Revision: 30.1 $ ## @(#) $Id: overview,v 30.1 2007/03/16 11:10:42 chongo Exp $ ## @(#) $Source: /usr/local/src/cmd/calc/help/RCS/overview,v $ ## ## Under source code control: 1991/07/21 04:37:23 ## File existed as early as: 1991 ## ## chongo /\oo/\ http://www.isthe.com/chongo/ ## Share and enjoy! :-) http://www.isthe.com/chongo/tech/comp/calc/ ************* * help ************* For more information while running calc, type help followed by one of the following topics: topic description ----- ----------- intro introduction to calc overview overview of calc help this file assoc using associations builtin builtin functions command top level commands config configuration parameters custom information about the custom builtin interface define how to define functions environment how environment variables effect calc errorcodes calc generated error codes expression expression sequences file using files history command history interrupt how interrupts are handled list using lists mat using matrices obj user defined data types operator math, relational, logic and variable access operators statement flow control and declaration statements types builtin data types unexpected unexpected syntax/usage surprises for C programmers usage how to invoke the calc command variable variables and variable declarations bindings input & history character bindings custom_cal information about custom calc resource files libcalc using the arbitrary precision routines in a C program new_custom information about how to add new custom functions resource standard calc resource files script using calc shell scripts cscript info on the calc shell scripts supplied with calc archive where to get the latest versions of calc bugs known bugs and mis-features changes recent changes to calc contrib how to contribute scripts, code or custom functions todo list of priority action items for calc wishlist wish list of future enhancements of calc credit who wrote calc and who helped copyright calc copyright and the GNU LGPL copying details on the Calc GNU Lesser General Public License copying-lgpl calc GNU Lesser General Public License text full all of the above (in the above order) For example: help usage will print the calc command usage information. One can obtain calc help without invoking any startup code by running calc as follows: calc -q help topic where 'topic' is one of the topics listed above. You can also ask for help on a particular builtin function name. For example: help asinh help round See: help builtin for a list of builtin functions. Some calc operators have their own help pages: help = help -> help * help . help % help // help # If the -m mode disallows opening files for reading or execution of programs, then the help facility will be disabled. See: help usage for details of the -m mode. The help command is able to display installed help files for custom builtin functions. However, if the custom name is the same as a standard help file, the standard help file will be displayed instead. The custom help builtin should be used to directly access the custom help file. For example, the custom help builtin has the same name as the standard help file. That is: help help will print this file only. However the custom help builtin will print only the custom builtin help file: custom("help", "help"); will by-pass a standard help file and look for the custom version directly. As a hack, the following: help custhelp/anything as the same effect as: custom("help", "anything"); ## Copyright (C) 1999-2007 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. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ## ## @(#) $Revision: 30.1 $ ## @(#) $Id: help,v 30.1 2007/03/16 11:10:42 chongo Exp $ ## @(#) $Source: /usr/local/src/cmd/calc/help/RCS/help,v $ ## ## Under source code control: 1991/07/21 04:37:20 ## File existed as early as: 1991 ## ## chongo /\oo/\ http://www.isthe.com/chongo/ ## Share and enjoy! :-) http://www.isthe.com/chongo/tech/comp/calc/ ************* * assoc ************* NAME assoc - create a new association array SYNOPSIS assoc() TYPES return association DESCRIPTION This function returns an empty association array. After A = assoc(), elements can be added to the association by assignments of the forms A[a_1] = v_1 A[a_1, a_2] = v_2 A[a_1, a_2, a_3] = v_3 A[a_1, a_2, a_3, a_4] = v_4 There are no restrictions on the values of the "indices" a_i or the "values" v_i. After the above assignments, so long as no new values have been assigned to A[a_i], etc., the expressions A[a_1], A[a_1, a_2], etc. will return the values v_1, v_2, ... Until A[a_1], A[a_1, a_2], ... are defined as described above, these expressions return the null value. Thus associations act like matrices except that different elements may have different numbers (between 1 and 4 inclusive) of indices, and these indices need not be integers in specified ranges. Assignment of a null value to an element of an association does not delete the element, but a later reference to that element will return the null value as if the element is undefined. The elements of an association are stored in a hash table for quick access. The index values are hashed to select the correct hash chain for a small sequential search for the element. The hash table will be resized as necessary as the number of entries in the association becomes larger. The size function returns the number of elements in an association. This size will include elements with null values. Double bracket indexing can be used for associations to walk through the elements of the association. The order that the elements are returned in as the index increases is essentially random. Any change made to the association can reorder the elements, this making a sequential scan through the elements difficult. The search and rsearch functions can search for an element in an association which has the specified value. They return the index of the found element, or a NULL value if the value was not found. Associations can be copied by an assignment, and can be compared for equality. But no other operations on associations have meaning, and are illegal. EXAMPLE ; A = assoc(); print A assoc (0 elements): ; A["zero"] = 0; A["one"] = 1; A["two"] = 2; A["three"] = 3; ; A["smallest", "prime"] = 2; ; print A assoc (5 elements); ["two"] = 2 ["three"] = 3 ["one"] = 1 ["zero"] = 0 ["smallest","prime"] = 2 LIMITS none LINK LIBRARY none SEE ALSO isassoc, rsearch, search, size ## 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. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ## ## @(#) $Revision: 30.1 $ ## @(#) $Id: assoc,v 30.1 2007/03/16 11:10:42 chongo Exp $ ## @(#) $Source: /usr/local/src/cmd/calc/help/RCS/assoc,v $ ## ## Under source code control: 1994/09/25 20:22:31 ## File existed as early as: 1994 ## ## chongo /\oo/\ http://www.isthe.com/chongo/ ## Share and enjoy! :-) http://www.isthe.com/chongo/tech/comp/calc/ ************* * builtin ************* 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. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ## ## @(#) $Revision: 30.1 $ ## @(#) $Id: builtin.top,v 30.1 2007/03/16 11:10:42 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 /\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 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) 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") r