Procedures set to read and write HP95LX appointment book (.abk) files. Notes: 1. Files created by the Appointment Book application may contain some padding following the last field of some data records. Hence, the RecordLength field must be used to determine the start of the next record. Appointment book files created by other programs need not have any padding. 2. ApptState has several bit fields. Only bit 0 is meaningful to software processing an appointment book file. Bit 0 being set or cleared corresponds to the alarm being enabled or disabled, respectively. Programs creating Appointment book files should clear all bits, except perhaps bit 0. 3. ToDoState has two one-bit bit fields. Bit 0 being set or cleared corresponds to carry forward being enabled or disabled for this todo item, respectively. Bit 1 being set or cleared corresponds to the doto being checked off or not checked off, respectively. 4. Appointment and ToDo texts are each limited to a maximum of 27 characters. 5. Note text is limited to a maximum of 11 lines of 39 characters per line (not counting the line terminator).
[ Full documentation | Source code ]
Pretty mundane stuff. Set_OS(), Basename(), Pathname(), Strip(), and a utility for creating index filenames.
[ Full documentation | Source code ]
Procedures used by programs that process address lists: nextadd() get next address writeadd(add) write address get_country(add) get country get_state(add) get state (U.S. addresses only) get_city(add) get city (U.S. addresses only) get_zipcode(add) get ZIP code (U.S. addresses only) get_lastname(add) get last name get_namepfx(add) get name prefix get_title(add) get name title format_country(s) format country name
[ Full documentation | Source code ]
allof{expr1,expr2} -- Control operation that performs iterative conjunction. Iterative conjunction permits a conjunction expression to be built at run time which supports full backtracking among the created terms of the expression. The computed expression can be of arbitrary length, and is built via an iterative loop in which one term is appended to the expression (as if connected with a "&" operator) per iteration. Expr1 works like the control expression of "every-do"; it controls iteration by being resumed to produce all of its possible results. The allof{} expression produces the outcome of conjunction of all of the resulting instances of expr2. For example: global c ... pattern := "ab*" "abcdef" ? { allof { c := !pattern , if c == "*" then move(0 to *&subject - &pos + 1) else =c } & pos(0) } This example will perform a wild card match on "abcdef" against pattern "ab*", where "*" in a pattern matches 0 or more characters. Since pos(0) will fail the first time it is evaluated, the allof{} expression will be resumed just as a conjunction expression would, and backtracking will propagate through all of the instances of expr2; the expression will ultimately succeed (as its conjunctive equivalent would). Note that, due to the scope of variables in co-expressions, variables shared between expr1 and expr2 must have global scope, hence c in the above example must be global. The allof{} procedure models Icon's expression evaluation mechanism in that it explicitly performs backtracking. The author of this procedure knows of no way to invoke Icon's built-in goal directed evaluation to perform conjunction of a arbitrary number of computed expressions (suggestions welcome).
[ Full documentation | Source code ]
[ Full documentation | Source code ]
This package of procedures implements a subset of the ANSI terminal control sequences. The names of the procedures are taken directly from the ANSI names. If it is necessary to use these routines with non-ANSI devices, link in iolib.icn, and (optionally) iscreen.icn as well. Use will be made of whatever routines are made available via either of these libraries. Be careful of naming conflicts if you link in iscreen.icn. It contains procedures like "clear" and "boldface." CUB(i) Moves the cursor left i columns CUD(i) Moves the cursor down i rows CUF(i) Moves the cursor right i columns CUP(i,j) Moves the cursor to row i, column j CUU(i) Moves the cursor up i rows ED(i) Erases screen: i = 0, cursor to end; i = 1, beginning to cursor; i = 2, all (default 2) EL(i) Erases data in cursor row: i = 0, cursor to end; i = 1, beginning to cursor; i = 2, all (default 0) SGR(i) Sets video attributes: 0 = off; 1 = bold; 4 = underscore; 5 = blink; 7 = reverse (default 0) Note that not all so-called ANSI terminals support every ANSI screen control sequence - not even the limited subset included in this file. If you plan on using these routines with non-ANSI magic-cookie terminals (e.g. a Wyse-50) then it is strongly recommended that you link in iolib or itlib *and* iscreen (not just iolib or itlib by itself). The routines WILL WORK with most magic cookie terminals; they just don't always get all the modes displayed (because they are basically too busy erasing the cookies).
[ Full documentation | Source code ]
This procedure applies a list of functions to an argument. An example is apply([integer, log], 10) which is equivalent to integer(log(10)).
[ Full documentation | Source code ]
argparse(s) parses s as if it were a command line and puts the components in in a list, which is returned. At present, it does not accept any escape conventions.
[ Full documentation | Source code ]
create_array([lbs], [ubs], value) creates a n-dimensional array with the specified lower bounds, upper bounds, and with each array element having the specified initial value. ref_array(A, i1, i2, ...) references the i1-th i2-th ... element of A.
[ Full documentation | Source code ]
asciiname(s) returns the mnemonic name of the single unprintable ASCII character s.
[ Full documentation | Source code ]
Descriptions: base64encode( s1 ) : s2 returns the base64 encoding of a string s1 base64decode( s1 ) : s2 returns the base64 decoding of a string s1 fails if s1 isn't base64 encoded references: MIME encoding Internet RFC 2045
[ Full documentation | Source code ]
This procedure is based on the UNIX basename(1) utility. It strips off any path information and removes the specified suffix, if present. If no suffix is provided, the portion of the name up to the first "." is returned. It should work under UNIX, MS-DOS, and the Macintosh.
[ Full documentation | Source code ]
This is a collection of procedures that support conversion of Icon data elements to and from binary data formats. The purpose is to facilitate dealing with binary data files. The procedures can be used individually or via the "control" procedures pack() and unpack().
[ Full documentation | Source code ]
unsigned() -- Converts binary byte string into unsigned integer. Detects overflow if number is too large. This procedure is normally used for processing of binary data read from a file. raw() -- Puts raw bits of characters of string s into an integer. If the size of s is less than the size of an integer, the bytes are put into the low order part of the integer, with the remaining high order bytes filled with zero. If the string is too large, the most significant bytes will be lost -- no overflow detection. This procedure is normally used for processing of binary data read from a file. rawstring() -- Creates a string consisting of the raw bits in the low order "size" bytes of integer i. This procedure is normally used for processing of binary data to be written to a file.
[ Full documentation | Source code ]
This procedure applies a binary operation to a list of arguments. For example, binop("+", 1, 2, 3) returns 6.
[ Full documentation | Source code ]
int2bit(i) produces a string with the bit representation of i. bit2int(s) produces an integer corresponding to the bit representation i.
[ Full documentation | Source code ]
Procedures for working with strings made up of numeric values represented by strings of an arbitrary number of bits, stored without regard to character boundaries. In conjunction with the "large integers" feature of Icon, this facility can deal with bitstring segments of arbitrary size. If "large integers" are not supported, bitstring segments (i.e. the nbits parameter of BitStringGet and BitStringPut) wider that the integer size of the platform are likely to produce incorrect results.
[ Full documentation | Source code ]
Procedures for reading and writing integer values made up of an arbitrary number of bits, stored without regard to character boundaries.
[ Full documentation | Source code ]
Utility procedures for HP95LX phone book and appointment book processing.
[ Full documentation | Source code ]
These procedures produce text with interspersed characters suit- able for printing to produce the effect of boldface (by over- striking) and underscoring (using backspaces). bold(s) bold version of s uscore(s) underscored version of s
[ Full documentation | Source code ]
Limitation: Assumes square patterns.
[ Full documentation | Source code ]
Synopsis: bufopen(s) Open a file name s for buffered read and lookahead bufread(f) Read the next line from file f bufnext(f, n) Return the next nth record from file f without changing the next record to be read by bufread bufclose(f) Close file f
[ Full documentation | Source code ]
Procedures in this file supersede several procedures in datetime.icn.
[ Full documentation | Source code ]
calendat(j) return a record with the month, day, and year corresponding to the Julian Date Number j.
[ Full documentation | Source code ]
These procedures deal with procedure invocations that are encapsulated in records.
[ Full documentation | Source code ]
Capture is initially called by the user with one argument, the open file to contain the echoed output. Then it places itself and several shadow procedures between all calls to write, writes & stop. The user never need call capture again. Subsequently, during calls to write, writes, and stop, the appropriate shadow procedure gains control and calls capture internally. Capture then constructs a list of only those elements that direct output to &output and calls the original builtin function via the saved name. Upon return the shadow routine calls the the original builtin function with the full list. A series of uncaptured output functions have been added to allow output to be directed only to &output. These are handy for placing progress messages and other comforting information on the screen. Example: otherfile := open(...,"w") capfile := capture(open(filename,"w")) write("Hello there.",var1,var2," - this should be echoed", otherfile,"This should appear once in the other file only") uncaptured_writes("This will appear once only.") every i := 1 to 10000 do if ( i % 100 ) = 0 then uncaptured_writes("Progress is ",i,"\r") close(capfile) close(otherfile)
[ Full documentation | Source code ]
These procedures project geographic coordinates. rectp(x1, y1, x2, y2, xm, ym) defines a rectangular projection. pptrans(L1, L2) defines a planar projective transformation. utm(a, f) defines a latitude/longitude to UTM projection. project(p, L) projects a list of coordinates. invp(p) returns the inverse of projection p. compose(p1, p2, ...) creates a composite projection.
[ Full documentation | Source code ]
These procedures are analogous to the standard string-analysis functions except that uppercase letters are considered equivalent to lowercase letters. anycl(c, s, i1, i2) succeeds and produces i1 + 1, provided map(s[i1]) is in cset(map(c)) and i2 is greater than i1. It fails otherwise. balcl(c1, c2, c3, s, i1, i2) generates the sequence of integer positions in s preceding a character of cset(map(c1)) in map(s[i1:i2]) that is balanced with respect to characters in cset(map(c2)) and cset(map(c3)), but fails if there is no such position. findcl(s1, s2, i1, i2) generates the sequence of integer positions in s2 at which map(s1) occurs as a substring in map(s2[i1:i2]), but fails if there is no such position. manycl(c, s, i1, i2) succeeds and produces the position in s after the longest initial sequence of characters in cset(map(c)) within map(s[i1:i2]). It fails if map(s[i1]) is not in cset(map(c)). matchcl(s1, s2, i1, i2) produces i1 + *s1 if map(s1) == map(s2[i1+:=*s1]) but fails otherwise. uptocl(c, s, i1, i2) generates the sequence of integer positions in s preceding a character of cset(map(c)) in map(s[i1:i2]). It fails if there is no such position. Defaults: s, s2 &subject i1 &pos if s or s2 is defaulted; otherwise 1 i2 0 c1 &cset c2 '(' c3 ')' Errors: 101 i1 or i2 not integer 103 s or s1 or s2 not string 104 c or c1 or c2 or c3 not cset
[ Full documentation | Source code ]
These procedures provide a way of storing Icon values as strings and retrieving them. The procedure encode(x) converts x to a string s that can be converted back to x by decode(s). These procedures handle all kinds of values, including structures of arbitrary complexity and even loops. For "scalar" types -- null, integer, real, cset, and string -- decode(encode(x)) === x For structures types -- list, set, table, and record types -- decode(encode(x)) is, for course, not identical to x, but it has the same "shape" and its elements bear the same relation to the original as if they were encoded and decode individually. No much can be done with files, functions and procedures, and co-expressions except to preserve type and identification. The encoding of strings and csets handles all characters in a way that it is safe to write the encoding to a file and read it back. No particular effort was made to use an encoding of value that minimizes the length of the resulting string. Note, however, that as of Version 7 of Icon, there are no limits on the length of strings that can be written out or read in.
[ Full documentation | Source code ]
colmize() -- Arrange data into columns. Procedure to arrange a number of data items into multiple columns. Items are arranged in column-wise order, that is, the sequence runs down the first column, then down the second, etc. This procedure goes to great lengths to print the items in as few vertical lines as possible.
[ Full documentation | Source code ]
complete(s,st) completes a s relative to a set or list of strings, st. Put differently, complete() lets you supply a partial string, s, and get back those strings in st that s is either equal to or a substring of.
[ Full documentation | Source code ]
The following procedures perform operations on complex numbers. complex(r,i) create complex number with real part r and imaginary part i cpxabs(z) compute absolute value of complex number z cpxadd(z1, z2) add complex numbers z1 and z2 cpxconj(z) compute conjugate of complex number z cpxdiv(z1, z2) divide complex number z1 by complex number z2 cpxmul(z1, z2) multiply complex number z1 by complex number z2 cpxsub(z1, z2) subtract complex number z2 from complex number z1 cpxstr(z) convert complex number z to string representation strcpx(s) convert string representation s of complex number to complex number
[ Full documentation | Source code ]
Thanks to Clint Jeffery for suggesting the Directive wrapper and making defining a specification much cleaner looking and easier!
[ Full documentation | Source code ]
This procedure produces continued-fraction convergents from a list of partial quotients.
[ Full documentation | Source code ]
exbase10(i, j) converts base-10 integer i to base j. inbase10(s, i) convert base-i integer s to base 10. radcon(s, i, j) convert base-i integer s to base j. There are several other procedures related to conversion that are not yet part of this module.
[ Full documentation | Source code ]
Links to core modules of the basic part of the library, as defined in the Icon Language book (3/e, p.179) and Graphics book (p.47).
[ Full documentation | Source code ]
This program returns the number of structures of a given type that have been created.
[ Full documentation | Source code ]
currency() -- Formats "amount" in standard American currency format. "amount" can be a real, integer, or numeric string. "width" is the output field width, in which the amount is right adjusted. The returned string will be longer than "width" if necessary to preserve significance. "minus" is the character string to be used for negative amounts (default "-"), and is placed to the right of the amount.
[ Full documentation | Source code ]
This file links procedure files that generate traces of points on various plain curves. The first two parameters determine the defining position of the curve: x x coordinate y y coordinate The meaning of "definition position" depends on the curve. In some cases it is the position at which plotting starts. In others, it is a "center" for the curve. The next arguments vary and generally refer to parameters of the curve. There is no practical way to describe these here. If they are not obvious, the best reference is A Catalog of Special Plane Curves, J. Dennis Lawrence, Dover Publications, Inc., New York, 1972. This book, which is in print at the time of this writing, is a marvelous source of information about plane curves and is inexpensive as well. The trailing parameters give the number of steps and the end points (generally in angles) of the curves: steps number of points, default varies lo beginning of plotting range, default varies hi end of plotting range, default varies Because of floating-point roundoff, the number of steps may not be exactly the number specified. Note: Some of the curves may be "upside down" when plotted on coordinate systems in which the y axis increases in a downward direction. Caution: Some of these procedures generate very large values in portions of their ranges. These may cause run-time errors when used in versions of Icon prior to 8.10. One work-around is to turn on error conversion in such cases. Warning: The procedures that follow have not been tested thoroughly. Corrections and additions are most welcome. These procedures are, in fact, probably most useful for the parametric equations they contain.
[ Full documentation | Source code ]
datefns.icn - a collection of date functions Adaptor: Charles L Hethcoat III June 12, 1995 Taken from various sources as attributed below. All date and calendar functions use the "date_rec" structure defined below. Note: I adapted the procedures "julian" and "unjulian" sometime in 1994 from "Numerical Recipes in C." Some time later I discovered them (under slightly different names) in Version 9 of the Icon Library (Ralph Griswold, author). I am including mine for what they are worth. That'll teach me to wait!
[ Full documentation | Source code ]
Notes: - the default value for function parameters named "hoursFromGmt" is the value of global variable "HoursFromGmt" if nonnull, or environment variable "HoursFromGmt" if set, or 0. - The base year from which the "seconds" representation of a date is calculated is by default 1970 (the ad hoc standard used by both Unix and MS-Windows), but can be changed by either setting the global variable "DateBaseYear" or environment variable "DateBaseYear". - There are some procedures not mentioned in this summary that are useful: DateRecToSec(), SecToDateRec(). See the source code for details. ClockToSec(seconds) converts a time in the format of &clock to seconds past midnight. DateLineToSec(dateline,hoursFromGmt) converts a date in &dateline format to seconds since start of dateBaseYear. DateToSec(date,hoursFromGmt) converts a date string in Icon &date format (yyyy/mm/dd) to seconds past DateBaseYear. SecToClock(seconds) converts seconds past midnight to a string in the format of &clock. SecToDate(seconds,hoursFromGmt) converts seconds past DateBaseYear to a string in Icon &date format (yyyy/mm/dd). SecToDateLine(seconds,hoursFromGmt) produces a date in the same format as Icon's &dateline. SecToUnixDate(seconds,hoursFromGmt) returns a date and time in typical UNIX format: Jan 14 10:24 1991. IsLeapYear(year) succeeds if year is a leap year, otherwise fails. calendat(j) returns a record with the month, day, and year corresponding to the Julian Date Number j. date() natural date in English. dayoweek(day, month, year) produces the day of the week for the given date. Note carefully the parameter order. full13th(year1, year2) generates records giving the days on which a full moon occurs on Friday the 13th in the range from year1 though year2. julian(m, d, y) returns the Julian Day Number for the specified month, day, and year. pom(n, phase) returns record with the Julian Day number of fractional part of the day for which the nth such phase since January, 1900. Phases are encoded as: 0 - new moon 1 - first quarter 2 - full moon 3 - last quarter# GMT is assumed. saytime() computes the time in natural English. If an argument is supplied it is used as a test value to check the operation the program. walltime() produces the number of seconds since midnight. Beware wrap-around when used in programs that span midnight.
[ Full documentation | Source code ]
These procedures read DDF files ("Data Descriptive Files", ISO standard 8211) such as those specified by the US Geological Survey's "Spatial Data Transfer Standard" for digital maps. ISO8211 files from other sources may contain additional data encodings not recognized by these procedures. ddfopen(filename) opens a file and returns a handle. ddfdda(handle) returns a list of header records. ddfread(handle) reads the next data record. ddfclose(handle) closes the file.
[ Full documentation | Source code ]
dif(stream, compare, eof, group) generates a sequence of differences between an arbitrary number of input streams. Each result is returned as a list of diff_recs, one for each input stream, with each diff_rec containing a list of items that differ and their position in the input stream. The diff_rec type is declared as: record diff_rec(pos,diffs) dif() fails if there are no differences, i.e. it produces an empty result sequence.
[ Full documentation | Source code ]
This procedure counts the number of each digit in a file and returns a ten-element list with the counts.
[ Full documentation | Source code ]
The procedures do_od and if_fi implement the "do ... od" and "if ... fi" control structures used in the book "A Discipline of Programming" by Edsger W. Dijkstra. This book uses a programming language designed to delay implementation details, such as the order in which tests are performed. Dijkstra's programming language uses two non-ASCII characters, a box and a right arrow. In the following discussion, the box and right arrow characters are represented as "[]" and "->" respectively. The "if ... fi" control structure is similar to multi-branch "if" statements found in many languages, including the Bourne shell (i.e. the "if / elif / fi" construct). The major difference is that in Dijkstra's notation, there is no specified order in which the "if / elif" tests are performed. The "if ... fi" structure has the form if Guard1 -> List1 [] Guard2 -> List2 [] Guard3 -> List3 ... [] GuardN -> ListN fi where Guard1, Guard2, Guard3 ... GuardN are boolean expressions, and List1, List2, List3 ... ListN are lists of statements. When this "if ... fi" statement is performed, the guard expressions are evaluated, in some order not specified by the language, until one of the guard expressions evaluates to true. Once a true guard is found, the list of statements following the guard is evaluated. It is a fatal error for none of the guards in an "if ... fi" statement to be true. The "do ... od" control is a "while" loop structure, but with multiple loop conditions, in style similar to "if ... fi". The form of a Dijkstra "do" statement is do Guard1 -> List1 [] Guard2 -> List2 [] Guard3 -> List3 ... [] GuardN -> ListN od where Guard1, Guard2, Guard3 ... GuardN are boolean expressions, and List1, List2, List3 ... ListN are lists of statements. To perform this "do ... od" statement, the guard expressions are evaluated, in some order not specified by the language, until either a guard evaluates to true, or all guards have been evaluated as false. - If all the guards are false, we exit the loop. - If a guard evaluates to true, then the list of statements following this guard is performed, and then we loop back to perform this "do ... od" statement again. The procedures if_fi{} and do_od{} implement Dijkstra's "if ... fi" and "do ... od" control structures respectively. In keeping with Icon conventions, the guard expressions are arbitrary Icon expressions. A guard is considered to be true precisely when it succeeds. Similarly, a statement list can be represented by a single Icon expression. The Icon call if_fi{ Guard1, List1, Guard2, List2, ... GuardN, ListN } suspends with each result produced by the expression following the true guard. If none of the guards succeed, runerr() is called with an appropriate message. Similarly, the Icon call do_od{ Guard1, List1, Guard2, List2, ... GuardN, ListN } parallels the "do ... od" statement. As long as at least one guard succeeds, another iteration is performed. When all guards fail, we exit the loop and do_od fails. The test section of this file includes a guarded command implementation of Euclid's algorithm for calculating the greatest common denominator. Unlike most implementations of Euclid's algorithm, this version handles its parameters in a completely symmetrical fashion.
[ Full documentation | Source code ]
Doesn't get the decimal point. Not sure what the padding does; to study.
[ Full documentation | Source code ]
These procedures assist in use of the ASCII and EBCDIC character sets, regardless of the native character set of the host: Ascii128() Returns a 128-byte string of ASCII characters in numerical order. Ascii128() should be used in preference to &ascii for applications which might run on an EBCDIC host. Ascii256() Returns a 256-byte string representing the 256- character ASCII character set. On an EBCDIC host, the order of the second 128 characters is essentially arbitrary. Ebcdic() Returns a 256-byte string of EBCDIC characters in numerical order. AsciiChar(i) Returns the character whose ASCII representation is i. AsciiOrd(c) Returns the position of the character c in the ASCII collating sequence. EbcdicChar(i) Returns the character whose EBCDIC representation is i. EbcdicOrd(c) Returns the position of the character c in the EBCDIC collating sequence. MapEtoA(s) Maps a string of EBCDIC characters to the equivalent ASCII string, according to a plausible mapping. MapAtoE(s) Maps a string of ASCII characters to the equivalent EBCDIC string, according to a plausible mapping. Control(c) Returns the "control character" associated with the character c. On an EBCDIC host, with $ representing an EBCDIC character with no 7-bit ASCII equivalent, Control("$") may not be identical to "\^$", as translated by ICONT (and neither result is particularly meaningful).
[ Full documentation | Source code ]
echo() substitutes global variables for occurrences of $name in &subject, and writes the result to standard output.
[ Full documentation | Source code ]
This procedure is called by timing programs produced by empg. It a "delta" timing value used to adjust timings.
[ Full documentation | Source code ]
This program is designed to be linked with the output of the meta- translator. As given here, they produce an identity translation. Modifications can be made to effect different translations. The procedures here are just wrappers. This file is a skeleton that can be used as a basis for code-generation procedures.
[ Full documentation | Source code ]
equiv(s,y) compare arbitrary structures x and y
[ Full documentation | Source code ]
The procedure escape(s) produces a string in which Icon quoted literal escape conventions in s are replaced by the corresponding characters. For example, escape("\\143\\141\\164") produces the string "cat".
[ Full documentation | Source code ]
Procedure kit for dealing with escape sequences in Icon character string representations. Note that Icon escape sequences are very similar to C escapes, so this works for C strings, too. escapeseq() -- a matching procedure for Icon string escape sequences escchar() -- produces the character value of an Icon string escape sequence escape() -- converts a string with escape sequences (as in Icon string representation) to the string it represents with escape quotedstring() -- matching routine for a quoted string.
[ Full documentation | Source code ]
This procedure analyzes a string representing an Icon function or procedure call and evaluates the result. Operators can be used in functional form, as in "*(2,3)". This procedure cannot handle nested expressions or control structures. It assumes the string is well-formed. The arguments can only be Icon literals. Escapes, commas, and parentheses in strings literals are not handled. In the case of operators that are both unary and binary, the binary form is used.
[ Full documentation | Source code ]
This procedure takes an expression, produces a program encapsulating it, and puts the results written by the program in a list. It is called as evallist(expr, n, ucode, ...) where expr is an expression (normally a generator), n is the maximum size of the list, and the trailing arguments are ucode files to link with the expression.
[ Full documentation | Source code ]
This program is designed to be linked with the output of the meta-variant translator. It is designed to insert event-reporting code in Icon programs.
[ Full documentation | Source code ]
everycat(x1, x2, ...) generates the concatenation of every string from !x1, !x2, ... . For example, if first := ["Mary", "Joe", "Sandra"] last := ["Smith", "Roberts"] then every write(everycat(first, " ", last)) writes Mary Smith Mary Roberts Joe Smith Joe Roberts Sandra Smith Sandra Roberts Note that x1, x2, ... can be any values for which !x1, !x2, ... produce strings or values convertible to strings. In particular, in the example above, the second argument is a one-character string " ", so that !" " generates a single blank.
[ Full documentation | Source code ]
pfl2str(pattern) expands pattern-form expressions, which have the form [<expr><op><expr>] to the corresponding string. The value of <op> determines the operation to be performed. pfl2gxp(pattern) expands pattern-form expressions into generators that, when compiled and evaluated, produce the corresponding string. pfl2pwl(pattern) converts pattern-form expressions to Painter's weaving language.
[ Full documentation | Source code ]
exprfile(exp, link, ...) produces a pipe to a program that writes all the results generated by exp. The trailing arguments name link files needed for the expression. exprfile() closes any previous pipe it opened and deletes its temporary file. Therefore, exprfile() cannot be used for multiple expression pipes. If the expression fails to compile, the global expr_error is set to 1; otherwise 0. exec_expr(expr_list, links[]) generates the results of executing the expression contained in the lists expr_list with the specified links. plst2pstr(L) converts the list of Icon programs lines in L to a string with separating newlines. pstr2plst(s) converts the string of Icon program lines (separated by newlines) to a list of lines. ucode(file) produces a ucode file from the Icon program in file.
[ Full documentation | Source code ]
This file contains procedures related to factorization and prime numbers. divisors(n) generates the divisors of n. divisorl(n) returns a list of the divisors of n. factorial(n) returns n!. It fails if n is less than 0. factors(i, j) returns a list containing the prime factors of i limited to maximum value j; default, no limit. genfactors(i, j) like factors(), except factors are generated as they are found. gfactorial(n, i) generalized factorial; n x (n - i) x (n - 2i) x ... ispower(i, j) succeeds and returns root if i is k^j isprime(n) succeeds if n is a prime. nxtprime(n) returns the next prime number beyond n. pfactors(i) returns a list containing the primes that divide i. prdecomp(i) returns a list of exponents for the prime decomposition of i. prime() generates the primes. primel() generates the primes from a precompiled list. primorial(i,j) product of primes j <= i; j defaults to 1. sfactors(i, j) as factors(i, j), except output is in string form with exponents for repeated factors squarefree(i) succeeds if the factors of i are distinct
[ Full documentation | Source code ]
These procedures implement integer-valued using the fastest method known to the author. "Fastest" does not mean "fast". acker(i, j) Ackermann's function fib(i) Fibonacci sequence g(k, i) Generalized Hofstader nested recurrence q(i) "Chaotic" sequence robbins(i) Robbins numbers
[ Full documentation | Source code ]
This procedure analyzes a string representing an Icon function or procedure call and evaluates the result. It assumes the string is well-formed. The arguments can only be Icon literals. Escapes, commas, and parentheses in strings literals are not handled.
[ Full documentation | Source code ]
filedim(s, p) computes the number of rows and maximum column width of the file named s. The procedure p, which defaults to detab, i applied to each line. For example, to have lines left as is, use filedim(s, 1)
[ Full documentation | Source code ]
This procedure is useful when you need to create the next file in a series of files (such as successive log files). Usage: fn := nextseqfilename( ".", "$", "log") returns the (non-existent) filename next in the sequence .\$*.log (where the * represents 1, 2, 3, ...) or fails
[ Full documentation | Source code ]
filesize(s) returns the number of characters in the file named s; it fails if s cannot be opened.
[ Full documentation | Source code ]
DESCRIPTION: findre() is like the Icon builtin function find(), except that it takes, as its first argument, a regular expression pretty much like the ones the Unix egrep command uses (the few minor differences are listed below). Its syntax is the same as find's (i.e. findre(s1,s2,i,j)), with the exception that a no- argument invocation wipes out all static structures utilized by findre, and then forces a garbage collection.
[ Full documentation | Source code ]
This procedure returns the file identification produced by file(1).
[ Full documentation | Source code ]
fullimage() -- enhanced image()-type procedure that outputs all data contained in structured types. The "level" argument tells it how far to descend into nested structures (defaults to unlimited).
[ Full documentation | Source code ]
gauss_random(x, f) produces a Gaussian distribution about the value x. The value of f can be used to alter the shape of the Gaussian distribution (larger values flatten the curve...)
[ Full documentation | Source code ]
Gdl returns a list containing everything in a directory (whose name must be passed as an argument to gdl). Nothing fancy. I use this file as a template, modifying the procedures according to the needs of the program in which they are used.
[ Full documentation | Source code ]
Gdl returns a list containing everything in a directory (whose name must be passed as an argument to gdl). Nothing fancy. I use this file as a template, modifying the procedures according to the needs of the program in which they are used. NOTE: MSDOS results are all in lower case Modifications: 1) Fixed MSDOS routines. 2) Added gdlrec which does same thing as gdl except it recursively descends through subdirectories. May choose which Unix utility to use by passing in method parameter. See below.
[ Full documentation | Source code ]
These procedures read and interpret GEDCOM files, a standard format for genealogy databases.
[ Full documentation | Source code ]
These procedures are for use with code produced by a meta-variant translator. As given here, they produce an identity translation. Modifications can be made to effect variant translations.
[ Full documentation | Source code ]
These procedures generate sequences of results. days() days of the week. hex() sequence of hexadecimal codes for numbers from 0 to 255 label(s,i) sequence of labels with prefix s starting at i multii(i, j) sequence of i * j i's months() months of the year octal() sequence of octal codes for numbers from 0 to 255 star(s) sequence consisting of the closure of s starting with the empty string and continuing in lexical order as given in s
[ Full documentation | Source code ]
These procedures generate sequences of results. arandseq(i, j) arithmetic sequence starting at i with randomly chosen increment between 1 and j arithseq(i, j) arithmetic sequence starting at i with increment j beatty1seq() Beatty's first sequence i * &phi beatty2seq() Beatty's second sequence i * &phi ^ 2 catlnseq(i) sequence of generalized Catalan numbers cfseq(i, j) continued-fraction sequence for i / j chaosseq() chaotic sequence chexmorphseq() sequence of centered hexamorphic numbers connellseq(p) generalized Connell sequence dietzseq(s) Dietz sequence for polynomial dressseq(i) dress sequence with increment i, default 1 (Schroeder) eisseq(i) EIS A sequence for i factseq() factorial sequence fareyseq(i, k) Farey fraction sequence; k = 0, the default, produces numerator sequence; k = 1 produces denominator sequence fibseq(i, j, k, m) generalized Fibonacci sequence (Lucas sequence) with initial values i and j and additive constant k. If m is supplied, the results are produced mod m. figurseq(i) series of ith figurate number fileseq(s, i) generate from file s; if i is null, lines are generated. Otherwise characters, except line terminators. friendseq(k) generate random friendly sequence from k values, 1 to k (in a friendly sequence, successive terms differ by 1). geomseq(i, j) geometric sequence starting at i with multiplier j hailseq(i) hailstone sequence starting at i irepl(i, j) j instances of i lindseq(f, i) generate symbols from L-system in file f; i if present overrides the number of generations specified in the L-system. logmapseq(k, x) logistic map lrrcseq(L1, L2) generalized linear recurrence with constant coefficients; L1 is a list of initial terms, L2 is a list of coefficients for n previous values, where n = *L2 meanderseq(s, n) sequences of all characters that contain all n-tuples of characters from s mthueseq() Morse-Thue sequence mthuegseq(i) Morse-Thue sequence for base i multiseq(i, j, k) sequence of (i * j + k) i's ngonalseq(i) sequence of the ith polygonal number nibonacciseq(values[]) generalized Fibonacci sequence that sums the previous n terms, where n = *values. partitseq(i, j, k) sequence of integer partitions of i with minimum j and maximum k pellseq(i, j, k) generalized Pell's sequence starting with i, j and using multiplier k perrinseq() Perrin sequence polyseq(coeff[]) polynomial in x evaluated for x := seq() primeseq() the sequence of prime numbers powerseq(i) sequence n ^ i, n = 1, 2, 3, 4, ... powersofseq(i) sequence i ^ n, n = 1, 2, 3, 4, ...n rabbitseq() rabbit sequence ratsseq(i) versumseq() with sort signaseq(r) signature sequence of r spectseq(r) spectral sequence integer(i * r), i - 1, 2, 3, ... srpseq(n, m) palindromic part of the continued-fraction sequence for sqrt(n^2+m) versumseq(i, j) generalized sequence of added reversed integers with seed i (default 196) and increment j (default 0) versumopseq(i, p) procedure p (default 1) applied to versumseq(i) vishwanathseq() random variation on Fibonacci sequence zebra(values[]) zebra colors, alternating 2 and 1, for number of times given by successive values
[ Full documentation | Source code ]
These procedures provide "projections" that convert among geodetic datums, which relate locations on the earth's surface to longitude and latitude coordinates. As measurement techniques improve, newer datums typically give slightly different values from older ones. The values returned here are used with the project() procedure of cartog.icn. geodat(s1, s2) defines a geodetic datum conversion. molodensky() performs an algorithmic datum conversion. nadcon(s1, s2) uses data files for more precise conversion. ellipsoid(s) return the parameters of the named ellipsoid.
[ Full documentation | Source code ]
Implementing getch() is a much, much more complex affair under UNIX than it is under, say, MS-DOS. This library represents one, solution to the problem - one which can be run as a library, and need not be compiled into the run-time system. Note that it will not work on all systems. In particular, certain Suns (with a screwy stty command) and the NeXT 1.0 OS (lacking the -g option for stty) do not run getchlib properly. See the bugs section below for workarounds. Four basic utilities are included here: getch() - waits until a keystroke is available & returns it without displaying it on the screen getche() - same as getch() only with echo getse(s) - like getche() only for strings. The optional argument s gives getse() something to start with. Use this if, say, you want to read single characters in cbreak mode, but get more input if the character read is the first part of a longer command. If the user backspaces over everything that has been input, getse() fails. Returns on \r or \n. reset_tty() - absolutely vital routine for putting the cur- rent tty line back into cooked mode; call it before exiting or you will find yourself with a locked-up terminal; use it also if you must temporarily restore the terminal to cooked mode Note that getse() *must* be used in place of read(&input) if you are planning on using getch() or getche(), since read(&input) assumes a tty with "sane" settings. Warning: The routines below do not do any sophisticated output processing. As noted above, they also put your tty line in raw mode. I know, I know: "Raw is overkill - use cbreak." But in a world that includes SysV, one must pick a lowest common denomi- nator. And no, icanon != cbreak. BUGS: These routines will not work on systems that do not imple- ment the -g option for the stty command. The NeXT workstation is an example of such a system. Tisk, tisk. If you are on a BSD system where the network configuration makes stty | more impossible, then substitute /usr/5bin/stty (or whatever your system calls the System V stty command) for /bin/stty in this file. If you have no SysV stty command online, then you can try replacing every instance of "stty -g 2>&1" below with "stty -g 2>&1 1> /dev/tty" or something similar.
[ Full documentation | Source code ]
Getkeys(FNAME) generates all keys in FNAME in order of occurrence. See gettext.icn for a description of the requisite file structure for FNAME.
[ Full documentation | Source code ]
The getmail procedure reads a Unix/Internet type mail folder and generates a sequence of records, one per mail message. It fails when end-of-file is reached. Each record contains the message header and message text components parsed into separate record fields. The entire uninterpreted message (header and text) are also stored in the record. See the description of message_record below. The argument to getmail is either the name of a mail folder or the file handle for a mail folder which has already been opened for reading. If getmail is resumed after the last message is generated, it closes the mail folder and returns failure. If getmail generates an incomplete sequence (does not close the folder and return failure) and is then restarted (not resumed) on the same or a different mail folder, the previous folder file handle remains open and inaccessible. This may be a problem if done repeatedly since there is usually an OS-imposed limit on number of open file handles. Safest way to use getmail is using one of the below forms: message := message_record() every message := !getmail("folder_name") do { process message ... } message := message_record() coex := create getmail("folder_name") while message := @coex do { process message ... } Note that if message_record's are stored in a list, the records may be sorted by individual components (like sender, _date, _subject) using sortf function in Icon Version 9.0.
[ Full documentation | Source code ]
Suspends, in turn, the paths supplied as args to getpaths(), then all paths in the PATH environment variable. A typical invocation might look like: open(getpaths("/usr/local/lib/icon/procs") || filename) Note that getpaths() will be resumed in the above context until open succeeds in finding an existing, readable file. Getpaths() can take any number of arguments.
[ Full documentation | Source code ]
Gettext() and associated routines allow the user to maintain a file of KEY/value combinations such that a call to gettext(KEY, FNAME) will produce value. Gettext() fails if no such KEY exists. Returns an empty string if the key exists, but has no associated value in the file, FNAME. The file format is simple. Keys belong on separate lines, marked as such by an initial colon+colon (::). Values begin on the line following their respective keys, and extend up to the next colon+colon-initial line or EOF. E.g. ::sample.1 or: ::sample.1 ::sample.2 Notice how the key above, sample.1, has :: prepended to mark it out as a key. The text you are now reading represents that key's value. To retrieve this text, you would call gettext() with the name of the key passed as its first argument, and the name of the file in which this text is stored as its second argument (as in gettext("sample.1","tmp.idx")). ::next.key etc... For faster access, an indexing utility is included, idxtext. Idxtext creates a separate index for a given text-base file. If an index file exists in the same directory as FNAME, gettext() will make use of it. The index becomes worthwhile (at least on my system) after the text- base file becomes longer than 5 kilobytes. Donts: 1) Don't nest gettext text-base files. 2) In searches, surround phrases with spaces or tabs in key names with quotation marks: "an example" 3) Don't modify indexed files in any way other than to append additional keys/values (unless you want to re-index). This program is intended for situations where keys tend to have very large values, and use of an Icon table structure would be unwieldy. BUGS: Gettext() relies on the Icon runtime system and the OS to make sure the last text/index file it opens gets closed.
[ Full documentation | Source code ]
These declarations are provided for representing geometrical objects as records.
[ Full documentation | Source code ]
The procedures here use sets to represent directed graphs. See The Icon Programming Language, second edition, pp. 195-198. A value of type "graph" has two components: a list of nodes and a two-way lookup table. The nodes in turn contain pointers to other nodes. The two-way table maps a node to its name and vice-versa. Graph specifications are give in files in which the first line is a white-space separated list of node names and subsequent lines give the arcs, as in Tucson Phoenix Bisbee Douglas Flagstaff Tucson->Phoenix Tucson->Bisbee Bisbee->Bisbee Bisbee->Douglas Douglas->Phoenix Douglas->Tucson
[ Full documentation | Source code ]
[ Full documentation | Source code ]
hex(s) -- Converts string of hex digits into an integer. hexstring(i,n,lc) -- Returns a string that is the hexadecimal representation of the argument. If n is supplied, a minimum of n digits appear in the result; otherwise there is no minimum, and negative values are indicated by a minus sign. If lc is non-null, lowercase characters are used instead of uppercase.
[ Full documentation | Source code ]
This procedure determines the name of the current host. It takes no arguments. Aborts with an error message if the necessary commands are not found. Geared specifically for UNIX machines.
[ Full documentation | Source code ]
These procedures parse HTML files: htchunks(f) generates the basic chunks -- tags and text -- that compose an HTML file. htrefs(f) generates the tagname/keyword/value combinations that reference other files. These procedures process strings from HTML files: httag(s) extracts the name of a tag. htvals(s) generates the keyword/value pairs from a tag. urlmerge(base,new) interprets a new URL in the context of a base. canpath(s) puts a path in canonical form
[ Full documentation | Source code ]
Procedures to support benchmarking of Icon programs: Init__(prog) initialize for benchmarking Term__() terminate benchmarking Allocated__() get amounts allocated Collections__() get collections Regions__() get regions Signature__() show program/environment information Storage__() get storage Time__() show elapsed time Display__(data,name) show information
[ Full documentation | Source code ]
General: Ichartp implements a simple chart parser - a slow but easy-to-implement strategy for parsing context free grammars (it has a cubic worst-case time factor). Chart parsers are flexible enough to handle a lot of natural language constructs. They also lack many of the troubles associated with empty and left-recursive derivations. To obtain a parse, just create a BNF file, obtain a line of input, and then invoke parse_sentence(sentence, bnf_filename, start-symbol). Parse_sentence suspends successive edge structures corresponding to possible parses of the input sentence. There is a routine called edge_2_tree() that converts these edges to a more standard form. See the stub main() procedure for an example of how to make use of all these facilities.
[ Full documentation | Source code ]
This program is designed to be linked with the output of the meta- translator. As given here, they produce an identity translation. Modifications can be made to effect different translations.
[ Full documentation | Source code ]
This procedure produces an "identity" value for types that have one.
[ Full documentation | Source code ]
These are procedure wrappers for use in Icon function tracing. Don't let the apparent recursion fool you.
[ Full documentation | Source code ]
These procedures provide tracing for Icon functions by using procedure wrappers to call the functions. iftrace(fncs[]) sets tracing for a list of function names.
[ Full documentation | Source code ]
The procedure Image(x,style) produces a string image of the value x. The value produced is a generalization of the value produced by the Icon function image(x), providing detailed information about structures. The value of style determines the formatting and order of processing: 1 indented, with ] and ) at end of last item (default) 2 indented, with ] and ) on new line 3 puts the whole image on one line 4 as 3, but with structures expanded breadth-first instead of depth-first as for other styles.
[ Full documentation | Source code ]
This procedure, inbits(), re-imports data converted into writable form by outbits(). See the file outbits.icn for all the whys and hows.
[ Full documentation | Source code ]
indices(spec, last) produces a list of the integers given by the specification spec, which is a common separated list of either positive integers or integer spans, as in "1,3-10, ..." If last is specified, it it used for a span of the form "10-". In an integer span, the low and high values need not be in order. For example, "1-10" and "10-1" are equivalent. Similarly, indices need not be in order, as in "3-10, 1, ..." And empty value, as in "10,,12" is ignored. indices() fails if the specification is syntactically erroneous or if it contains a value less than 1.
[ Full documentation | Source code ]
inserts() -- Inserts values into a table in which the same key can have more than one value (i.e., duplicate keys). The value of each element is a list of inserted values. The table must be created with default value &null.
[ Full documentation | Source code ]
intstr() -- Creates a string consisting of the raw bits in the low order "size" bytes of integer i. This procedure is normally used for processing of binary data to be written to a file. Note that if large integers are supported, this procedure still will not work for integers larger than the implementation defined word size due to the shifting in of zero-bits from the left in the right shift operation.
[ Full documentation | Source code ]
They provide facilities for handling input, output, and files. There are other modules in the Icon program library that deal with input and output. They are not included here because they conflict with procedures here or each other.
[ Full documentation | Source code ]
The following library represents a series of rough functional equivalents to the standard UNIX low-level termcap routines. It is not meant as an exact termlib clone. Nor is it enhanced to take care of magic cookie terminals, terminals that use \D in their termcap entries, or archaic terminals that require padding. This library is geared mainly for use with ANSI and VT-100 devices. Note that this file may, in most instances, be used in place of the older UNIX-only itlib.icn file. It essentially replaces the DOS- only itlibdos routines. For DOS users not familiar with the whole notion of generalized screen I/O, I've included extra documentation below. Please read it. The sole disadvantage of this over the old itlib routines is that iolib.icn cannot deal with archaic or arcane UNIX terminals and/or odd system file arrangements. Note that because these routines ignore padding, they can (unlike itlib.icn) be run on the NeXT and other systems which fail to implement the -g option of the stty command. Iolib.icn is also simpler and faster than itlib.icn. I want to thank Norman Azadian for suggesting the whole idea of combining itlib.icn and itlibdos.icn into one distribution, for suggesting things like letting drive specifications appear in DOS TERMCAP environment variables, and for finding several bugs (e.g. the lack of support for %2 and %3 in cm). Although he is loathe to accept this credit, I think he deserves it.
[ Full documentation | Source code ]
This file contains some rudimentary screen functions for use with itlib.icn (termlib-like routines for Icon). clear() - clears the screen (tries several methods) emphasize() - initiates emphasized (usu. = reverse) mode boldface() - initiates bold mode blink() - initiates blinking mode normal() - resets to normal mode message(s) - displays message s on 2nd-to-last line underline() - initiates underline mode status_line(s,s2,p) - draws status line s on the 3rd-to-last screen line; if s is too short for the terminal, s2 is used; if p is nonnull then it either centers, left-, or right-justi- fies, depending on the value, "c," "l," or "r." clear_emphasize() - horrible way of clearing the screen to all- emphasize mode; necessary for many terminals
[ Full documentation | Source code ]
These procedures implement commonly referenced ``text-book'' recursively defined functions, but using iteration. acker(i, j) Ackermann's function fib(i, j) Generalized Fibonacci (Lucas) sequence
[ Full documentation | Source code ]
The following library represents a series of rough functional equivalents to the standard UNIX low-level termcap routines. They are not meant as exact termlib clones. Nor are they enhanced to take care of magic cookie terminals, terminals that use \D in their termcap entries, or, in short, anything I felt would not affect my normal, day-to-day work with ANSI and vt100 terminals. There are some machines with incomplete or skewed implementations of stty for which itlib will not work. See the BUGS section below for work- arounds.
[ Full documentation | Source code ]
The following library represents a series of rough functional equivalents to the standard UNIX low-level termcap routines. They are not meant as exact termlib clones. Nor are they enhanced to take care of magic cookie terminals, terminals that use \D in their termcap entries, or, in short, anything I felt would not affect my normal, day-to-day work with ANSI and vt100 terminals. At this point I'd recommend trying iolib.icn instead of itlibdos.icn. Iolib is largely DOS-UNIX interchangeable, and it does pretty much every- thing itlibdos.icn does.
[ Full documentation | Source code ]
This file contains itokens() - a utility for breaking Icon source files up into individual tokens. This is the sort of routine one needs to have around when implementing things like pretty printers, preprocessors, code obfuscators, etc. It would also be useful for implementing cut-down implementations of Icon written in Icon - the sort of thing one might use in an interactive tutorial. Itokens(f, x) takes, as its first argument, f, an open file, and suspends successive TOK records. TOK records contain two fields. The first field, sym, contains a string that represents the name of the next token (e.g. "CSET", "STRING", etc.). The second field, str, gives that token's literal value. E.g. the TOK for a literal semicolon is TOK("SEMICOL", ";"). For a mandatory newline, itokens would suspend TOK("SEMICOL", "\n"). Unlike Icon's own tokenizer, itokens() does not return an EOFX token on end-of-file, but rather simply fails. It also can be instructed to return syntactically meaningless newlines by passing it a nonnull second argument (e.g. itokens(infile, 1)). These meaningless newlines are returned as TOK records with a null sym field (i.e. TOK(&null, "\n")). NOTE WELL: If new reserved words or operators are added to a given implementation, the tables below will have to be altered. Note also that &keywords should be implemented on the syntactic level - not on the lexical one. As a result, a keyword like &features will be suspended as TOK("CONJUNC", "&") and TOK("IDENT", "features").
[ Full documentation | Source code ]
itrcline(f) generates lines from the file f that are Icon trace messages. It can, of course, be fooled.
[ Full documentation | Source code ]
This procedure turns a string from image() into the corresponding Icon value. It can handle integers, real numbers, strings, csets, keywords, structures, and procedures. For the image of a structure, it produces a result of the correct type and size, but any values in the structure are not likely to be correct, since they are not encoded in the image. For procedures, the procedure must be present in the environment in which ivalue() is evaluated. This generally is true for built-in procedures (functions). All keywords are supported even if image() does not produce a string of the form "&name" for them. The values produced for non-constant keywords are, of course, the values they have in the environment in which ivalue() is evaluated. ivalue() also can handle non-local variables (image() does not produce these), but they must be present in the environment in which ivalue() is evaluated.
[ Full documentation | Source code ]
jumpque(queue, y) moves y to the head of the queue if it is in queue but just adds y to the head of the queue if it is not already in the queue. A copy of queue is returned; the argument is not modified.
[ Full documentation | Source code ]
This procedure maps uppercase letters and the control modifier key in combination with letters into the corresponding lowercase letters. It is intended for use with graphic applications in which the modifier keys for shift and control are encoded in keyboard events.
[ Full documentation | Source code ]
This procedure produces a new label in sequence each time it's called. The labels consist of all possible combinations of the characters given in the argument the first time it is called. See star(s) in gener.icn for a generator that does the same thing (and much more concisely).
[ Full documentation | Source code ]
Descriptions: lastc( c, s, i1, i2 ) : i3 succeeds and produces i1, provided either - i1 is 1, or - s[i1 - 1] is in c and i2 is greater than i1 defaults: same as for any errors: same as for any findp( c, s1, s2, i1, i2 ) : i3, i4, ..., in generates the sequence of positions in s2 at which s1 occurs provided that: - s2 is preceded by a character in c, or is found at the beginning of the string i1 & i2 limit the search as in find defaults: same as for find errors: same as for find & lastc findw( c1, s1, c2, s2, i1, i2 ) : i3, i4, ..., in generates the sequence of positions in s2 at which s1 occurs provided that: - s2 is preceded by a character in c1, or is found at the beginning of the string; and - s2 is succeeded by a character in c2, or the end of the string i1 & i2 limit the search as in find defaults: same as for find errors: same as for find & lastc
[ Full documentation | Source code ]
Produces the last name of a name in conventional form. Obviously, it doesn't work for every possibility.
[ Full documentation | Source code ]
rcseval(a, c, m) evaluates the constants used in a linear congruence recurrence for generating a sequence of pseudo-random numbers. a is the multiplicative constant, c is the additive constant, and m is the modulus. Any line of output starting with asterisks indicates a problem. See Donald E. Knuth, "Random Numbers" in The Art of Computer Programming, Vol. 2, Seminumerical Algorithms, Addison-Wesley, Reading, Massachusetts, 1969, pp. 1-160.
[ Full documentation | Source code ]
The procedure levenshtein(s1, s2) returns the minimum number of edit operations needed to transform string s1 into s2. Examples: levenshtein("day", "may") produces 1 levenshtein("cat", "dog") produces 3 Now, those are easy examples, but consider: levenshtein("Saturday", "Sunday") produces 3 Yes, 3. Delete "a" and "t" from Saturday (Surday), then change the "r" to an "n", and you have Sunday!
[ Full documentation | Source code ]
lindgen() assumes a "full" mapping table; lindgenx() does not. Note that the first argument is a single character. At the top level it might be called as lindgen(!axiom, rewrite, gener)
[ Full documentation | Source code ]
Lindenmayer systems are usually are interpreted as specifications for drawing plant-like objects, fractals, or other geometric designs. This procedure illustrates that L-systems can be interpreted in other ways -- as striped patterns, for example. The procedure is called as lindstrp(prod, band_tbl) where prod is a "production" that is interpreted as being a sequence of one-character symbols, and band_tbl is a table with these symbols as keys whose corresponding values are specifications for bands of the form "color:width". An example of a table for the symbols A, B, and C is: band_tbl := table() band_tbl["A"] := "blue:3" band_tbl["B"] := "red:10" band_tbl["C"] := "black:5" With a table default of null, as above, symbols in prod that are not table keys are effectively ignored. Other table defaults can be used to produce different behaviors for such symbols. An example of a production is: "ABCBABC" The result is a string of band specifications for the striped pattern represented by prod. It can be converted to an image by using strplang.icn, but graphics are not necessary for the use of this procedure itself. One thing this procedure is useful for is developing an understanding of how to construct L-systems for specific purpose: L-systems for plant-like objects and fractals are require specialized knowledge and are difficult to construct, while stripes are simple enough for anyone to understand and develop L-systems for.
[ Full documentation | Source code ]
This procedure writes a list as a tab-separated string. Carriage returns in files are converted to vertical tabs.
[ Full documentation | Source code ]
file2lst(s) create list from lines in file imag2lst(s) convert limage() output to list l_Bscan(e1) begin list scanning l_Escan(l_OuterEnvir, e2) end list scanning l_any(l1,l2,i,j) any() for list scanning l_bal(l1,l2,l3,l,i,j bal() for list scanning l_find(l1,l2,i,j) find() for list scanning l_many(l1,l2,i,j) many() for list scanning l_match(l1,l2,i,j) match() for list scanning l_move(i) move() for list scanning l_pos(i) pos() for list scanning l_tab(i) tab() for list scanning l_upto(l1,l2,i,j) upto() for list scanning lclose(L) close open palindrome lcomb(L,i) list combinations lcompact(L) compact list, mapping out missing values ldecollate(I, L) list decollation ldelete(L, spec) list deletion ldupl(L, i) list term duplication lequiv(L1, L2) list equivalence levate(L, m, n) list elevation lextend(L, i) list extension lfliph(L) list horizontal flip (reversal) lflipv(L) list vertical flip limage(L) unadorned list image lindex(L, x) generate indices of L whose values are x lcollate(L1, L2, ...) list collation; like linterl() except stops on short list lconstant(L) succeeds and returns element if all are the same linterl(L1, L2) list interleaving llayer(L1, L2, ...) layer and interleave L1, L2, ... llpad(L, i, x) list padding at left lltrim(L, S) list left trimming lmap(L1,L2,L3) list mapping lpalin(L, x) list palindrome lpermute(L) list permutations lreflect(L, i) returns L concatenated with its reversal to produce palindrome; the values of i determine "end conditions" for the reversal: 0 omit first and last elements; default 1 omit first element 2 omit last element 3 don't omit element lremvals(L, x1, x2, ...) remove values from list lrepl(L, i) list replication lresidue(L, m, i) list residue lreverse(L) list reverse lrotate(L, i) list rotation lrpad(L, i, x) list right padding lrundown(L1, L2, L3) list run down lrunup(L1, L2, L3) list run up lrtrim(L, S) list right trimming lshift(L, i) shift list terms lst2str(L) string from concatenated values in L lswap(L) list element swap lunique(L) keep only unique list elements lmaxlen(L, p) returns the size of the largest value in L. If p is given, it is applied to each string as as a "length" procedure. The default for p is proc("*", 1). lminlen(L, p) returns the size of the smallest value in L. If p is given, it is applied to each string as as a "length" procedure. The default for p is proc("*", 1). sortkeys(L) returns list of keys from L, where L is the result of sorting a table with option 3 or 4. sortvalues(L) return list of values from L, where L is the result of sorting a table with option 3 or 4. str2lst(s, i) creates list with i-character lines from s. The default for i is 1.
[ Full documentation | Source code ]
longstr(l,s,i,j) works like any(), except that instead of taking a cset as its first argument, it takes instead a list or set of strings (l). Returns i + *x, where x is the longest string in l for which match(x,s,i,j) succeeds. Fails if no match occurs. Defaults: s &subject i &pos if s is defaulted, otherwise 1 j 0 Errors: The only manual error-checking that is done is to test l to be sure it is, in fact, a list or set. Errors such as non- string members in l, and non-integer i/j parameters, are caught by the normal Icon built-in string processing and sub- scripting mechanisms.
[ Full documentation | Source code ]
This procedure produces an approximate of an integer value in the form n.nx10^n. It is primarily useful for large integers.
[ Full documentation | Source code ]
Links: genrfncs, numbers
[ Full documentation | Source code ]
Links: numbers
[ Full documentation | Source code ]
lu_decomp(M, I) performs LU decomposition on the square matrix M using the vector I. Both M and I are modified in the process. The value returned is +1 or -1 depending on whether the number of row interchanges is even or odd. lu_decomp() is used in combination with lu_back_sub() to solve linear equations or invert matrices. lu_decomp() fails if the matrix is singular. lu_back_sub(M, I, B) solves the set of linear equations M x X = B. M is the matrix as modified by lu_decomp(). I is the index vector produced by lu_decomp(). B is the right-hand side vector and return with the solution vector. M and I are not modified by lu_back_sub() and can be used in successive calls of lu_back_sub() with different Bs.
[ Full documentation | Source code ]
These procedures coverts a list corresponding to an L-System into an L-System record. See lindsys.icn for documentation about format. See linden.dat for an example of input data. See also linden.icn for a graphics version.
[ Full documentation | Source code ]
The procedure mapbit(s) produces a string of zeros and ones corresponding to the bit patterns for the characters of s. For example, mapbit("Axe") produces "010000010111100001100101".
[ Full documentation | Source code ]
Mapstrs(s, l1, l2) works like map(), except that instead of taking ordered character sequences (strings) as arguments 2 and 3, it takes ordered string sequences (lists). Suppose, for example, you wanted to bowdlerize a string by replacing the words "hell" and "shit" with "heck" and "shoot." You would call mapstrs as follows: mapstrs(s, ["hell", "shit"], ["heck", "shoot"]) In order to achieve reasonable speed, mapstrs creates a lot of static structures, and uses some extra storage. If you want to replace one string with another, it is overkill. Just use the IPL replace() routine (in strings.icn). If l2 is longer than l1, extra members in l2 are ignored. If l1 is longer, however, strings in l1 that have no correspondent in l2 are simply deleted. Mapstr uses a longest-possible-match approach, so that replacing ["hellish", "hell"] with ["heckish", "heck"] will work as one would expect.
[ Full documentation | Source code ]
These procedures perform low-level "lexical" matching for recursive-descent pattern matchers. rb_() match right bracket lb_() match left bracket rp_() match right parenthesis lp_() match left parenthesis vb_() match vertical bar nl_() match newline empty_() match empty string
[ Full documentation | Source code ]
binocoef(n, k) produces the binomial coefficient n over k. It fails unless 0 <= k <= n. cosh(r) produces the hyperbolic cosine of r. sinh(r) produces the hyperbolic sine of r. tanh(r) produces the hyperbolic tangent of r.
[ Full documentation | Source code ]
This file contains procedures for matrix manipulation.
[ Full documentation | Source code ]
transpose_matrix(M) : L - produces a matrix R that is the transpose of M: R[j][i] = M[i][j] numeric_matrix(M) : L - produces a matrix R that is a copy of M except each element has been subjected to the numeric(x) function; if numeric fails for any element, numeric_matrix fails: R[i][j] = numeric(M[i][j]) scale_matrix(M,mult) : L - produces a new matrix R each of whose elements is mult times larger than its peer in M: R[i][j] := mult * M[i][j] scale_matrix(mult,M) : L - is a synonym for scale_matrix(M,mult). floor_matrix(M,min) : L - produces a matrix R that is a copy of M except each element is increased to min if necessary: R[i][j] := min <= M[i][j] | min floor_matrix(min,M) : L - is a synonym for floor_matrix(M,min). ceil_matrix(M,max) : L - produces a matrix R that is a copy of M except each element is increased to max if necessary: R[i][j] := max <= M[i][j] | max ceil_matrix(max,M) : L - is a synonym for ceil_matrix(M,max). sumsquares_matrix(M) : n - produces the sum of the squares of all terms in a matrix sum(for every i,j) (M[i][j])^2 sumsquaresdiff_matrix(M1,M2) : n - produces the sum of the squares of all terms in the difference between two matrices sum(for every i,j) (M1[i][j] - M2[i][j])^2 normalize_rows(M,t) : L - produce a row-scaled matrix such that, for every row i, the sum of the values in all columns is 1 R[i][j] /:= sum(for every J) M[i][J] t is a required minimum magnitude for row sums to avoid divide-by-zero errors normalize_rows(t,M) : L - synonym for normalize_rows(M,t) normalize_columns(M,t) : L - produce a column-scaled matrix such that, for every column i, the sum of the values in all rows is 1 such that their sum is 1 R[i][j] /:= sum(for every I) M[I][j] t is a required minimum magnitude for column sums to avoid divide-by-zero errors normalize_columns(t,M) : L - synonym for normalize_columns(M,t) sprintf_matrix(f,M) - produces a matrix R of strings whose elements are formatted (by the IPL sprintf routine) from the elements of M: R[i][j] := sprintf(f,M[i,j])
[ Full documentation | Source code ]
memlog(f) writes a message to file f recording the current memory usage in the string and block regions. For each, three figures are written: amount in use, amount reserved, and number of collections. memlog does not perturb the figures: it requires no allocation itself. f defaults to &output. memlog() returns the total current usage.
[ Full documentation | Source code ]
These procedures implement commonly referenced ``text-book'' recursively defined functions using memory to avoid redundant calls. acker(i, j) Ackermann's function fib(i) Fibonacci sequence q(i) "Chaotic" sequence
[ Full documentation | Source code ]
This procedure sorts tables like sort(T, i), except that the keys that are strings are sorted with case mixed. That is, keys such as "Volvo" and "voluntary" come out sorted "voluntary" followed by "Volvo" as if it were "volvo" instead (assuming ASCII). If a string appears in two case forms, as in "Volvo" and "volvo", one key is lost. At present, this procedure applies only to keys (i = 1 or 3). It could be extended to handle values (i = 2 or 3).
[ Full documentation | Source code ]
These procedures model built-in Icon functions. Their purpose is primarily pedagogical. See Icon Analyst 11, pp. 5-7.
[ Full documentation | Source code ]
This procedure converts the string s to its Morse code equivalent. The version used is known both as International Morse Code and as Continental Code, and is used by radio amateurs (hams).
[ Full documentation | Source code ]
The idea of the mset type is that no two identical data-structures can be present in a set, where identity is defined as "containing the same elements". Definitions implicit in the procedure same_value(..,..): TYPE IDENTITY TEST all types === and if this test fails... integer = real = cset, string == record all fields have same value list all elements are the same, including ordering table same keys, and every key has the same associated value set contain the same elements
[ Full documentation | Source code ]
Produces the "name prefix" from a name in standard form -- omitting any title, but picking up the first name and any initials. There are a lot more titles that should be added to this list. Obviously, it can't always produce the "correct" result.
[ Full documentation | Source code ]
Procedure s_list(L) produces a string-representation of a nested list. Procedure l_list(s) produces a nested list from s, its string representation.
[ Full documentation | Source code ]
The procedure ngrams(s, n, c, t) generates a tabulation of the n-grams in the specified string. If c is non-null, it is used as the set of characters from which n-grams are taken (other characters break n-grams). The default for c is the upper- and lowercase letters. If t is non-null, the tabulation is given in order of frequency; otherwise in alphabetical order of n-grams. For backward compatibility, the first argument may be a file, in which case, it is read to provide the string.
[ Full documentation | Source code ]
Kit of case-independent versions of Icon's built-in string-analysis procedures.
[ Full documentation | Source code ]
These procedures deal with numbers in various ways: adp(i) additive digital persistence of i adr(i) additive digital root of i (same as digred()) amean ! L returns arithmetic mean of numbers in L. ceil(r) returns nearest integer to r away from 0. commas(s) inserts commas in s to separate digits into groups of three. decimal(i, j) decimal expansion of i / j; terminates when expansion terminates or the end of a recurring period is reached. The format of the returned value is <integer>.<seq>, where <seq> is a string a decimal digits if the expansion is finite but <pre>[<recurr>] if it is not, where <pre> is a string of decimal digits (possibly empty) before the recurring part. decipos(r, i, j) positions decimal point at i in real number r in field of width j. digprod(i) product of digits of i digred(i) reduction of number by adding digits until one digit is reached. digroot(i) same as digred(). digsum(i) sum of digits in i. distseq(i, j) generates i to j in distributed order. div(i, j) produces the result of real division of i by j. fix(i, j, w, d) formats i / j as a real (floating-point) number in a field of width w with d digits to the right of the decimal point, if possible. j defaults to 1, w to 8, and d to 3. If w is less than 3 it is set to 3. If d is less than 1, it is set to 1. The function fails if j is 0 or if the number cannot be formatted. floor(r) nearest integer to r toward 0. frn(r, w, d) format real number r into a string with d digits after the decimal point; a result narrower than w characters is padded on the left with spaces. Fixed format is always used; there is no exponential notation. Defaults: w 0, d 0 gcd(i, j) returns greatest common divisor of abs(i) and abs(j). gcdl ! L returns the greatest common divisor of the integers in list L. gmean ! L returns geometric mean of numbers in L. hmean ! L returns harmonic mean of numbers in L. large(i) succeeds if i is a large integer but fails otherwise. lcm(i, j) returns the least common multiple of i and j. lcml ! L returns the least common multiple of the integers in the list L. mantissa(r) mantissa (fractional part) of r. max ! L produces maximum of numbers in L. mdp(i) multiplicative digital persistence of i mdr(i) multiplicative digital root of i min ! L produces minimum of numbers in L. mod1(i, m) residue for 1-based indexing. npalins(n) generates palindromic n-digit numbers. qmean ! L returns quadratic mean (RMS) of numbers in L. residue(i, m, j) residue for j-based indexing. roman(i) converts i to Roman numerals. round(r) returns nearest integer to r. sigma(i) synonym for digroot(i) sign(r) returns sign of r. spell(i) spells out i in American English. sum ! L sum of numbers in list L trunc(r) returns nearest integer to r toward 0 unroman(s) converts Roman numerals to integers.
[ Full documentation | Source code ]
Usage: OpenCheck() Subsequent opens and closes will write diagnostic information to &errout Useful for diagnosing situations where many files are opened and closed and there is a possibility that some files are not always being closed.
[ Full documentation | Source code ]
opnames() produces a table that maps virtual-machine instruction numbers to instruction names.
[ Full documentation | Source code ]
opsyms() produces a table that maps virtual-machine instruction numbers for operators to operator symbols. The suffixes 1 and 2 are used for symbols that have both a unary and binary meaning.
[ Full documentation | Source code ]
options(arg, optstring,errproc) removes command options from the argument list of an Icon main procedure, returning a table of option values.
[ Full documentation | Source code ]
In any number of instances (e.g. when outputting variable-length characters or fixed-length encoded strings), the programmer must fit variable and/or non-byte-sized blocks into standard 8-bit bytes. Outbits() performs this task. Pass to outbits(i, len) an integer i, and a length parameter (len), and outbits will suspend byte-sized chunks of i converted to characters (most significant bits first) until there is not enough left of i to fill up an 8-bit character. The remaining portion is stored in a buffer until outbits() is called again, at which point the buffer is combined with the new i and then output in the same manner as before. The buffer is flushed by calling outbits() with a null i argument. Note that len gives the number of bits there are in i (or at least the number of bits you want preserved; those that are discarded are the most significant ones). A trivial example of how outbits() might be used: outtext := open("some.file.name","w") l := [1,2,3,4] every writes(outtext, outbits(!l,3)) writes(outtext, outbits(&null,3)) # flush buffer List l may be reconstructed with inbits() (see inbits.icn): intext := open("some.file.name") l := [] while put(l, inbits(intext, 3)) Note that outbits() is a generator, while inbits() is not.
[ Full documentation | Source code ]
Integers written directly as strings occupy much more space than they need to. One easy way to shrink them a bit is to "pack" them, i.e. convert each decimal digit into a four-byte binary code, and pack these four-bit chunks into eight-bit characters, which can be written to a file. Interestingly, packing decimal strings in this manner lends itself to unpacking by treating each character as a base-10 integer, and then converting it to base-16. Say we have an input string "99." Pack() would convert it to an internal representation of char(16*9 + 9), i.e. char(153). Unpack would treat this char(153) representation as a base-10 integer, and convert it to base 16 (i.e. 10r153 -> 16r99). The 99 is, of course, what we started with. Note that two unpack routines are provided here: The first, by Tanaglia, utilizes convert.icn from the IPL. The second, by Goerwitz, does not. They utilize very different methods, but both amount to basically the same thing. Goerwitz's routine returns an integer, though, and has no "width" argument.
[ Full documentation | Source code ]
Procedure to condense a parse tree produced by the output of pargen.icn and produce the string that was parsed. The necessary record declaration is provided by the program with which is linked.
[ Full documentation | Source code ]
partit(i, min, max) generates, as lists, the partitions of i; that is the ways that i can be represented as a sum of positive integers with minimum and maximum values. partcount(i, min, max) returns just the number of partitions. fibpart(i) returns a list of Fibonacci numbers that is a partition of i.
[ Full documentation | Source code ]
This procedure writes numeric triangles as "carpets". The argument determines the number of rows written, default 16.
[ Full documentation | Source code ]
The procedure, when invoked by a call to PascalsTriangle(n), returns the nth row of Pascal's Triangle in list form. Pascal's Triangle is a mathematical structure in which each element of a row is the sum of the two elements directly above it. The first few levels are: Row 1: 1 Triangle stored as: [[1], 2: 1 1 [1, 1], 3: 1 2 1 [1, 2, 1], 4: 1 3 3 1 [1, 3, 3, 1], 5: 1 4 6 4 1 [1, 4, 6, 4, 1]] For example, PascalsTriangle(4) would return the list [1, 3, 3, 1]. The procedure fails if n is not an integer or if it is less than one.
[ Full documentation | Source code ]
This procedure produces a sequence of edited items, reading a source stream (from) and a stream of difference records (diffs), as generated by dif.icn. An optional parameter (rev) causes the edits to be made in reverse. This allows an old stream to be regenerated from a new stream and an appropriate stream of difference records. The original patch(1) utility was written by Larry Wall, and is used widely in the UNIX community. See also diffu.icn and patchu.icn, the utility program versions of dif.icn and patch.icn. Usage: patch(old, diff) # patch old to new via diff patch(new, diff, rev) # patch new to old via diff
[ Full documentation | Source code ]
These procedures provide procedural equivalents for most SNOBOL4 patterns and some extensions. Procedures and their pattern equivalents are: Any(s) ANY(S) Arb() ARB Arbno(p) ARBNO(P) Arbx(i) ARB(I) Bal() BAL Break(s) BREAK(S) Breakx(s) BREAKX(S) Cat(p1,p2) P1 P2 Discard(p) /P Exog(s) \S Find(s) FIND(S) Len(i) LEN(I) Limit(p,i) P \ i Locate(p) LOCATE(P) Marb() longest-first ARB Notany(s) NOTANY(S) Pos(i) POS(I) Replace(p,s) P = S Rpos(i) RPOS(I) Rtab(i) RTAB(I) Span(s) SPAN(S) String(s) S Succeed() SUCCEED Tab(i) TAB(I) Xform(f,p) F(P) The following procedures relate to the application and control of pattern matching: Apply(s,p) S ? P Mode() anchored or unanchored matching (see Anchor and Float) Anchor() &ANCHOR = 1 if Mode := Anchor Float() &ANCHOR = 0 if Mode := Float In addition to the procedures above, the following expressions can be used: p1() | p2() P1 | P2 v <- p() P . V (approximate) v := p() P $ V (approximate) fail FAIL =s S (in place of String(s)) p1() || p2() P1 P2 (in place of Cat(p1,p2)) Using this system, most SNOBOL4 patterns can be satisfactorily transliterated into Icon procedures and expressions. For example, the pattern SPAN("0123456789") $ N "H" LEN(*N) $ LIT can be transliterated into (n <- Span('0123456789')) || ="H" || (lit <- Len(n)) Concatenation of components is necessary to preserve the pattern-matching properties of SNOBOL4. Caveats: Simulating SNOBOL4 pattern matching using the procedures above is inefficient.
[ Full documentation | Source code ]
The procedure patword(s) returns a letter pattern in which each different character in s is assigned a letter. For example, patword("structural") returns "abcdebdcfg".
[ Full documentation | Source code ]
Icon procedure set to read and write HP95LX phone book (.pbk) files.
[ Full documentation | Source code ]
These procedures use co-expressions to used to model the built-in control structures of Icon and also provide new ones. AddTabbyPDCO{e, i} adds tabby to treadling sequence AllparAER{e1,e2, ...} parallel evaluation with last result used for short sequences AltPDCO{e1,e2} models e1 | e2 BinopPDCO{op,e1,e2} produces the result of applying op to e1 and e2 CFapproxPDCO{e} produce sequence of approximations for the continued-fraction sequence e ComparePDCO{e1,e2} compares result sequences of e1 and e2 ComplintPDCO{e} produces the integers not in e CondPDCO{e1,e2, ...} models the generalized Lisp conditional CumsumPDCO{e} generates the cumulative sum of the terms of e CycleparAER{e1,e2, ...} parallel evaluation with shorter sequences re-evaluated DecimatePDCO{e1, e2} "decimate" e1 by deleting e2-numbered terms (e2 is assumed to be an increasing sequence). DecimationPDCO{e} produce a decimation sequence from e1 by deleting even-valued terms and replacing odd-valued terms by their position. DecollatePDCO{e, i} decollate e according to parity of i DeltaPDCO{e1} produces the difference of the values in e1 ElevatePDCO{e1, m, n} elevate e1 mod n to n values EveryPDCO{e1,e2} models every e1 do e2 ExtendSeqPDCO{e1,i} extends e1 to i results ExtractAER{e1,e2, ...} extract results of even-numbered arguments according to odd-numbered values FifoAER{e1,e2, ...} reversal of lifo evaluation FriendlyPDCO{m, k, e3} friendly sequence starting at k shaft mod m GaltPDCO{e1,e2, ...} produces the results of concatenating the sequences for e1, e2, ... GconjPDCO{e1,e2,...} models generalized conjunction: e1 & e2 & ... The programmer-defined control operation above shows an interesting technique for modeling conjunction via recursive generative procedures. HistoPDCO{e,i} generates histogram for e limited to i terms; default 100. IncreasingPDCO{e} filters out non-increasing values in integer sequence IndexPDCO{e1,e2} produce e2-th terms from e1 InterPDCO{e1,e2, ...} produces results of e1, e2, ... alternately LcondPDCO{e1,e2, ...} models the Lisp conditional LengthPDCO{e} returns the length of e LifoAER{e1,e2, ...} models standard Icon "lifo" evaluation LimitPDCO{e1,e2} models e1 \ e2 ListPDCO{e,i} produces a list of the first i results from e LowerTrimPDCO{e} lower trim MapPDCO{e1,e2} maps values of e1 in the order they first appear to values of e2 (as needed) OddEven{e} forces odd/even sequence PalinPDCO{e} x produces results of concatenating the sequences for e and then its reverse. ParallelPDCO{e1,e2, ...} synonym for InterPDCO{e1, e2, ...} ParallelAER{e1,e2, ...} parallel evaluation terminating on shortest sequence PatternPalinPDCO{e, i} produces pattern palindrome. If i is given, e is truncated to length i. PeriodPDCO{e, i} generates the periodic part of e; i values are used to find the period PermutePDCO{e1,e2} permutes each n-subsequence of e1 by the n positional values in lists from e2. If a list does not consist of all the integers in the range 1 to n, "interesting" things happen (see the use of map() for transpositions). PivotPDCO{e, m} produces pivot points from e % m; m default 100 PosDiffPDCO{e1,e2} produces positions at which e1 and e2 differ PositionsPDCO{e, i} generates the positions at which i occurs in e. RandomPDCO{e1,e2, ...} produces results of e1, e2, ... at random ReducePDCO{op, x, e} "reduces" the sequence e by starting with the value x and repetitively applying op to the current value and values from e. RemoveDuplPDCO{e} removes duplicate adjacent values. RepaltPDCO{e} models |e RepeatPDCO{e1, e2} repeats the sequence for e1 e2 times ReplPDCO{e1,e2} replicates each value in e1 by the corresponding integer value in e2. ResumePDCO{e1,e2,e3} models every e1 \ e2 do e3 ReversePDCO{e, i} produces the results of e in reverse order. If i is given, e is truncated to i values. RotatePDCO(e, i) rotates the sequence for e left by i; negative i rotates to the right SelfreplPDCO{e1,i} produces e1 * i copies of e1 SeqlistPDCO{e1, i} produce list with first i values of e1; i defaults to all values SimpleAER{e1,e2, ...} simple evaluation with only success or failure SkipPDCO{e1,e2} generate e1 skipping each e2 terms SmodPDCO{e1,e2} reduce terms in e1 (shaft) modulus e2 SpanPDCO{e,m} fill in between consecutive (integer) values in e % m; m default 100 SumlimitPDCO{e, i, j} produces values of e until their sum exceeds i. Values less than j are discarded. TrinopPDCO{op,e2,e2,e3} produces the result of applying op to e1, e2, and e3 UndulantPDCO{e} produces the undulant for e. UniquePDCO{e} produces the unique results of e in the order they first appear UnopPDCO{e1,e2} produces the result of applying e1 to e2 UpperTrimPDCO{e} upper trim ValrptPDCO{e1,e2} synonym for ReplPDCO WobblePDCO{e} produces e(1), e(2), e(1), e(2), e(3), e(2), ... Comments: Because of the handling of the scope of local identifiers in co-expressions, expressions in programmer-defined control operations cannot communicate through local identifiers. Some constructions, such as break and return, cannot be used in argu- ments to programmer-defined control operations.
[ Full documentation | Source code ]
Sqrt(i, j) produces a rational approximation to the square root of i with j iterations of the half-way method. j defaults to 5.
[ Full documentation | Source code ]
Links: lists, seqops
[ Full documentation | Source code ]
This procedure generates the letter combinations corresponding to the digits in a telephone number. Warning: The number of possibilities is very large. This procedure should be used in a context that limits or filters its output.
[ Full documentation | Source code ]
This procedure produces the plural form of a singular English noun. The procedure here is rudimentary and does not work in all cases.
[ Full documentation | Source code ]
The format for strings omits symbols for multiplication and exponentiation. For example, 3*a^2 is entered as 3a2. A polynomial is represented by a table in which each term, such as 3xy, the xy is # a key and the corresponding value is the coefficient, 3 in this case. If a variable is raised to a power, such as x^3, the key is the product of the individual variables, xxx in this case.
[ Full documentation | Source code ]
The procedure poly2seq(str) generates the Dietz sequence for the polynomial str. See Ada Dietz, "Algebraic Expressions in Handweaving".
[ Full documentation | Source code ]
These procedures are for creating and performing operations on single- variable polynomials (like ax^2 + bx + c). poly (c1, e1, c2, e2, ...) - creates a polynomial from the parameters given as coefficient-exponent pairs: c1x^e1 + c2x^e2 + ... is_zero (n) - determines if n = 0 is_zero_poly (p) - determines if a given polynomial is 0x^0 poly_add (p1, p2) - returns the sum of two polynomials poly_sub (p1, p2) - returns the difference of p1 - p2 poly_mul (p1, p2) - returns the product of two polynomials poly_eval (p, x) - finds the value of polynomial p when evaluated at the given x. term2string (c, e) - converts one coefficient-exponent pair into a string. poly_string (p) - returns the string representation of an entire polynomial.
[ Full documentation | Source code ]
Contents: popen(command, mode) mode == "w" writes to a pipe mode == "r" reads from a pipe pclose(pipe) On systems without real pipes (ms-dos), popen and pclose imitate pipes; pclose must be called after popen. The code should run faster on ms-dos if dir in tempfile() points to a directory on a virtual disk. On systems with real pipes, popen & pclose open and close a pipe.
[ Full documentation | Source code ]
These procedures manipulate priority queues. pq(L) returns a priority queue containing the elements in L. L is a list (or table or set) of pqelem records, each containing a data and priority field. If L is &null, pq() returns an empty priority queue. pqget(Q) returns and removes the highest priority element from Q. Q is a priority queue returned by pq(). pqput(Q, e) adds element e (a pqelem record) to Q. pqgen(Q) generates the elements in Q in priority order. pqelem(d, p) constructs a record with data d and priority p.
[ Full documentation | Source code ]
This procedure deals with with the problem of printing tabular data where the total width of items to be printed is wider than the page. Simply allowing the data to wrap to additional lines often produces marginally readable output. This procedure facil- itates printing such groups of data as vertical columns down the page length, instead of as horizontal rows across the page. That way many, many fields can be printed neatly. The programming of such a transformation can be a nuisance. This procedure does much of the work for you, like deciding how many items can fit across the page width and ensuring that entire items will be printed on the same page without page breaks (if that service is requested).
[ Full documentation | Source code ]
This procedure behaves somewhat like the standard printf. Supports d, e, s, o, and x formats like printf. An "r" format prints real numbers in a manner similar to that of printf's "f". Though "e" differs from printf in some details, it always produces exponential format. Left or right justification and field width control are provided as in printf. %s, %r, and %e handle precision specifications.
[ Full documentation | Source code ]
prockind(p) produces a code for the kind of the procedure p as follows: "p" (declared) procedure "f" (built-in) function "o" operator "c" record constructor It fails if p is not of type procedure.
[ Full documentation | Source code ]
procname(p, x) produces the name of a procedure from a procedure value. Here, the term "procedure" includes functions, operators, and record constructors. If x is null, the result is derived from image() is a relatively straightforward way. In the case of operators, the number of arguments is appended to the operator symbol. If x is nonnull, the result is put in a form that resembles an Icon expression. procname() fails if p is not of type procedure.
[ Full documentation | Source code ]
This procedure creates an array with one element for each program token. The program is read from file. The initial value of each element is value.
[ Full documentation | Source code ]
This file contains procedures for writing PostScript output explicitly, as contrasted with the procedures in psrecord.icn that write PostScript as a side effect of normal graphics calls. epsheader(f, x, y, w, h, flags) writes an Encapsulated PostScript file header and initializes the PostScript coordinate system. psprotect(s) adds escapes to protect characters that are special in PostScript strings, notably parentheses and backslash.
[ Full documentation | Source code ]
These procedures provide various operations on 3-dimensional objects in 3-space.
[ Full documentation | Source code ]
This file contains procedures related to pseudo-random numbers. choose(k, n) produces a set of k distinct integers in [1..n] rand_num() is a linear congruential pseudo-random number generator. Each time it is called, it produces another number in the sequence and also assigns it to the global variable random. With no arguments, rand_num() produces the same sequence(s) as Icon's built-in random-number generator. Arguments can be used to get different sequences. The global variable random serves the same role that &random does for Icon's built-in random number generator. rand_int(i) produces a randomly selected integer in the range 1 to i. It models ?i for positive i. randomize() sets &random to a "random" value, using /dev/urandom if available, otherwise based on the date and time. randrange(min, max) produces random number in the range min <= i <= max. randrangeseq(i, j) generates the integers from i to j in random order. randseq(seed) generates the values of &random, starting at seed, that occur as the result of using ?x. rng(a, c, m, x) generates a sequence of numbers using the linear congruence method. With appropriate parameters, the result is a pseudo-random sequence. The default values produce the sequence used in Icon. shuffle(x) shuffles the elements of x
[ Full documentation | Source code ]
These procedures perform arithmetic on rational numbers (fractions): addrat(r1,r2) Add rational numbers r1 and r2. divrat(r1,r2) Divide rational numbers r1 and r2. medrat(r1,r2) Form mediant of r1 and r2. mpyrat(r1,r2) Multiply rational numbers r1 and r2. negrat(r) Produce negative of rational number r. rat2real(r) Produce floating-point approximation of r rat2str(r) Convert the rational number r to its string representation. real2rat(v,p) Convert real to rational with precision p. The default precision is 1e-10. (Too much precision gives huge, ugly factions.) reciprat(r) Produce the reciprocal of rational number r. str2rat(s) Convert the string representation of a rational number (such as "3/2") to a rational number. subrat(r1,r2) Subtract rational numbers r1 and r2.
[ Full documentation | Source code ]
This procedure reads a "carpet" file and returns a corresponding matrix.
[ Full documentation | Source code ]
This file is part of the strpsgml package. It does the job of read- ing option user-created mapping information from a file. The purpose of this file is to specify how each code in a given input text should be translated. Each line has the form: SGML-designator start_code end_code where the SGML designator is something like "quote" (without the quota- tion marks), and the start and end codes are the way in which you want the beginning and end of a <quote>...<\quote> sequence to be transla- ted. Presumably, in this instance, your codes would indicate some set level of indentation, and perhaps a font change. If you don't have an end code for a particular SGML designator, just leave it blank.
[ Full documentation | Source code ]
Descriptions: ReAssign( s ) : s2 Replaces sequences of \n in s with the corresponding parenthesis groups from the last regular expression match/find (if one exists). Special characters: \n use nth parenthesis group \\ escaped \ \n.i nth group followed by a number
[ Full documentation | Source code ]
This procedure writes fields of a record as tab-separated string. Carriage returns in files are converted to vertical tabs. (Works for lists too.)
[ Full documentation | Source code ]
This procedure serves as a main procedure for the output of recognizers.
[ Full documentation | Source code ]
field(R, i) returns the name of the ith field of R. fieldnum(R, s) returns the index of the field named s in record R. movecorr(R1, R2) copies values from the fields of record R1 into fields of the same names (if any) in record R2, and returns R2.
[ Full documentation | Source code ]
These procedures implement commonly referenced ``text-book'' recursively defined functions. acker(i, j) Ackermann's function fib(i) Fibonacci sequence g(k, i) generalized Hofstader nested recurrence q(i) chaotic sequence
[ Full documentation | Source code ]
This procedure maps a recurrence declaration of the form f(i): if expr11 then expr12 if expr21 then expr22 ... else expr The declaration if passed to recurmap() in the form of a list. The result is returned as a string constituting an Icon procedure declaration. into an Icon procedure that compute corresponding values. At present there is no error checking and the most naive form of code is generated.
[ Full documentation | Source code ]
reduce(op, init, args[]) applies the binary operation op to all the values in args, using init as the initial value. For example, reduce("+", 1, args[]) produces the sum of the values in args.
[ Full documentation | Source code ]
This is a kit of procedures to deal with UNIX-like regular expression patterns. These procedures are interesting partly because of the "recursive suspension" (or "suspensive recursion" :-) technique used to simulate conjunction of an arbitrary number of computed expressions (see notes, below). The public procedures are: ReMatch(pattern,s,i1,i2) : i3,i4,...,iN ReFind(pattern,s,i1,i2) : i3,i4,...,iN RePat(s) : pattern list
[ Full documentation | Source code ]
This procedure returns the length of the smallest range of values that repeat in a list. For example, if L := [1, 2, 3, 1, 2, 3, 1, 2, 3] repetit(L) returns 3. If there is no repetition, repetit() returns the length of the list.
[ Full documentation | Source code ]
This procedure is designed to help explore the number-theory problem in which an integer is added to its (digit) reversal until a palindrome appears. It is unknown if this process terminates for all integers. For example, for 196, it appears not to, but no proof, to our knowledge, exists for nontermination. The radix used is important. For bases that are powers of 2, it can be proved that there are integers for which the process does not terminate in a palindrome.
[ Full documentation | Source code ]
The procedure rewrap(s,i), included in this file, reformats text fed to it into strings < i in length. Rewrap utilizes a static buffer, so it can be called repeatedly with different s arguments, and still produce homogenous output. This buffer is flushed by calling rewrap with a null first argument. The default for argument 2 (i) is 70.
[ Full documentation | Source code ]
This procedure generates a sequence of numbers using the linear congruence method. With appropriate parameters, the result is a pseudo-random sequence. The default values produce the sequence used in Icon.
[ Full documentation | Source code ]
This program is designed to be linked with the output of the meta- translator. These procedures produce "evaluation sandwiches" so that program execution can be monitored. See "Evaluation Sandwiches", Icon Analyst 6, pp. 8-10, 1991.
[ Full documentation | Source code ]
This module contains procedures related to string scanning: balq(c1, c2, c3, c4, c5, s, i1, i2) like bal() with quoting from characters in c5. balqc(c1, c2, c3, c4, c5, s1, s2, s3, i1, i2) like balq() with the addition that balanced characters within "comments", as delimited by the strings s1 and s2, are also excluded from balancing. In addition, if s1 is given and s2 limatch(L, c) matches items in list L delimited by characters in c slashbal(c1, c2, c3, s, i, j) like bal() with escape processing slashupto(c, s, i, j) like upto() with escape processing slshupto() synonym for slashupto() snapshot(title, len) snapshot of string scanning with optional title and maximum length. More extensive documentation proceeds each procedure.
[ Full documentation | Source code ]
These procedures model string scanning: e1 ? e2 -> Escan(Bscan(e1, e2) See Icon Analyst 6, pp. 1-2.
[ Full documentation | Source code ]
Procedure to set up for user-written string-scanning procedures that are in the spirit of Icon's built-ins. The values passed are the s, i1, i2 parameters which are the last three arguments to all Icon scanning functions (such as upto(c,s,i1,i2)). scan_setup() supplies any appropriate defaults and returns needed values. The value returned is a "scan_setup_result" record consisting of two values: 1. The substring of s to be scanned (ss). 2. The size of the substring of s that precedes the substring to be scanned (offset). scan_setup() fails if i1 or i2 is out of range with respect to s. The user-written procedure can then match in the string ss to compute the position within ss appropriate to the scan (p). The value returned (or suspended) to the caller is p + offset (the position within the original string, s). For example, the following function finds two words separated by spaces: procedure two_words(s,i1,i2) local x,p x := scan_setup(s,i1,i2) | fail # fail if out of range x.ss ? suspend { tab(upto(&letters)) & pos(1) | (move(-1) & tab(any(~&letters))) & p := &pos & # remember starting position tab(many(&letters)) & tab(many(' ')) & tab(many(&letters)) & p + x.offset # return position in original s } end
[ Full documentation | Source code ]
These procedures segment a string s into consecutive substrings consisting of characters that respectively do/do not occur in c. segment(s,c) generates the substrings, while seglist produces a list of the segments. For example, segment("Not a sentence.",&letters) generates "Not" " " "a" " " "sentence" "." while seglist("Not a sentence.",&letters) produces ["Not"," ","a","sentence","."]
[ Full documentation | Source code ]
sentence(f) generates the English sentences encountered in a file.
[ Full documentation | Source code ]
sentence(f) - suspends sentences from file f A lot of grammatical and stylistic analysis programs are predicated on the notion of a sentence. For instance, some programs count the number of words in each sentence. Other count the number and length of clauses. Still others pedantically check for sentence-final par- ticles and prepositions. This procedure, sentence(), is supposed to be used as a filter for ASCII text files, suspending everything that looks remotely like a sentence in them.
[ Full documentation | Source code ]
Links: genrfncs, lterps, math, numbers, partit, pdco, seqops, strings, convert
[ Full documentation | Source code ]
The procedure Seqimage{e,i,j} produces a string image of the result sequence for the expression e. The first i results are printed. If i is omitted, there is no limit. If there are more than i results for e, ellipses are provided in the image after the first i. If j is specified, at most j results from the end of the sequence are printed after the ellipses. If j is omitted, only the first i results are produced. For example, the expressions Seqimage{1 to 12} Seqimage{1 to 12,10} Seqimage{1 to 12,6,3} produce, respectively, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12} {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...} {1, 2, 3, 4, 5, 6, ..., 10, 11, 12} Warning: If j is not omitted and e has an infinite result sequence, Seqimage{} does not terminate.
[ Full documentation | Source code ]
These procedures perform operations related to T-Sequences and to analyze T-Sequences.
[ Full documentation | Source code ]
Procedure to return the serial number of a structure.
[ Full documentation | Source code ]
sername(p, s, n, i) produces a series of names of the form p<nnn>s. If n is given it determines the number of digits in <nnn>. If i is given it resets the sequence to start with i. <nnn> is an right-adjusted integer padded with zeros. Ordinarily, the arguments only are given on the first call. Subsequent calls without arguments give the next name. For example, sername("image", ".gif", 3, 0) produces "image000.gif", and subsequently, sername() produces "image001.gif", image002.gif", and so on. The defaults, if sername() is first called without any arguments is as for the call sername("file", 3, 0, ""). If any argument changes on subsequent calls, all non-null arguments are reset.
[ Full documentation | Source code ]
cset2set(c) returns a set that contains the individual characters in cset c. domain(T) returns the domain of the function defined by the table T. inverse(T, x) returns the inverse of the function defined by the table T. If x is null, it's the functional inverse. If x is an empty list, it's the relational inverse. If x is an empty set, it the relational inverse, but with each table member as a set instead of a list. pairset(T) converts the table T to an equivalent set of ordered pairs. range(T) returns the range of the function defined by the table T. seteq(S1, S2) tests equivalence of sets S1 and S2. setlt(S1, S2) tests inclusion of set S1 in S2. simage(S) string image of set
[ Full documentation | Source code ]
showtbl(title, tbl, sort_type, limit, sort_order, posit, w1, w2, gutter, f1, f2) displays tbl according to the arguments given. The arguments are: position name meaning default/alternative 1 title heading title "" 2 tbl table to be shown 3 sort_type type of sorting "ref"/"val" 4 limit lines of table output essentially infinite 5 sort_order increasing/decreasing "incr"/"decr" 6 posit first column "val"/"ref" 7 w1 width of 1st column 10 8 w2 width of 2nd column 10 9 gutter width between columns 3 10 f1 function of 1st column left 11 f2 function of 2nd column right showtbl() returns a record with the first element being a count of the size of the table and the second element the number of lines written.
[ Full documentation | Source code ]
The following procedures are useful for writing Icon programs that generate shell commands. Certain characters cannot appear in the open in strings that are to be interpreted as "words" by command shells. This family of procedures assists in quoting such strings so that they will be interpreted as single words. Quoting characters are applied only if necessary -- if strings need no quoting they are returned unchanged. shquote(s1, s2, ..., sN) : s -- Produces a string of words s1, s2, ..., sN that are properly separated and quoted for the Bourne Shell (sh). cshquote(s1, s2, ..., sN) : s -- Produces a string of words s1, s2, ..., sN that are properly separated and quoted for the C-Shell (csh). mpwquote(s1, s2, ..., sN) : s -- Produces a string of words s1, s2, ..., sN that are properly separated and quoted for the Macintosh Programmer's Workshop shell (MPW Shell). dequote(s1,s2) : s3 -- Produces the UNIX-style command line word s1 with any quoting characters removed. s2 is the escape character required by the shell (s2 defaults the the usual UNIX escape character, the backslash "\\").
[ Full documentation | Source code ]
signed(s,n) -- Puts raw bits of characters of string s into an integer. The value is taken as signed. If large integers are supported, this routine will work for integers of arbitrary size. If large integers are not supported, the following are true: If the size of s is the same as or greater than the size of an integer in the Icon implementation, the result will be negative or positive depending on the value of the integer's sign bit. If the size of s is less than the size of an integer, the bytes are put into the low order part of the integer, with the remaining high order bytes filled with sign bits (the high order bit of the first character of the string). If the string is too large, the most significant bytes will be lost. This procedure is normally used for processing of binary data read from a file.
[ Full documentation | Source code ]
isort(x, p) customized sort in which procedure p is used for comparison. sortff(L, fields[]) like sortf(), except takes an unlimited number of field arguments. sortgen(T, m) generates sorted output in a manner specified by m: "k+" sort by key in ascending order "k-" sort by key in descending order "v+" sort by value in ascending order "v-" sort by value in descending order sortt(T, i) like sort(T, i) but produces a list of two-element records instead of a list of two-element lists.
[ Full documentation | Source code ]
This program sorts a table in the manner of sort(T, i) but produces a list of two-element records instead of a list of two-element lists
[ Full documentation | Source code ]
This procedure produces a code for a name that tends to bring together variant spellings. See Donald E. Knuth, The Art of Computer Programming, Vol.3; Searching and Sorting, pp. 391-392.
[ Full documentation | Source code ]
When names are communicated by telephone, they are often transcribed incorrectly. An organization that has to keep track of a lot of names has a need, therefore, for some system of representing or encoding a name that will mitigate the effects of transcription errors. One idea, originally proposed by Margaret K. Odell and Robert C. Russell, uses the following encoding system to try to bring together occurrences of the same surname, variously spelled: Encode each of the letters of the name according to the following equivalences: a, e, h, i, o, u, w, y -> * b, f, p, v -> 1 c, g, j, k, q, s, x, z -> 2 d, t -> 3 l -> 4 m, n -> 5 r -> 6 If any two adjacent letters have the same code, change the code for the second one to *. The Soundex representation consists of four characters: the initial letter of the name, and the first three digit (non-asterisk) codes corresponding to letters after the initial. If there are fewer than three such digit codes, use all that there are, and add zeroes at the end to make up the four-character representation.
[ Full documentation | Source code ]
speedo -- a "percentage complete" graphic indicator for command-line-oriented user interfaces. This is a general facility that can function for anything, and a specific implementation for input files. The general implementation consists of two procedures: SpeedoNew -- Starts a speedo SpeedoValue -- Sets a new value for the speedo (non-decreasing) See FileSpeedo for an example of using the general facility. FileSpeedo is especially for input files. Here is how to use it, by example: f := open("input_file") | stop("!!!") FileSpeedo(f,75,&errout) # Start a file speedo, specifying # length and output file while read(f) do { FileSpeedo(f) # Keep it updated while reading file ... } FileSpeedo() # Finish up
[ Full documentation | Source code ]
This little procedure came from a discussion about how to produce a spinning cursor. The argument, if supplied, limits the number of cycles.
[ Full documentation | Source code ]
This procedure produces a "two-way" table to map state names (in the postal sense) to their postal abbreviations and vice-versa. The list is done in two parts with auxiliary procedures so that this procedure can be used with the default constant-table size for the translator and linker.
[ Full documentation | Source code ]
step(r1, r2, r3) generates real values from r1 to r2 in increments of r3 (default 1.0). It is the real equivalent of i to j by k. If r2 is null, the sequence is infinite and is the real equivalent of seq(). Beware the usual problems of floating-point precision.
[ Full documentation | Source code ]
str2toks: cset x string x integer x integer -> strings (c, s, i, j) -> s1, s2, ... Suspends portions of s[i:j] delimited by characters in c. The usual defaults for s, i, and j apply, although str2toks is not meant as a primitive scanning function (note that it suspends strings, and not integer positions). Defaults: c ~(&letters ++ &digits) s &subject i &pos if s is defaulted, otherwise 1 j 0 Basically, this file is just a very simple piece of code wrapped up with some sensible defaults, and isolated in its own procedure.
[ Full documentation | Source code ]
These procedures perform operations on strings. cat(s1, s2, ...) concatenates an arbitrary number of strings. charcnt(s, c) returns the number of instances of characters in c in s. collate(s1, s2) collates the characters of s1 and s2. For example, collate("abc", "def") produces "adbecf". comb(s, i) generates the combinations of characters from s taken i at a time. compress(s, c) compresses consecutive occurrences of charac- ters in c that occur in s; c defaults to &cset. coprefix(s1, s2, ...) produces the common prefix of its arguments: the longest initial substring shared by all, which may be the empty string. cosuffix(s1, s2, ...) produces the common suffix of its arguments: the longest trailing substring shared by all, which may be the empty string. csort(s) produces the characters of s in lexical order. decollate(s, i) produces a string consisting of every other character of s. If i is odd, the odd-numbered characters are selected, while if i is even, the even-numbered characters are selected. The default value of i is 1. deletec(s, c) deletes occurrences of characters in c from s. deletep(s, L) deletes all characters at positions specified in L. deletes(s1, s2) deletes occurrences of s2 in s1. diffcnt(s) returns count of the number of different characters in s. extend(s, n) replicates s to length n. fchars(s) returns characters of s in order of decreasing frequency interleave(s1, s2) interleaves characters s2 extended to the length of s1 with s1. ispal(s) succeeds and returns s if s is a palindrome maxlen(L, p) returns the length of the longest string in L. If p is given, it is applied to each string as as a "length" procedure. The default for p is proc("*", 1). meander(s, n) produces a "meandering" string that contains all n-tuples of characters of s. multicoll(L) returns the collation of the strings in L. ochars(s) produces the unique characters of s in the order that they first appear in s. odd_even(s) inserts values in a numerical string so that adjacent digits follow an odd-even pattern. palins(s, n) generates all the n-character palindromes from the characters in s. permutes(s) generates all the permutations of the string s. pretrim(s, c) trims characters from beginning of s. reflect(s1, i, s2) returns s1 concatenated s2 and the reversal of s1 to produce a palindroid; the values of i determine "end conditions" for the reversal: 0 pattern palindrome; the default 1 pattern palindrome with center duplicated 2 true palindrome with center not duplicated 3 true palindrome with center duplicated s2 defaults to the empty string, in which case the result is a full palindrome replace(s1, s2, s3) replaces all occurrences of s2 in s1 by s3; fails if s2 is null. replacem(s, ...) performs multiple replacements in the style of of replace(), where multiple argument pairs may be given, as in replacem(s, "a", "bc", "d", "cd") which replaced all "a"s by "bc"s and all "d"s by "cd"s. Replacements are performed one after another, not in parallel. replc(s, L) replicates each character of c by the amount given by the values in L. rotate(s, i) rotates s i characters to the left (negative i produces rotation to the right); the default value of i is 1. schars(s) produces the unique characters of s in lexical order. scramble(s) scrambles (shuffles) the characters of s randomly. selectp(s, L) selects characters of s that are at positions given in L. slugs(s, n, c) generates column-sized chunks (length <= n) of string s broken at spans of cset c. Defaults: n 80 c ' \t\r\n\v\f' Example: every write("> ", slugs(msg, 50)) starseq(s) sequence consisting of the closure of s starting with the empty string and continuing in lexical order as given in s strcnt(s1, s2) produces a count of the number of non-overlapping times s1 occurs in s2; fails is s1 is null substrings(s, i, j) generates all the substrings of s with lengths from i to j, inclusive; i defaults to 1, j to *s transpose(s1, s2, s3) transposes s1 according to label s2 and transposition s3. words(s, c) generates the "words" from the string s that are separated by characters from the cset c, which defaults to ' \t\r\n\v\f'.
[ Full documentation | Source code ]
strip(s,c) - strip characters c from string s
[ Full documentation | Source code ]
Strip commented-out portion of a line of Icon code. Fails on lines which, either stripped or otherwise, come out as an empty string.
[ Full documentation | Source code ]
This routine strips material from a line which is unbalanced with respect to the characters defined in arguments 1 and 2 (unbalanced being defined as bal() defines it, except that characters preceded by a backslash are counted as regular characters, and are not taken into account by the balancing algorithm). One little bit of weirdness I added in is a table argument. Put simply, if you call stripunb() as follows, stripunb('<','>',s,&null,&null,t) and if t is a table having the form, key: "bold" value: outstr("\e[2m", "\e1m") key: "underline" value: outstr("\e[4m", "\e1m") etc. then every instance of "<bold>" in string s will be mapped to "\e2m," and every instance of "</bold>" will be mapped to "\e[1m." Values in table t must be records of type output(on, off). When "</>" is encountered, stripunb will output the .off value for the preceding .on string encountered.
[ Full documentation | Source code ]
This procedure to takes tab-separated strings and inserts them into a list. Vertical tabs in strings are converted to carriage returns. (Works for lists too.)
[ Full documentation | Source code ]
This procedure to takes tab-separated strings and inserts them into fields of a record. Vertical tabs in strings are converted to carriage returns. (Works for lists too.)
[ Full documentation | Source code ]
keylist(T) produces list of keys in table T. kvallist(T) produces values in T ordered by sorted order of keys. tbleq(T1, T2) tests equivalences of tables T1 amd T2. tblunion(T1, T2) approximates T1 ++ T2. tblinter(T1, T2) approximates T1 ** T2. tbldiff(T1, T2) approximates T1 -- T2. tblinvrt(T) produces a table whose keys are T's values and whose values are T's keys. tbldflt(T) produces the default value for T. twt(T) produces a two-way table based on T. vallist(T) produces list of values in table T.
[ Full documentation | Source code ]
tclass(x) returns "atomic" or "composite" depending on the type of x.
[ Full documentation | Source code ]
This procedure produces the "title" of a name, as "Mr." from "Mr. John Doe". The process is imperfect.
[ Full documentation | Source code ]
This procedure produces a set of strings that commonly appear as titles in names. This set is (necessarily) incomplete.
[ Full documentation | Source code ]
These procedures are for use with code produced by a meta-translator. The result of linking these procedures with a program translated by standard the meta-translator and executing the result is a tabulation of the tokens in the program.
[ Full documentation | Source code ]
depth(t) compute maximum depth of tree t ldag(s) construct a dag from the string s ltree(s) construct a tree from the string s stree(t) construct a string from the tree t tcopy(t) copy tree t teq(t1,t2) compare trees t1 and t2 visit(t) visit, in preorder, the nodes of the tree t
[ Full documentation | Source code ]
This procedure implements a "tuple" feature that produces the effect of multiple keys. A tuple is created by an expression of the form tuple([exrp1, expr2, ..., exprn]) The result can be used in a case expression or as a table subscript. Lookup is successful provided the values of expr1, expr2, ..., exprn are the same (even if the lists containing them are not). For example, consider selecting an operation based on the types of two operands. The expression case [type(op1), type(op2)] of { ["integer", "integer"]: op1 + op2 ["string", "integer"] : op1 || "+" || op2 ["integer", "string"] : op1 || "+" || op2 ["string", "string"] : op1 || "+" || op2 } does not work, because the comparison in the case clauses compares lists values, which cannot be the same as control expression, because the lists are different, even though their contents are the same. With tuples, however, the comparison succeeds, as in case tuple([type(op1), type(op2)]) of { tuple(["integer", "integer"]): op1 + op2 tuple(["string", "integer"]) : op1 || "+" || op2 tuple(["integer", "string"]) : op1 || "+" || op2 tuple(["string", "string"]) : op1 || "+" || op2 }
[ Full documentation | Source code ]
typecode(x) produces a one-letter string identifying the type of its argument. In most cases, the code is the first (lowercase) letter of the type, as "i" for the integer type. Structure types are in uppercase, as "L" for the list type. All records have the code "R". The code "C" is used for the co-expression type to avoid conflict for the "c" for the cset type. In the case of graphics, "w" is produced for windows.
[ Full documentation | Source code ]
unsigned() -- Puts raw bits of characters of string s into an integer. The value is taken as unsigned. If large integers are supported, this routine will work for integers of arbitrary size. If large integers are not supported, the following are true: If the size of s is the same as or greater than the size of an integer in the Icon implementation, the result will be negative or positive depending on the value of the integer's sign bit. If the size of s is less than the size of an integer, the bytes are put into the low order part of the integer, with the remaining high order bytes filled with zero. If the string is too large, the most significant bytes will be lost. This procedure is normally used for processing of binary data read from a file.
[ Full documentation | Source code ]
These procedures provide various common services: Usage(s) stops executions with a message concerning the expected form of usage of a program. Error(L[]) writes arguments to &errout and returns. ErrorCheck(l,f) reports an error that has been converted to failure. Feature(s) succeeds if feature s is available in the running implementation of Icon. Requires(s) terminates execution is feature s is not available. Signature() writes the version, host, and features support in the running implementation of Icon.
[ Full documentation | Source code ]
Variable values are obtained from the supplied procedure, "varProc", which returns the value of its variable-name argument or fails if there is no such variable. "varProc" defaults to the procedure, "getenv". As with the UNIX Bourne shell and C shell, variable names are preceded by $. Optionally, the variable name can additionally be surrounded by curly braces {}, which is usually done when necessary to isolate the variable name from surrounding text. As with the C-shell, the special symbol ~<username> is handled. Username can be omitted, in which case the value of the variable "HOME" is substituted. If username is supplied, the /etc/passwd file is searched to supply the home directory of username (this action is obviously not portable to non-UNIX environments).
[ Full documentation | Source code ]
This procedure produces an approximation to the number of n-digit versum numbers, using a recurrence described in "Versum Numbers" in Icon Analyst 35.
[ Full documentation | Source code ]
This procedure produces the version number of Icon on which a program is running. It only works if the &version is in the standard form.
[ Full documentation | Source code ]
vhttp(url) validates a URL (a World Wide Web link) of HTTP: form by sending a request to the specified Web server. It returns a string containing a status code and message. If the URL is not in the proper form, or if it does not specify the HTTP: protocol, vhttp fails.
[ Full documentation | Source code ]
This file contains procedures for producing VRML files. point_field(L) create VRML point field from point list L u_crd_idx(i) create VRML coordinate index for 0 through i - 1 render(x) render node x vrml1(x) produces VRML 1.0 file for node x vrml2(x) produces VRML 2.0 file for node x vrml_color(s) convert Icon color specification to vrml form Notes: Not all node types have been tested. Where field values are complex, as in vectors, these must be built separately as strings to go in the appropriate fields. There is no error checking. Fields must be given in the order they appear in the node record declarations and field values must be of the correct type and form. The introduction of record types other than for nodes will cause bogus output. A structural loop will produce output until the evaluation stack overflows.
[ Full documentation | Source code ]
This file contains record declarations for VRML 1.0 nodes. Note: Although VRML 1.0 allows node fields to be given in any order, they must be specified in the order given in the record declarations that follow. Omitted (null-valued) fields are ignored on output. Group nodes require list arguments for lists of nodes.
[ Full documentation | Source code ]
This file contains record declarations for VRML 2.0 nodes. Note: Although VRML 2.0 allows node fields to be given in any order, they must be specified in the order given in the record declarations that follow. Group nodes require list arguments for lists of nodes.
[ Full documentation | Source code ]
widag(s1, s2, ...) writes the values of the global variables named s1, s2, ... with s1, s2, ... as identifying labels. It writes a diagnostic message to standard error output if an argument is not the name of a global variable. Note that this procedure only works for global variables; there is no way it can access the local variables of the procedure from which it is called.
[ Full documentation | Source code ]
AD HOC
[ Full documentation | Source code ]
These procedures implement the weaving expressions supported by Painter and described in the PDF document "Advanced Weaving" that accompanies that application.
[ Full documentation | Source code ]
Links: expander, tables
[ Full documentation | Source code ]
WeightedShuffle returns the list "sample" with only a portion of the elements switched. Examples: L := WeightedShuffle (X, 100) - returns a fully shuffled list L := WeightedShuffle (X, 50) - every other element is eligible to be switched L := WeightedShuffle (X, 25) - every fourth element is shuffled L := WeightedShuffle (X, 0) - nothing is changed The procedure will fail if the given percentage is not between 0 and 100, inclusive, or if it is not a numeric value.
[ Full documentation | Source code ]
This is a kit of procedures to deal with UNIX-like filename wild-card patterns containing *, ?, and [...]. The meanings are as of the pattern characters are the same as in the UNIX shells csh and sh. They are described briefly in the wild_pat() procedure. These procedures are interesting partly because of the "recursive suspension" technique used to simulate conjunction of an arbitrary number of computed expressions. The public procedures are: wild_match(pattern,s,i1,i2) : i3,i4,...,iN wild_find(pattern,s,i1,i2) : i3,i4,...,iN wild_match() produces the sequence of positions in "s" past a substring starting at "i1" that matches "pattern", but fails if there is no such position. Similar to match(), but is capable of generating multiple positions. wild_find() produces the sequence of positions in "s" where substrings begin that match "pattern", but fails if there is no such position. Similar to find(). "pattern" can be either a string or a pattern list -- see wild_pat(), below. Default values of s, i1, and i2 are the same as for Icon's built-in string scanning procedures such as match(). wild_pat(s) : L Creates a pattern element list from pattern string "s". A pattern element is needed by wild_match() and wild_find(). wild_match() and wild_find() will automatically convert a pattern string to a pattern list, but it is faster to do the conversion explicitly if multiple operations are done using the same pattern.
[ Full documentation | Source code ]
word(s) -- Produces the position past a UNIX-style command line word. dequote(s) -- Produces the UNIX-style command line word s with any quoting characters removed.
[ Full documentation | Source code ]
wrap(s,i) -- Facilitates accumulation of small strings into longer output strings, outputting when the accumulated string would exceed a specified length (e.g. outputting items in multiple columns). s -- string to accumulate i -- width of desired output string Wrap fails if the string s did not necessitate output of the buffered output string; otherwise the output string is returned (which never includes s). s defaults to the empty string (""), causing nothing to be accumulated; i defaults to 0, forcing output of any buffered string. Note that calling wrap() with no arguments produces the buffer (if it is not empty) and clears it. Wrap does no output to files. Here's how wrap is normally used: wrap() # Initialize (not really necessary unless # a previous use might have left stuff in # the buffer). every i := 1 to 100 do # Loop to process strings to output -- write(wrap(x[i],80)) # only writes when 80-char line filled. write(wrap()) # Output what's in buffer -- only outputs # if something to write. wraps(s,i) -- Facilitates managing output of numerous small strings so that they do not exceed a reasonable line length (e.g. outputting items in multiple columns). s -- string to accumulate i -- maximum width of desired output string If the string "s" did not necessitate a line-wrap, the string "s" is returned. If a line-wrap is needed, "s", preceded by a new-line character ("\n"), is returned. "s" defaults to the empty string (""), causing nothing to be accumulated; i defaults to 0, forcing a new line if anything had been output on the current line. Thus calling wraps() with no arguments reinitializes it. Wraps does no output to files. Here's how wraps is normally used: wraps() # Initialize (not really necessary unless # a previous use might have left it in an # unknown condition). every i := 1 to 100 do # Loop to process strings to output -- writes(wraps(x[i],80))# only wraps when 80-char line filled. writes(wraps()) # Only outputs "\n" if something written # on last line.
[ Full documentation | Source code ]
write_cpt(output, carpet) writes the carpet with heading information to the specified file.
[ Full documentation | Source code ]
Description ----------- These procedures provide a way of storing Icon values in files and retrieving them. The procedure xencode(x,f) stores x in file f such that it can be converted back to x by xdecode(f). These procedures handle several kinds of values, including structures of arbitrary complexity and even loops. The following sequence will output x and recreate it as y: f := open("xstore","w") xencode(x,f) close(f) f := open("xstore") y := xdecode(f) close(f) For "scalar" types -- null, integer, real, cset, and string, the above sequence will result in the relationship x === y For structured types -- list, set, table, and record types -- y is, for course, not identical to x, but it has the same "shape" and its elements bear the same relation to the original as if they were encoded and decoded individually. Files, co-expressions, and windows cannot generally be restored in any way that makes much sense. These objects are restored as empty lists so that (1) they will be unique objects and (2) will likely generate run-time errors if they are (probably erroneously) used in computation. However, the special files &input, &output, and &errout are restored. Not much can be done with functions and procedures, except to preserve type and identification. The encoding of strings and csets handles all characters in a way that it is safe to write the encoding to a file and read it back. xdecode() fails if given a file that is not in xcode format or it the encoded file contains a record for which there is no declaration in the program in which the decoding is done. Of course, if a record is declared differently in the encoding and decoding programs, the decoding may be bogus. xencoden() and xdecoden() perform the same operations, except xencoden() and xdecoden() take the name of a file, not a file. xencodet() and xdecodet() are like xencode() and xdecode() except that the trailing argument is a type name. If the encoded decoded value is not of that type, they fail. xencodet() does not take an opt argument.
[ Full documentation | Source code ]
Note: This version handles the encoding of records using canonical names: record0, record1, ... . This allows programs to decode files by providing declarations for these names when the original declarations are not available. This version also provides for procedures and files present in the encoded file that are not in the decoding program. This version should be merged with the ordinary version. Description ----------- These procedures provide a way of storing Icon values in files and retrieving them. The procedure xencode(x,f) stores x in file f such that it can be converted back to x by xdecode(f). These procedures handle several kinds of values, including structures of arbitrary complexity and even loops. The following sequence will output x and recreate it as y: f := open("xstore","w") xencode(x,f) close(f) f := open("xstore") y := xdecode(f) close(f) For "scalar" types -- null, integer, real, cset, and string, the above sequence will result in the relationship x === y For structured types -- list, set, table, and record types -- y is, for course, not identical to x, but it has the same "shape" and its elements bear the same relation to the original as if they were encoded and decoded individually. Files, co-expressions, and windows cannot generally be restored in any way that makes much sense. These objects are restored as empty lists so that (1) they will be unique objects and (2) will likely generate run-time errors if they are (probably erroneously) used in computation. However, the special files &input, &output, and &errout are restored. Not much can be done with functions and procedures, except to preserve type and identification. The encoding of strings and csets handles all characters in a way that it is safe to write the encoding to a file and read it back. xdecode() fails if given a file that is not in xcode format or it the encoded file contains a record for which there is no declaration in the program in which the decoding is done. Of course, if a record is declared differently in the encoding and decoding programs, the decoding may be bogus. xencoden() and xdecoden() perform the same operations, except xencoden() and xdecoden() take the name of a file, not a file. xencodet() and xdecodet() are like xencode() and xdecode() except that the trailing argument is a type name. If the encoded decoded value is not of that type, they fail. xencodet() does not take an opt argument.
[ Full documentation | Source code ]
These procedures produce matrices for affine transformation in two dimensions and transform point lists. A point list is a list of Point() records. See gobject.icn.
[ Full documentation | Source code ]
ximage(x) : s Produces a string image of x. ximage() differs from image() in that it outputs all elements of structured data types. The output resembles Icon code and is thus familiar to Icon programmers. Additionally, it indents successive structural levels in such a way that it is easy to visualize the data's structure. Note that the additional arguments in the ximage procedure declaration are used for passing data among recursive levels. xdump(x1,x2,...,xn) : xn Using ximage(), successively writes the images of x1, x2, ..., xn to &errout. Some Examples: The following code: ... t := table() ; t["one"] := 1 ; t["two"] := 2 xdump("A table",t) xdump("A list",[3,1,3,[2,4,6],3,4,3,5]) Writes the following output (note that ximage() infers the predominant list element value and avoids excessive output): "A table" T18 := table(&null) T18["one"] := 1 T18["two"] := 2 "A list" L25 := list(8,3) L25[2] := 1 L25[4] := L24 := list(3) L24[1] := 2 L24[2] := 4 L24[3] := 6 L25[6] := 4 L25[8] := 5
[ Full documentation | Source code ]
xrotate(X, i) rotates the values in X right by one position. It works for lists and records. This procedure is mainly interesting as a recursive version of x1 :=: x2 :=: x3 :=: ... xn since a better method for lists is push(L, pull(L))
[ Full documentation | Source code ]
These Unix procedures read files from ZIP format archives by opening pipes to the "unzip" utility. It is assumed that "unzip" is in the shell search path. iszip(zname) succeeds if zname is a ZIP archive. zipdir(zname) opens a ZIP archive directory. zipfile(zname, fname) opens a member of a ZIP archive.
[ Full documentation | Source code ]