web-archive-net.com » NET » M » MAZAMA.NET Total: 124 Choose link from "Titles, links and description words view": Or switch to
"Titles and links view". |

- Pocket Scheme sample code

does a BlueTooth PAN driver in order to access this server While an ActiveSync connection to a host PC establishes a PPP link between the two devices there is no route back from the host to the device timeclnt scm A simple network time client per RFC 868 the old non compensated Time TCP protocol Demonstrates a TCP client and simple numeric network I O sdkgeneric smd The CE 2 0 SDK generic cpp application as rendered in Pocket Scheme This demonstrates the use of the three preceding interface libraries to create a GUI application It probably won t make any sense to you unless you re already comfortable writing Windows applications in C cm17a scm An interface library for the X10 FireCracker CM17A home automation controller Intended for use in a script e g my catbedon smd load cm17a scm display Turning on the cat s bed warmer newline firecracker on A1 At the top of cm17a scm I define two numeric values time warmup and time pulse which specify delays in milliseconds for warming up and holding a pulse in the signal to the CM17A transmitter The greater the value of time pulse the longer the CM17A will spend transmitting each bit of the signal making its RF transmission more robust Reducing this value to 1 will greatly speed operation but will reduce the radius of effective operation to point blank range less than 7 meters Also please remember that the synch cable for CE devices is a null modem cable wired as DCE instead of DTE You will need a null modem adapter as opposed to a simple gender changer if you plan to plug the CM17A into the DB9F at the distal end of the cable grep smd A simple script that finds lines in text files matching a given pattern subst smd Another simple script that performs text substitution in files Helps compensate for the lack of a Replace function in the Pocket Scheme Editor exn scm Contains a library of functions for manipulating exceptions Use this if you use the with handlers facility letcc scm Defines the letcc construct used in many examples of The Seasoned Schemer Sample code for version 1 1 The following samples work only on the previous five year old release of Pocket Scheme version 1 1 I haven t yet finished porting them to 1 2 They will not work on the current release I present them here only as partial examples Most of these samples were written for Windows CE Many of them will run on Windows NT or 2000 as well either as is or after setting the variable windows ce to f To run them on 95 98 or ME you may need to modify foreign procedure and structure imports to reference narrow character instead of wide character entry points ftp scm Implements a simple FTP client capable of uploading downloading or listing the contents directories on servers that accept anonymous connections While it would be

Original URL path: http://www.mazama.net/scheme/pscheme-samples.htm (2016-04-30)

Open archived version from archive - Applications Hosted by Pocket Scheme

of Prolog style logic programming in Scheme After downloading Schelog simply follow the installation directions therein identifying your Scheme dialect as pscheme and your operating system if necessary as windows Versions of Schelog previous to 3h2 will require that you examine and possibly modify Schelog s makeport scm to generate the correct syntax for Pocket Scheme Rename the resulting file with the extraordinarily long filename to something that won t provoke tendonitis To test your Schelog installation try the map coloring example Be sure that you have verbosity set to 3 or less Assuming that you renamed the ported Schelog to s scm load Program Files Pocket Scheme schelog s scm load Program Files Pocket Scheme schelog examples mapcol scm which M test color test M This simple map coloring test will yield a total of 120 non unique permutations You can see them all without typing more 119 times via do i 1 i 1 f which M test color test M more not f No more solutions display Sol n display i display display f newline Comparison with Edinburgh syntax Prolog Here s a simple Prolog program that sorts a list of numbers bsort List Slist swap List List0 bsort List0 Slist bsort Slist Slist swap X Y T Y X T not ordered X Y swap H T H T0 swap T T0 ordered X Y X In Schelog this bubble sort becomes define bsort letrec swap rel x y t h t0 cons x cons y t cons y cons x t not ordered x y cons h t cons h t0 swap t t0 ordered rel x y x y Here s Prolog to solve the Eight Queens problem queens N Qs range 1 N Ns queens Ns Qs queens Qs Qs queens UnplacedQs SafeQs Qs select Q UnplacedQs UnplacedQs1 not attack Q SafeQs queens UnplacedQs1 Q SafeQs Qs select X X Xs Xs select X Y Ys Y Zs select X Ys Zs attack X Xs attack X 1 Xs attack X N Y Ys X is Y N X is Y N attack X N Y Ys N1 is N 1 attack X N1 Ys range M N M Ns M In Schelog this becomes define queens letrec select rel x xs y ys zs x cons x xs xs x cons y ys cons y zs select x ys zs attack rel x xs n n1 y ys x xs attack x 1 xs x n cons y ys is x y n x n cons y ys is x y n x n cons y ys is n1 n 1 attack x n1 ys range rel m m1 n ns m n cons m ns These two examples highlight a number of differences between Prolog and Schelog Schelog relations may use private variables and lexical scoping note the use of letrec to hide auxiliary routines In Prolog all names are global and all variables available throughout a relation Schelog relations must

Original URL path: http://www.mazama.net/scheme/pscheme-apps.htm (2016-04-30)

Open archived version from archive - Pocket Scheme - Release History

wait procedure More thorough error checking 30 September 1999 Version 0 5 6 Rewrote eval variable reference memoization to accommodate Schelog broken in 0 5 0 New procedures expand macro expand macro 1 Default editor tabstop now 2 Better hash function courtesy of Bob Jenkins 1 September 1999 Version 0 5 5 expires 31 December 1999 Foreign function interface Bug fixes in raw vectors 19 August 1999 Version 0 5 4 BETA 1 expiration date relaxed Bug fix in current directory handling Editor tab handling changed 16 August 1999 Version 0 5 3 Bug fixes eval side effects command line parsing stack overflow handling require install directory library directory 6 August 1999 Version 0 5 2 Bug fixes equal on similar strings GC cannibalizing the environment premature partial evaluation of untaken branches in if clauses 5 August 1999 Version 0 5 1 Reduce consing on long iterative processes a misfeature of 0 5 0 Further performance improvements All mutator procs return void Read only strings from certain procedures 30 July 1999 Version 0 5 0 expires 1 September 1999 Major delta to evaluator symbol manager storage manager Evaluator caches lexical addresses of variables Storage manager maintains a monolithic cell address space Added gensym for safe macros Changed defmacro to define macro Withdrew symbol value set symbol value symbol bound apropos Be sure to remove any previous version before installing this one 14 June 1999 Version 0 4 0 expires 1 August 1999 UI work command history pause command improved input mode full screen usage during execution Changed command line switches Simplified script model Added socket local address socket remote port socket local port Be sure to remove any previous version before installing this one 26 May 1999 Version 0 3 8 Bug fix in socket support 17 May 1999 Version 0 3 7 Directory support create directory delete directory current directory emulated on CE Replaced opendir readdir closedir with directory list Added w32 beep Eval call cc apply call their procedure arguments as tail calls Some reader loader cleanup Tweak UI to reduce the flashing screen problem on certain models of H PC 3 May 1999 Version 0 3 6 Much work on storage management exception handling String ports made compliant with SRFI 6 Chez Mz style New soft ports similar to Chez Socket support now follows the Scsh model Changed regexp model Typed exceptions thrown for interpreter errors Extensive fixes throughout 14 April 1999 Version 0 3 5 Support big endian Unicode text data Increase range of exact integers the maximum positive exact integer value is now xFFFFFFFF Better exact versus inexact numerical discipline Corrections to number and character readers 11 April 1999 Version 0 3 4 Case insensitive symbols Numeric comparisons of arity greater than two Hexadecimal character literal syntax Callstacks available upon errors via debug stack depth Remainder of list parameter in closure now assignable Fixed pitch output available in UI Changes to SLIB initialization file 8 April 1999 Version 0 3 3 Defmacro made internal to

Original URL path: http://www.mazama.net/scheme/pscheme-history.htm (2016-04-30)

Open archived version from archive - Pocket Scheme

size Also its commands File Open and File Save only operate under the My Documents directory on your device or storage cards To work around this shortcoming open files from the File Explorer Debugging The procedures trace and untrace implement call tracing for user defined functions trace shadows a function with a shell that reports every call to and return from that function while untrace removes the shadow from a function Warning calls to a traced procedure are no longer tail recursive even in tail position Printing call traces will greatly slow a program To increase the speed of a deeply recursive traced procedure hide the output window either by tapping the taskbar rectangle to send Pocket Scheme to the background or by tapping the little desktop box to bring the desktop to the foreground The procedure debug activates callstacks a listing of pending procedure calls that Pocket Scheme will display when stopping with an error For best performance always leave this feature disabled the default Once code stops with an error enable callstacks via debug t then reevaluate the offending expression The procedure gc verbose instructs the garbage collector whether to report its activity Again for best performance always leave this feature disabled the default Enabling it via gc verbose t results in a pop up window periodically appearing whenever Pocket Scheme recycles unused memory Note this feature has been disabled for 1 3 The procedures gc stats and gc reset stats are also useful to this end Note Tools Break returns control to the topmost environment It does not leave the user in the context of the interrupted evaluation as the name might imply Scripting In much the same fashion that a MS DOS PC can run BAT files via COMMAND COM or a Unix workstation can run shell scripts via bin sh the Pocket PC can run Scheme scripts via Pocket Scheme To run a script open it from the File Explorer Pocket Scheme recognizes any file ending in the suffix smd as its own and will attempt to interpret the contents of that file as a Scheme program See the description of the r command line switch for an explanation of this mechanism Note that double tapping the icon of a scm file will instead open that file in the Pocket Scheme Editor If the command line passes any arguments after the mandatory r scriptname smd a script can access those arguments through its argv global E g the invocation pscheme exe r My Documents mail smd root x com would run the Scheme program My Documents mail smd setting the global symbol argv to the list My Documents mail smd root x com By default a script that stops with an error leaves Scheme in interactive mode while a script that completes successfully closes the Scheme window when finished You may switch away from a running script at any time If it needs input it will notify you Otherwise it will continue running until it

Original URL path: http://www.mazama.net/scheme/v13/pscmhlp.htm (2016-04-30)

Open archived version from archive - Pocket Scheme Language Reference

input raw vector u8vec start end raw input source Creates a raw input source that delivers octets from a u8 raw vector The optional start and end parameters if supplied specify a half open range of indices into the raw vector Compare with open input string open output raw vector raw output sink Creates a raw output sink that accumulates octets written to it A subsequent call to get output raw vector on this sink will return those octets Compare with open output string get output raw vector osnk u8 raw vector Called on a raw output sink returned by open output raw vector returns a raw vector containing all octets written to that sink Compare with get output string open output raw vector u8vec start end raw output sink Creates a raw output sink that stores its octets in the given raw vector u8vec Such an output sink requires no subsequent call to get output raw vector The optional start and end parameters if supplied specify a half open range of indices into the raw vector raw input source obj Boolean Returns t if object is a raw input source f otherwise raw output sink obj Boolean Returns t if object is a raw output sink f otherwise file position isrc offset integer Returns the number of octets previously read from a raw input file or written to a raw output file With an offset seeks within the stream as if the specified number force output osnk void Ensures that any octets potentially buffered in an output stream have been written to the backing device octets ready isrc count Boolean Returns t if the specified raw input source has data ready for the specified number of calls to read octet default 1 or at EOF or if EOF is within the specified count f otherwise A return value of f means that a read call may potentially block On streams associated with non interactive devices and counts greater than 1 the system may use this as a hint to read ahead close raw input source isrc void Close the specified raw input source making it incapable of producing octets close raw output sink osnk void Close the specified raw output sink making it incapable of consuming octets Up Numeric I O read octet isrc integer Takes a single raw input source Returns exact integer in range 0 255 or the eof object at end of stream write octet octet osnk void Takes two parameters an exact integer in the range 0 255 and an raw output sink Returns nothing read raw number isrc count endian signed integer Reads a sequence of octets from the stream interpreting them as a raw machine integer count is an exact nonnegative integer specifying the number of octets to read it must have the value 1 2 4 or 8 The optional Boolean signed parameter if supplied and true specifies to interpret the sequence as a twos complement representation of a signed integer otherwise the result will be interpreted as unsigned with the procedure returning a nonnegative value The optional endian keyword symbol parameter specifies the order in which to interpret the octets as successive base 256 digits of an exact integer unspecified the implementation uses the host s default order The procedure returns the eof object at end of file or otherwise if it can read fewer than the specified count of octets The endian parameter may take any one of the following values Keyword Encoding big endian most significant byte first little endian least significant byte first network synonym for big endian native use the ordering of the local hosting system host synonym for native write raw number osnk n count endian void Take the specified value n and encode it onto the output sink osnk as a sequence of octets n must be an exact integer If it is negative the encoding will be two s complement signed otherwise it will be unsigned The emitted encoding will occupy the specified count of base 256 digits arranged per the endian attribute read raw ieee754 isrc count endian real Reads a sequence of octets from the stream interpreting them as an IEEE 754 floating point number and returning an inexact real quantity count must be an exact integer one of 4 or 8 The procedure will return f if it cannot honor found NaN INF or INF values write raw ieee754 osnk x count endian void Take the specified value x and encode it onto the output sink osnk as a sequence of octets in IEEE754 format and encode it as a sequence of octets in IEEE 754 format count must be an exact integer one of 4 or 8 Up Block numeric I O read raw number block isrc element count octet count endian signed raw vector or EOF Returns a raw vector where each element of the vector has been read from the stream by read raw number The procedure reads up to element count items from the stream or fewer upon encountering end of file If the stream contains insufficient data to compose even a single raw number i e fewer than octet count octets the procedure will return the eof object The returned raw vector will be of a type that can accommodate the given values of octet count and signed e g 2 and t would return a s16 raw vector Note that this procedure does not test for octets ready Stream octet count element count it reads for the entire amount blocking and taking what it can get Also since raw input sources support neither pushback nor read ahead any odd octets immediately before end of file will be lost after the manner of the posix fread 3 call read raw ieee754 block isrc element count octet count endian raw vector or EOF Similar to read raw number block only decoding per IEEE 754 floating point format and returning a f32 or f64 raw vector octet count must be either 4 or 8 read raw number block uvec isrc endian start end integer or EOF Similar to read raw number block or read raw ieee754 block but destructively modifying an existing raw vector reading elements into that vector at the half open start end interval octet count and signed cf previous calls are inferred from the type of the raw vector Returns the number of elements read or the EOF object at the end of file write raw number block uvec osnk endian start end void Writes the specified elements of the vector to the stream as if by write raw number or write raw ieee754 octet count and signed cf previous calls are inferred from the type of the raw vector emitting single precision floats from a f32 double precision floats from a f64 Up Character encoding Many of these procedures take one or more external format arguments describing the manner in which a character is encoded on the stream Symbol Encoding ascii 7 bits of ASCII character code within an 8 bit octet with the eighth bit clear latin 1 8 bits of Latin 1 character code in an 8 bit octet ucs 2be 16 bits of UCS 2 character code in two octets big endian ucs 2le 16 bits of UCS 2 character code in two octets little endian ucs 2 16 bits of UCS 2 character code in two octets arranged host native unicode Synonym for ucs 2 system ansi Default Windows codepage on the device May represent one character in either one or two octets crlf newline newline Scheme character represents two external characters CR LF as seen in TCP network protocols and Microsoft disk text files This format is composable with any other external format lf newline newline Scheme character represents one external character LF as seen in Unix disk text files This format is composable with any other external format emit bom Emitted data includes a byte order mark Output only Composable with any Unicode external format suppress bom Emitted data does not include a byte order mark Output only Composable with any Unicode external format unicode char n character or f The fundamental character constructor Returns the character corresponding to the specified Unicode codepoint If it cannot represent the specified value it will return f integer char n character Per R4RS Synonym for unicode char Note that this does not deliver the order preserving isomorphisms of R4RS char unicode c integer Returns the Unicode codepoint value corresponding to the specified character char integer c integer Per R4RS Synonym for char unicode Again note that this does not deliver the order preserving isomorphisms of R4RS read raw string isrc octet count external format string or EOF Reads octet count octets from the specified input source decoding them into characters per the specified external format and returning a new string of the characters Will return EOF if insufficient octets remain on the stream to decode even a single character raw string length str external format start end integer Returns the number of octets that the given string str would require for the specified external format The optional start and end are half open indices into the string per SRFI 13 the scsh read string primitive or the standard procedure substring write raw string str osnk external format start end void Encodes the characters in the given string str onto the output sink start and end are half open indices into the string cook input source isrc octet count external format input port Given a raw input source create a proper input port that decodes from the stream That input port will consume octet count octets from the stream returning EOF once it has consumed the specified count octet count may also be f in which case the input port will read from its backing stream until it completely exhausts the stream or until close input port is called on the port While this port is open it is an error to call cook input source to create another such port on the same stream and calling read octet and its ilk will have unspecified effects since the new port may be caching octets from its stream A program may close a character port before it exhausts its specified octet count whereupon any external format procedure will be called one last time with EOF Subsequent calls to read octet on the stream will then act as if a full octet count number of calls to read octet had taken place cook output sink osnk external format output port Given an output sink create a proper output port that encodes onto the stream While this port is open it is an error to call cook output sink to create another such port on the same sink and calling write octet and its ilk will have unspecified effects since the new port may be deferring encoding cook char encoding port symbol Returns a symbol representing the character encoding scheme on the given port The port must be connected to external data e g one created by open output file but not open output string cook newline encoding port symbol Similar to cook char encoding this procedure returns a symbol representing the newline encoding scheme on the given port This will be either crlf newline or lf newline The port must be connected to external data Up Text I O open input file filename flags input port Per R4RS The flags may be any appropriate combination of external format specifiers If no external format specifiers are supplied the systems attempts to determine the format of the opened file and supply the correct data conversion It is an error to open a file that does not exist or cannot be read See file exists with input from file filename thunk flags value Per R4RS supporting the flags of open input file call with input file filename proc flags value Per R4RS supporting the flags of open input file with input from port port thunk value Generalization of with input from file for any port open output file filename flags output port Per R4RS The flags may be a combination of external format specifiers or the following behavioral specifiers Flag Behavior truncate if exists If opened file already exists truncate it to length 0 before writing append if exists If opened file already exists append data to its end error if exists If opened file already exists raise an exception update must exist If opened file does not already exist raise an exception with output to file filename thunk flags value Per R4RS supporting the flags of open output file call with output file filename proc flags value Per R4RS supporting the flags of open output file with output to port port thunk value Generalization of with output to file for any port force output port void Force an output port or raw octet sink to deliver any cached data Without a parameter defaults to the current output port read string port count string Read characters from the specified port up to the number of characters specified If no character count is specified reads up to a newline character Returns the string of characters or the EOF object at end of file read string string port start end integer Read characters from the specified port into the specified string If the call specifies start and end it enters the characters into the string at the half open interval start end per the substring procedure Return the number of characters read or the EOF object at end of file read line port string Read a single line of input as a string read line differs from read string without a character count by eliding the terminating newline character from the returned string Returns the string or the EOF object at end of file write string string port start end void Writes characters from the specified string into the specified port If the call specifies start and end it takes the charactes from the string at the half open interval start end per the substring procedure Return the number of characters read or the EOF object at end of file Up Soft ports make input port handler input port Creates a new input port that queries the procedure handler for its content An input port handler is a variable arity procedure called with one of the following symbols as its first argument Flag Effect read char Return a character peek char Return a character A subsequent call to read or peek will return this same character char ready Return t if a read will not block per the semantics of the standard Scheme procedure of this name close port Port is closing make output port handler output port Creates a new output port that queries the procedure handler for the disposition of its content An output port handler is a variable arity procedure called with one of the following symbols as its first argument Flag Effect write char Second argument is a character to write force output Write any pending cached data close port Port is closing make input octet source handler raw input source Similar to make input port but creates a raw input source rather than an input port Its handler delivers octets not characters Flag Effect read octet Return an octet data ready Return t if a read will not block per the semantics of the Pocket Scheme procedure of this name Second argument is the number of octets expected close port Octet source is closing make output octet sink handler raw output sink Similar to make output port but creates a raw output sink rather than an output port Its handler receives octets not characters Flag Effect write octet Second argument is an octet to write force output Write any pending cached data close port Octet sink is closing Up Raw vectors The raw vector data type provides Pocket Scheme with an efficient medium for binary file I O Unlike standard Scheme vectors raw vectors have homogeneous numeric elements with a range limited by the fundamental raw machine datatype of the vector Name Raw machine type u8 unsigned 8 bit exact integer s8 signed 8 bit exact integer u16 unsigned 16 bit exact integer s16 signed 16 bit exact integer u32 unsigned 32 bit exact integer s32 signed 32 bit exact integer u64 unsigned 64 bit exact integer s64 signed 64 bit exact integer f32 single precision 32 bit inexact real f64 double precision 64 bit inexact real Raw vectors are similar to the arrays of SIOD the uniform vectors of SCM or the homogeneous numeric vectors of Gambit and SRFI 4 q v http srfi schemers org srfi 4 srfi 4 html make raw vector k type raw vector Create a new raw vector with k elements of the specified type raw vector ref v i number Return the index i element of raw vector v raw vector set v i d void Set the index i element of raw vector v to value d raw vector object Boolean Predicate returning t if the argument is a raw vector raw vector length v integer Returns the number of elements in a raw vector raw vector type v symbol Returns the symbol naming the type of a raw vector This will be one of the symbols in the table above Up Strings string breakup source separator list Scan the given string source returning a list of its substrings as delimited by the substring separator string unbreakup string list separator string Concatenate all strings in string list separating them by the string separator For any string s and any separator r the following relation holds string s string unbreakup string breakup s r r Up Numerics zero number Boolean Per the Scheme standard In addition to numbers this predicate will accept a foreign as an argument returning t if the foreign has a bit pattern of

Original URL path: http://www.mazama.net/scheme/v13/pscmref.htm (2016-04-30)

Open archived version from archive - Revised(5) Scheme

in terms of other built in procedures are identified as library procedures A program may use a top level definition to bind any variable It may subsequently alter any such binding by an assignment see see section Assignments These operations do not modify the behavior of Scheme s built in procedures Altering any top level binding that has not been introduced by a definition has an unspecified effect on the behavior of the built in procedures Equivalence predicates A predicate is a procedure that always returns a boolean value t or f An equivalence predicate is the computational analogue of a mathematical equivalence relation it is symmetric reflexive and transitive Of the equivalence predicates described in this section eq is the finest or most discriminating and equal is the coarsest Eqv is slightly less discriminating than eq procedure eqv obj1 obj2 The eqv procedure defines a useful equivalence relation on objects Briefly it returns t if obj1 and obj2 should normally be regarded as the same object This relation is left slightly open to interpretation but the following partial specification of eqv holds for all implementations of Scheme The eqv procedure returns t if obj1 and obj2 are both t or both f obj1 and obj2 are both symbols and string symbol string obj1 symbol string obj2 t Note This assumes that neither obj1 nor obj2 is an uninterned symbol as alluded to in section section Symbols This report does not presume to specify the behavior of eqv on implementation dependent extensions obj1 and obj2 are both numbers are numerically equal see section see section Numbers and are either both exact or both inexact obj1 and obj2 are both characters and are the same character according to the char procedure section see section Characters both obj1 and obj2 are the empty list obj1 and obj2 are pairs vectors or strings that denote the same locations in the store section see section Storage model obj1 and obj2 are procedures whose location tags are equal section see section Procedures The eqv procedure returns f if obj1 and obj2 are of different types section see section Disjointness of types one of obj1 and obj2 is t but the other is f obj1 and obj2 are symbols but string symbol string obj1 symbol string obj2 f one of obj1 and obj2 is an exact number but the other is an inexact number obj1 and obj2 are numbers for which the procedure returns f obj1 and obj2 are characters for which the char procedure returns f one of obj1 and obj2 is the empty list but the other is not obj1 and obj2 are pairs vectors or strings that denote distinct locations obj1 and obj2 are procedures that would behave differently return different value s or have different side effects for some arguments eqv a a t eqv a b f eqv 2 2 t eqv t eqv 100000000 100000000 t eqv cons 1 2 cons 1 2 f eqv lambda 1 lambda 2 f eqv f nil f let p lambda x x eqv p p t The following examples illustrate cases in which the above rules do not fully specify the behavior of eqv All that can be said about such cases is that the value returned by eqv must be a boolean eqv unspecified eqv unspecified eqv lambda x x lambda x x unspecified eqv lambda x x lambda y y unspecified The next set of examples shows the use of eqv with procedures that have local state Gen counter must return a distinct procedure every time since each procedure has its own internal counter Gen loser however returns equivalent procedures each time since the local state does not affect the value or side effects of the procedures define gen counter lambda let n 0 lambda set n n 1 n let g gen counter eqv g g t eqv gen counter gen counter f define gen loser lambda let n 0 lambda set n n 1 27 let g gen loser eqv g g t eqv gen loser gen loser unspecified letrec f lambda if eqv f g both f g lambda if eqv f g both g eqv f g unspecified letrec f lambda if eqv f g f both g lambda if eqv f g g both eqv f g f Since it is an error to modify constant objects those returned by literal expressions implementations are permitted though not required to share structure between constants where appropriate Thus the value of eqv on constants is sometimes implementation dependent eqv a a unspecified eqv a a unspecified eqv b cdr a b unspecified let x a eqv x x t Rationale The above definition of eqv allows implementations latitude in their treatment of procedures and literals implementations are free either to detect or to fail to detect that two procedures or two literals are equivalent to each other and can decide whether or not to merge representations of equivalent objects by using the same pointer or bit pattern to represent both procedure eq obj1 obj2 Eq is similar to eqv except that in some cases it is capable of discerning distinctions finer than those detectable by eqv Eq and eqv are guaranteed to have the same behavior on symbols booleans the empty list pairs procedures and non empty strings and vectors Eq s behavior on numbers and characters is implementation dependent but it will always return either true or false and will return true only when eqv would also return true Eq may also behave differently from eqv on empty vectors and empty strings eq a a t eq a a unspecified eq list a list a f eq a a unspecified eq unspecified eq t eq 2 2 unspecified eq A A unspecified eq car car t let n 2 3 eq n n unspecified let x a eq x x t let x eq x x t let p lambda x x eq p p t Rationale It will usually be possible to implement eq much more efficiently than eqv for example as a simple pointer comparison instead of as some more complicated operation One reason is that it may not be possible to compute eqv of two numbers in constant time whereas eq implemented as pointer comparison will always finish in constant time Eq may be used like eqv in applications using procedures to implement objects with state since it obeys the same constraints as eqv library procedure equal obj1 obj2 Equal recursively compares the contents of pairs vectors and strings applying eqv on other objects such as numbers and symbols A rule of thumb is that objects are generally equal if they print the same Equal may fail to terminate if its arguments are circular data structures equal a a t equal a a t equal a b c a b c t equal abc abc t equal 2 2 t equal make vector 5 a make vector 5 a t equal lambda x x lambda y y unspecified Numbers Numerical computation has traditionally been neglected by the Lisp community Until Common Lisp there was no carefully thought out strategy for organizing numerical computation and with the exception of the MacLisp system Pitman83 little effort was made to execute numerical code efficiently This report recognizes the excellent work of the Common Lisp committee and accepts many of their recommendations In some ways this report simplifies and generalizes their proposals in a manner consistent with the purposes of Scheme It is important to distinguish between the mathematical numbers the Scheme numbers that attempt to model them the machine representations used to implement the Scheme numbers and notations used to write numbers This report uses the types number complex real rational and integer to refer to both mathematical numbers and Scheme numbers Machine representations such as fixed point and floating point are referred to by names such as fixnum and flonum Numerical types Mathematically numbers may be arranged into a tower of subtypes in which each level is a subset of the level above it number complex real rational integer For example 3 is an integer Therefore 3 is also a rational a real and a complex The same is true of the Scheme numbers that model 3 For Scheme numbers these types are defined by the predicates number complex real rational and integer There is no simple relationship between a number s type and its representation inside a computer Although most implementations of Scheme will offer at least two different representations of 3 these different representations denote the same integer Scheme s numerical operations treat numbers as abstract data as independent of their representation as possible Although an implementation of Scheme may use fixnum flonum and perhaps other representations for numbers this should not be apparent to a casual programmer writing simple programs It is necessary however to distinguish between numbers that are represented exactly and those that may not be For example indexes into data structures must be known exactly as must some polynomial coefficients in a symbolic algebra system On the other hand the results of measurements are inherently inexact and irrational numbers may be approximated by rational and therefore inexact approximations In order to catch uses of inexact numbers where exact numbers are required Scheme explicitly distinguishes exact from inexact numbers This distinction is orthogonal to the dimension of type Exactness Scheme numbers are either exact or inexact A number is exact if it was written as an exact constant or was derived from exact numbers using only exact operations A number is inexact if it was written as an inexact constant if it was derived using inexact ingredients or if it was derived using inexact operations Thus inexactness is a contagious property of a number If two implementations produce exact results for a computation that did not involve inexact intermediate results the two ultimate results will be mathematically equivalent This is generally not true of computations involving inexact numbers since approximate methods such as floating point arithmetic may be used but it is the duty of each implementation to make the result as close as practical to the mathematically ideal result Rational operations such as should always produce exact results when given exact arguments If the operation is unable to produce an exact result then it may either report the violation of an implementation restriction or it may silently coerce its result to an inexact value See section section Implementation restrictions With the exception of inexact exact the operations described in this section must generally return inexact results when given any inexact arguments An operation may however return an exact result if it can prove that the value of the result is unaffected by the inexactness of its arguments For example multiplication of any number by an exact zero may produce an exact zero result even if the other argument is inexact Implementation restrictions Implementations of Scheme are not required to implement the whole tower of subtypes given in section section Numerical types but they must implement a coherent subset consistent with both the purposes of the implementation and the spirit of the Scheme language For example an implementation in which all numbers are real may still be quite useful Implementations may also support only a limited range of numbers of any type subject to the requirements of this section The supported range for exact numbers of any type may be different from the supported range for inexact numbers of that type For example an implementation that uses flonums to represent all its inexact real numbers may support a practically unbounded range of exact integers and rationals while limiting the range of inexact reals and therefore the range of inexact integers and rationals to the dynamic range of the flonum format Furthermore the gaps between the representable inexact integers and rationals are likely to be very large in such an implementation as the limits of this range are approached An implementation of Scheme must support exact integers throughout the range of numbers that may be used for indexes of lists vectors and strings or that may result from computing the length of a list vector or string The length vector length and string length procedures must return an exact integer and it is an error to use anything but an exact integer as an index Furthermore any integer constant within the index range if expressed by an exact integer syntax will indeed be read as an exact integer regardless of any implementation restrictions that may apply outside this range Finally the procedures listed below will always return an exact integer result provided all their arguments are exact integers and the mathematically expected result is representable as an exact integer within the implementation quotient remainder modulo max min abs numerator denominator gcd lcm floor ceiling truncate round rationalize expt Implementations are encouraged but not required to support exact integers and exact rationals of practically unlimited size and precision and to implement the above procedures and the procedure in such a way that they always return exact results when given exact arguments If one of these procedures is unable to deliver an exact result when given exact arguments then it may either report a violation of an implementation restriction or it may silently coerce its result to an inexact number Such a coercion may cause an error later An implementation may use floating point and other approximate representation strategies for inexact numbers This report recommends but does not require that the IEEE 32 bit and 64 bit floating point standards be followed by implementations that use flonum representations and that implementations using other representations should match or exceed the precision achievable using these floating point standards IEEE In particular implementations that use flonum representations must follow these rules A flonum result must be represented with at least as much precision as is used to express any of the inexact arguments to that operation It is desirable but not required for potentially inexact operations such as sqrt when applied to exact arguments to produce exact answers whenever possible for example the square root of an exact 4 ought to be an exact 2 If however an exact number is operated upon so as to produce an inexact result as by sqrt and if the result is represented as a flonum then the most precise flonum format available must be used but if the result is represented in some other way then the representation must have at least as much precision as the most precise flonum format available Although Scheme allows a variety of written notations for numbers any particular implementation may support only some of them For example an implementation in which all numbers are real need not support the rectangular and polar notations for complex numbers If an implementation encounters an exact numerical constant that it cannot represent as an exact number then it may either report a violation of an implementation restriction or it may silently represent the constant by an inexact number Syntax of numerical constants The syntax of the written representations for numbers is described formally in section section Lexical structure Note that case is not significant in numerical constants A number may be written in binary octal decimal or hexadecimal by the use of a radix prefix The radix prefixes are b binary o octal d decimal and x hexadecimal With no radix prefix a number is assumed to be expressed in decimal A numerical constant may be specified to be either exact or inexact by a prefix The prefixes are e for exact and i for inexact An exactness prefix may appear before or after any radix prefix that is used If the written representation of a number has no exactness prefix the constant may be either inexact or exact It is inexact if it contains a decimal point an exponent or a character in the place of a digit otherwise it is exact In systems with inexact numbers of varying precisions it may be useful to specify the precision of a constant For this purpose numerical constants may be written with an exponent marker that indicates the desired precision of the inexact representation The letters s f d and l specify the use of short single double and long precision respectively When fewer than four internal inexact representations exist the four size specifications are mapped onto those available For example an implementation with two internal representations may map short and single together and long and double together In addition the exponent marker e specifies the default precision for the implementation The default precision has at least as much precision as double but implementations may wish to allow this default to be set by the user 3 14159265358979F0 Round to single 3 141593 0 6L0 Extend to long 600000000000000 Numerical operations The reader is referred to section section Entry format for a summary of the naming conventions used to specify restrictions on the types of arguments to numerical routines The examples used in this section assume that any numerical constant written using an exact notation is indeed represented as an exact number Some examples also assume that certain numerical constants written using an inexact notation can be represented without loss of accuracy the inexact constants were chosen so that this is likely to be true in implementations that use flonums to represent inexact numbers procedure number obj procedure complex obj procedure real obj procedure rational obj procedure integer obj These numerical type predicates can be applied to any kind of argument including non numbers They return t if the object is of the named type and otherwise they return f In general if a type predicate is true of a number then all higher type predicates are also true of that number Consequently if a type predicate is false of a number then all lower type predicates are also false of that number If z is an inexact complex number then real z is true if and only if zero imag part z is true If x is an inexact real number then integer x is true if and only if x round x complex 3 4i t complex 3 t real 3 t real 2 5 0 0i t real e1e10 t rational 6 10 t rational 6 3 t integer 3 0i t integer 3 0 t integer 8 4 t Note The behavior of these type predicates on inexact numbers is unreliable since any inaccuracy may affect the result Note In many implementations the rational procedure will be the same as real and the complex procedure will be the same as number but unusual implementations may be able to represent some irrational numbers exactly or may extend the number system to support some kind of non complex numbers procedure exact z procedure inexact z These numerical predicates provide tests for the exactness of a quantity For any Scheme number precisely one of these predicates is true procedure z1 z2 z3 procedure x1 x2 x3 procedure x1 x2 x3 procedure x1 x2 x3 procedure x1 x2 x3 These procedures return t if their arguments are respectively equal monotonically increasing monotonically decreasing monotonically nondecreasing or monotonically nonincreasing These predicates are required to be transitive Note The traditional implementations of these predicates in Lisp like languages are not transitive Note While it is not an error to compare inexact numbers using these predicates the results may be unreliable because a small inaccuracy may affect the result this is especially true of and zero When in doubt consult a numerical analyst library procedure zero z library procedure positive x library procedure negative x library procedure odd n library procedure even n These numerical predicates test a number for a particular property returning t or f See note above library procedure max x1 x2 library procedure min x1 x2 These procedures return the maximum or minimum of their arguments max 3 4 4 exact max 3 9 4 4 0 inexact Note If any argument is inexact then the result will also be inexact unless the procedure can prove that the inaccuracy is not large enough to affect the result which is possible only in unusual implementations If min or max is used to compare numbers of mixed exactness and the numerical value of the result cannot be represented as an inexact number without loss of accuracy then the procedure may report a violation of an implementation restriction procedure z1 procedure z1 These procedures return the sum or product of their arguments 3 4 7 3 3 0 4 4 1 procedure z1 z2 procedure z optional procedure z1 z2 procedure z1 z2 procedure z optional procedure z1 z2 With two or more arguments these procedures return the difference or quotient of their arguments associating to the left With one argument however they return the additive or multiplicative inverse of their argument 3 4 1 3 4 5 6 3 3 3 4 5 3 20 3 1 3 library procedure abs x Abs returns the absolute value of its argument abs 7 7 procedure quotient n1 n2 procedure remainder n1 n2 procedure modulo n1 n2 These procedures implement number theoretic integer division n2 should be non zero All three procedures return integers If n1 n2 is an integer quotient n1 n2 n1 n2 remainder n1 n2 0 modulo n1 n2 0 If n1 n2 is not an integer quotient n1 n2 n q remainder n1 n2 n r modulo n1 n2 n m where n q is n1 n2 rounded towards zero 0 n r n2 0 n m n2 n r and n m differ from n1 by a multiple of n2 n r has the same sign as n1 and n m has the same sign as n2 From this we can conclude that for integers n1 and n2 with n2 not equal to 0 n1 n2 quotient n1 n2 remainder n1 n2 t provided all numbers involved in that computation are exact modulo 13 4 1 remainder 13 4 1 modulo 13 4 3 remainder 13 4 1 modulo 13 4 3 remainder 13 4 1 modulo 13 4 1 remainder 13 4 1 remainder 13 4 0 1 0 inexact library procedure gcd n1 library procedure lcm n1 These procedures return the greatest common divisor or least common multiple of their arguments The result is always non negative gcd 32 36 4 gcd 0 lcm 32 36 288 lcm 32 0 36 288 0 inexact lcm 1 procedure numerator q procedure denominator q These procedures return the numerator or denominator of their argument the result is computed as if the argument was represented as a fraction in lowest terms The denominator is always positive The denominator of 0 is defined to be 1 numerator 6 4 3 denominator 6 4 2 denominator exact inexact 6 4 2 0 procedure floor x procedure ceiling x procedure truncate x procedure round x These procedures return integers Floor returns the largest integer not larger than x Ceiling returns the smallest integer not smaller than x Truncate returns the integer closest to x whose absolute value is not larger than the absolute value of x Round returns the closest integer to x rounding to even when x is halfway between two integers Rationale Round rounds to even for consistency with the default rounding mode specified by the IEEE floating point standard Note If the argument to one of these procedures is inexact then the result will also be inexact If an exact value is needed the result should be passed to the inexact exact procedure floor 4 3 5 0 ceiling 4 3 4 0 truncate 4 3 4 0 round 4 3 4 0 floor 3 5 3 0 ceiling 3 5 4 0 truncate 3 5 3 0 round 3 5 4 0 inexact round 7 2 4 exact round 7 7 library procedure rationalize x y Rationalize returns the simplest rational number differing from x by no more than y A rational number r 1 is simpler than another rational number r 2 if r 1 p 1 q 1 and r 2 p 2 q 2 in lowest terms and p 1 p 2 and q 1 q 2 Thus 3 5 is simpler than 4 7 Although not all rationals are comparable in this ordering consider 2 7 and 3 5 any interval contains a rational number that is simpler than every other rational number in that interval the simpler 2 5 lies between 2 7 and 3 5 Note that 0 0 1 is the simplest rational of all rationalize inexact exact 3 1 10 1 3 exact rationalize 3 1 10 i1 3 inexact procedure exp z procedure log z procedure sin z procedure cos z procedure tan z procedure asin z procedure acos z procedure atan z procedure atan y x These procedures are part of every implementation that supports general real numbers they compute the usual transcendental functions Log computes the natural logarithm of z not the base ten logarithm Asin acos and atan compute arcsine sin 1 arccosine cos 1 and arctangent tan 1 respectively The two argument variant of atan computes angle make rectangular x y see below even in implementations that don t support general complex numbers In general the mathematical functions log arcsine arccosine and arctangent are multiply defined The value of log z is defined to be the one whose imaginary part lies in the range from pi exclusive to pi inclusive log 0 is undefined With log defined this way the values of sin 1 z cos 1 z and tan 1 z are according to the following formulæ sin 1 z i log i z sqrt1 z 2 cos 1 z pi 2 sin 1 z tan 1 z log 1 i z log 1 i z 2 i The above specification follows CLtL which in turn cites Penfield81 refer to these sources for more detailed discussion of branch cuts boundary conditions and implementation of these functions When it is possible these procedures produce a real result from a real argument procedure sqrt z Returns the principal square root of z The result will have either positive real part or zero real part and non negative imaginary part procedure expt z1 z2 Returns z1 raised to the power z2 For z 1 0 z 1 z 2 e z 2 log z 1 0 z is 1 if z 0 and 0 otherwise procedure make rectangular x1 x2 procedure make polar x3 x4 procedure real part z procedure imag part z procedure magnitude z procedure angle z These procedures are part of every implementation that supports general complex numbers Suppose x1 x2 x3 and x4 are real numbers and z is a complex number such that z x1 x2 i x3 e i x4 Then make rectangular x1 x2 z make polar x3 x4 z real part z x1 imag part z x2 magnitude z x3 angle z x angle where pi x angle pi with x angle x4 2pi n for some integer n Rationale Magnitude is the same as abs for a real argument but abs must be present in all implementations whereas magnitude need only be present in implementations that support general complex numbers procedure exact inexact z procedure inexact exact z Exact inexact returns an inexact representation of z The value returned is the inexact number that is numerically closest to the argument If an exact argument has no reasonably close inexact equivalent then a violation of an implementation restriction may be reported Inexact exact returns an exact representation of z The value returned is the exact number that is numerically closest to the argument If an inexact argument has no reasonably close exact equivalent then a violation of an implementation restriction may be reported These procedures implement the natural one to one correspondence between exact and inexact integers throughout an implementation dependent range See section section Implementation restrictions Numerical input and output procedure number string z procedure number string z radix Radix must be an exact integer either 2 8 10 or 16 If omitted radix defaults to 10 The procedure number string takes a number and a radix and returns as a string an external representation of the given number in the given radix such that let number number radix radix eqv number string number number string number radix radix is true It is an error if no possible result makes this expression true If z is inexact the radix is 10 and the above expression can be satisfied by a result that contains a decimal point then the result contains a decimal point and is expressed using the minimum number of digits exclusive of exponent and trailing zeroes needed to make the above expression true howtoprint howtoread otherwise the format of the result is unspecified The result returned by number string never contains an explicit radix prefix Note The error case can occur only when z is not a complex number or is a complex number with a non rational real or imaginary part Rationale If z is an inexact number represented using flonums and the radix is 10 then the above expression is normally satisfied by a result containing a decimal point The unspecified case allows for infinities NaNs and non flonum representations procedure string number string procedure string number string radix Returns a number of the maximally precise representation expressed by the given string Radix must be an exact integer either 2 8 10 or 16 If supplied radix is a default radix that may be overridden by an explicit radix prefix in string e g o177 If radix is not supplied then the default radix is 10 If string is not a syntactically valid notation for a number then string number returns f string number 100 100 string number 100 16 256 string number 1e2 100 0 string number 15 1500 0 Note The domain of string number may be restricted by implementations in the following ways String number is permitted to return f whenever string contains an explicit radix prefix If all numbers supported by an implementation are real then string number is permitted to return f whenever string uses the polar or rectangular notations for complex numbers If all numbers are integers then string number may return f whenever the fractional notation is used If all numbers are exact then string number may return f whenever an exponent marker or explicit exactness prefix is used or if a appears in place of a digit If all inexact numbers are integers then string number may return f whenever a decimal point is used Other data types This section describes operations on some of Scheme s non numeric data types booleans pairs lists symbols characters strings and vectors Booleans The standard boolean objects for true and false are written as t and f What really matters though are the objects that the Scheme conditional expressions if cond and or do treat as true or false The phrase a true value or sometimes just true means any object treated as true by the conditional expressions and the phrase a false value or false means any object treated as false by the conditional expressions Of all the standard Scheme values only f counts as false in conditional expressions Except for f all standard Scheme values including t pairs the empty list symbols numbers strings vectors and procedures count as true Note Programmers accustomed to other dialects of Lisp should be aware that Scheme distinguishes both f and the empty list from the symbol nil Boolean constants evaluate to themselves so they do not need to be quoted in programs t t f f f f library procedure not obj Not returns t if obj is false and returns f otherwise not t f not 3 f not list 3 f not f t not f not list f not nil f library procedure boolean obj Boolean returns t if obj is either t or f and returns f otherwise boolean f t boolean 0 f boolean f Pairs and lists A pair sometimes called a dotted pair is a record structure with two fields called the car and cdr fields for historical reasons Pairs are created by the procedure cons The car and cdr fields are accessed by the procedures car and cdr The car and cdr fields are assigned by the procedures set car and set cdr Pairs are used primarily to represent lists A list can be defined recursively as either the empty list or a pair whose cdr is a list More precisely the set of lists is defined as the smallest set X such that The empty list is in X If list is in X then any pair whose cdr field contains list is also in X The objects in the car fields of successive pairs of a list are the elements of the list For example a two element list is a pair whose car is the first element and whose cdr is a pair whose car is the second element and whose cdr is the empty list The length of a list is the number of elements which is the same as the number of pairs The empty list is a special object of its own type it is not a pair it has no elements and its length is zero Note The above definitions imply that all lists have finite length and are terminated by the empty list The most general notation external representation for Scheme pairs is the dotted notation c1 c2 where c1 is the value of the car field and c2 is the value of the cdr field For example 4 5 is a pair whose car is 4 and whose cdr is 5 Note that 4 5 is the external representation of a pair not an expression that evaluates to a pair A more streamlined notation can be used for lists the elements of the list are simply enclosed in parentheses and separated by spaces The empty list is written For example a b c d e and a b c d e are equivalent notations for a list of symbols A chain of pairs not ending in the empty list is called an improper list Note that an improper list is not a list The list and dotted notations can be combined to represent improper lists a b c d is equivalent to a b c d Whether a given pair is a list depends upon what is stored in the cdr field When the set cdr procedure is used an object can be a list one moment and not the next define x list a b c define y x y a b c list y t set cdr x 4 unspecified x a 4 eqv x y t y a 4 list y f set cdr x x unspecified list x f Within literal expressions and representations of objects read by the read procedure the forms datum datum datum and datum denote two ele ment lists whose first elements are the symbols quote quasiquote unquote and unquote splicing respectively The second element in each case is datum This convention is supported so that arbitrary Scheme programs may be represented as lists That is according to Scheme s grammar every expression is also a datum see section see section External representations Among other things this permits the use of the read procedure to parse Scheme programs See section section External representations procedure pair obj Pair returns t if obj is a pair and otherwise returns f pair a b t pair a b c t pair f pair a b f procedure cons obj1 obj2 Returns a newly allocated pair whose car is obj1 and whose cdr is obj2 The pair is

Original URL path: http://www.mazama.net/scheme/doc/r5rs.htm (2016-04-30)

Open archived version from archive - Revised(4) Report on The Algorithmic Language Scheme

For example indexes into data structures must be known exactly as must some polynomial coefficients in a symbolic algebra system On the other hand the results of measurements are inherently inexact and irrational numbers may be approximated by rational and therefore inexact approximations In order to catch uses of inexact numbers where exact numbers are required Scheme explicitly distinguishes exact from inexact numbers This distinction is orthogonal to the dimension of type Exactness Scheme numbers are either exact or inexact A number is exact if it was written as an exact constant or was derived from exact numbers using only exact operations A number is inexact if it was written as an inexact constant if it was derived using inexact ingredients or if it was derived using inexact operations Thus inexactness is a contagious property of a number If two implementations produce exact results for a computation that did not involve inexact intermediate results the two ultimate results will be mathematically equivalent This is generally not true of computations involving inexact numbers since approximate methods such as floating point arithmetic may be used but it is the duty of each implementation to make the result as close as practical to the mathematically ideal result Rational operations such as should always produce exact results when given exact arguments If the operation is unable to produce an exact result then it may either report the violation of an implementation restriction or it may silently coerce its result to an inexact value See section Implementation restrictions With the exception of inexact exact the operations described in this section must generally return inexact results when given any inexact arguments An operation may however return an exact result if it can prove that the value of the result is unaffected by the inexactness of its arguments For example multiplication of any number by an exact zero may produce an exact zero result even if the other argument is inexact Implementation restrictions Implementations of Scheme are not required to implement the whole tower of subtypes given in section Numerical types but they must implement a coherent subset consistent with both the purposes of the implementation and the spirit of the Scheme language For example an implementation in which all numbers are real may still be quite useful Implementations may also support only a limited range of numbers of any type subject to the requirements of this section The supported range for exact numbers of any type may be different from the supported range for inexact numbers of that type For example an implementation that uses flonums to represent all its inexact real numbers may support a practically unbounded range of exact integers and rationals while limiting the range of inexact reals and therefore the range of inexact integers and rationals to the dynamic range of the flonum format Furthermore the gaps between the representable inexact integers and rationals are likely to be very large in such an implementation as the limits of this range are approached An implementation of Scheme must support exact integers throughout the range of numbers that may be used for indexes of lists vectors and strings or that may result from computing the length of a list vector or string The length vector length and string length procedures must return an exact integer and it is an error to use anything but an exact integer as an index Furthermore any integer constant within the index range if expressed by an exact integer syntax will indeed be read as an exact integer regardless of any implementation restrictions that may apply outside this range Finally the procedures listed below will always return an exact integer result provided all their arguments are exact integers and the mathematically expected result is representable as an exact integer within the implementation quotient remainder modulo max min abs numerator denominator gcd lcm floor ceiling truncate round rationalize expt Implementations are encouraged but not required to support exact integers and exact rationals of practically unlimited size and precision and to implement the above procedures and the procedure in such a way that they always return exact results when given exact arguments If one of these procedures is unable to deliver an exact result when given exact arguments then it may either report a violation of an implementation restriction or it may silently coerce its result to an inexact number Such a coercion may cause an error later An implementation may use floating point and other approximate representation strategies for inexact numbers This report recommends but does not require that the IEEE 32 bit and 64 bit floating point standards be followed by implementations that use flonum representations and that implementations using other representations should match or exceed the precision achievable using these floating point standards IEEE In particular implementations that use flonum representations must follow these rules A flonum result must be represented with at least as much precision as is used to express any of the inexact arguments to that operation It is desirable but not required for potentially inexact operations such as sqrt when applied to exact arguments to produce exact answers whenever possible for example the square root of an exact 4 ought to be an exact 2 If however an exact number is operated upon so as to produce an inexact result as by sqrt and if the result is represented as a flonum then the most precise flonum format available must be used but if the result is represented in some other way then the representation must have at least as much precision as the most precise flonum format available Although Scheme allows a variety of written notations for numbers any particular implementation may support only some of them For example an implementation in which all numbers are real need not support the rectangular and polar notations for complex numbers If an implementation encounters an exact numerical constant that it cannot represent as an exact number then it may either report a violation of an implementation restriction or it may silently represent the constant by an inexact number Syntax of numerical constants The syntax of the written representations for numbers is described formally in section Lexical structure A number may be written in binary octal decimal or hexadecimal by the use of a radix prefix The radix prefixes are b binary o octal d decimal and x hexadecimal With no radix prefix a number is assumed to be expressed in decimal A numerical constant may be specified to be either exact or inexact by a prefix The prefixes are e for exact and i for inexact An exactness prefix may appear before or after any radix prefix that is used If the written representation of a number has no exactness prefix the constant may be either inexact or exact It is inexact if it contains a decimal point an exponent or a character in the place of a digit otherwise it is exact In systems with inexact numbers of varying precisions it may be useful to specify the precision of a constant For this purpose numerical constants may be written with an exponent marker that indicates the desired precision of the inexact representation The letters s f d and l specify the use of short single double and long precision respectively When fewer than four internal inexact representations exist the four size specifications are mapped onto those available For example an implementation with two internal representations may map short and single together and long and double together In addition the exponent marker e specifies the default precision for the implementation The default precision has at least as much precision as double but implementations may wish to allow this default to be set by the user 3 14159265358979F0 Round to single 3 141593 0 6L0 Extend to long 600000000000000 Numerical operations The reader is referred to section Entry format for a summary of the naming conventions used to specify restrictions on the types of arguments to numerical routines The examples used in this section assume that any numerical constant written using an exact notation is indeed represented as an exact number Some examples also assume that certain numerical constants written using an inexact notation can be represented without loss of accuracy the inexact constants were chosen so that this is likely to be true in implementations that use flonums to represent inexact numbers essential procedure number obj essential procedure complex obj essential procedure real obj essential procedure rational obj essential procedure integer obj These numerical type predicates can be applied to any kind of argument including non numbers They return t if the object is of the named type and otherwise they return f In general if a type predicate is true of a number then all higher type predicates are also true of that number Consequently if a type predicate is false of a number then all lower type predicates are also false of that number If z is an inexact complex number then real z is true if and only if zero imag part z is true If x is an inexact real number then integer x is true if and only if x round x complex 3 4i t complex 3 t real 3 t real 2 5 0 0i t real e1e10 t rational 6 10 t rational 6 3 t integer 3 0i t integer 3 0 t integer 8 4 t Note The behavior of these type predicates on inexact numbers is unreliable since any inaccuracy may affect the result Note In many implementations the rational procedure will be the same as real and the complex procedure will be the same as number but unusual implementations may be able to represent some irrational numbers exactly or may extend the number system to support some kind of non complex numbers essential procedure exact z essential procedure inexact z These numerical predicates provide tests for the exactness of a quantity For any Scheme number precisely one of these predicates is true essential procedure z1 z2 z3 essential procedure x1 x2 x3 essential procedure x1 x2 x3 essential procedure x1 x2 x3 essential procedure x1 x2 x3 These procedures return t if their arguments are respectively equal monotonically increasing monotonically decreasing monotonically nondecreasing or monotonically nonincreasing These predicates are required to be transitive Note The traditional implementations of these predicates in Lisp like languages are not transitive Note While it is not an error to compare inexact numbers using these predicates the results may be unreliable because a small inaccuracy may affect the result this is especially true of and zero When in doubt consult a numerical analyst essential procedure zero z essential procedure positive x essential procedure negative x essential procedure odd n essential procedure even n These numerical predicates test a number for a particular property returning t or f See note above essential procedure max x1 x2 essential procedure min x1 x2 These procedures return the maximum or minimum of their arguments max 3 4 4 exact max 3 9 4 4 0 inexact Note If any argument is inexact then the result will also be inexact unless the procedure can prove that the inaccuracy is not large enough to affect the result which is possible only in unusual implementations If min or max is used to compare numbers of mixed exactness and the numerical value of the result cannot be represented as an inexact number without loss of accuracy then the procedure may report a violation of an implementation restriction essential procedure z1 essential procedure z1 These procedures return the sum or product of their arguments 3 4 7 3 3 0 4 4 1 essential procedure z1 z2 essential procedure z procedure z1 z2 essential procedure z1 z2 essential procedure z procedure z1 z2 With two or more arguments these procedures return the difference or quotient of their arguments associating to the left With one argument however they return the additive or multiplicative inverse of their argument 3 4 1 3 4 5 6 3 3 3 4 5 3 20 3 1 3 essential procedure abs x Abs returns the magnitude of its argument abs 7 7 essential procedure quotient n1 n2 essential procedure remainder n1 n2 essential procedure modulo n1 n2 These procedures implement number theoretic integer division For positive integers n1 and n2 if n3 and n4 are integers such that n1 n2 n3 n4 0 n4 and n4 n2 Then quotient n1 n2 n3 remainder n1 n2 n4 modulo n1 n2 n4 For integers n1 and n2 with n2 not equal to 0 n1 n2 quotient n1 n2 remainder n1 n2 t provided all numbers involved in that computation are exact The value returned by quotient always has the sign of the product of its arguments Remainder and modulo differ on negative arguments the remainder is either zero or has the sign of the dividend while the modulo always has the sign of the divisor modulo 13 4 1 remainder 13 4 1 modulo 13 4 3 remainder 13 4 1 modulo 13 4 3 remainder 13 4 1 modulo 13 4 1 remainder 13 4 1 remainder 13 4 0 1 0 inexact essential procedure gcd n1 essential procedure lcm n1 These procedures return the greatest common divisor or least common multiple of their arguments The result is always non negative gcd 32 36 4 gcd 0 lcm 32 36 288 lcm 32 0 36 288 0 inexact lcm 1 procedure numerator q procedure denominator q These procedures return the numerator or denominator of their argument the result is computed as if the argument was represented as a fraction in lowest terms The denominator is always positive The denominator of 0 is defined to be 1 numerator 6 4 3 denominator 6 4 2 denominator exact inexact 6 4 2 0 essential procedure floor x essential procedure ceiling x essential procedure truncate x essential procedure round x These procedures return integers Floor returns the largest integer not larger than x Ceiling returns the smallest integer not smaller than x Truncate returns the integer closest to x whose absolute value is not larger than the absolute value of x Round returns the closest integer to x rounding to even when x is halfway between two integers Rationale Round rounds to even for consistency with the default rounding mode specified by the IEEE floating point standard Note If the argument to one of these procedures is inexact then the result will also be inexact If an exact value is needed the result should be passed to the inexact exact procedure floor 4 3 5 0 ceiling 4 3 4 0 truncate 4 3 4 0 round 4 3 4 0 floor 3 5 3 0 ceiling 3 5 4 0 truncate 3 5 3 0 round 3 5 4 0 inexact round 7 2 4 exact round 7 7 procedure rationalize x y Rationalize returns the simplest rational number differing from x by no more than y A rational number r1 is simpler than another rational number r2 if r1 p1 q1 and r2 p2 q2 in lowest terms and abs p1 abs p2 and abs q1 abs q2 Thus 3 5 is simpler than 4 7 Although not all rationals are comparable in this ordering consider 2 7 and 3 5 any interval contains a rational number that is simpler than every other rational number in that interval the simpler 2 5 lies between 2 7 and 3 5 Note that 0 0 1 is the simplest rational of all rationalize inexact exact 3 1 10 1 3 exact rationalize 3 1 10 i1 3 inexact procedure exp z procedure log z procedure sin z procedure cos z procedure tan z procedure asin z procedure acos z procedure atan z procedure atan y x These procedures are part of every implementation that supports general real numbers they compute the usual transcendental functions Log computes the natural logarithm of z not the base ten logarithm Asin acos and atan compute arcsine arccosine and arctangent respectively The two argument variant of atan computes angle make rectangular x y see below even in implementations that don t support general complex numbers In general the mathematical functions log arcsine arccosine and arctangent are multiply defined For nonzero real x the value of log x is defined to be the one whose imaginary part lies in the range pi exclusive to pi inclusive log 0 is undefined The value of log z when z is complex is defined according to the formula define log z log magnitude z i angle z With log defined this way the values of arcsin arccos and arctan are according to the following formulae define asin z i log i z sqrt 1 z z define acos z pi 2 asin z define atan z log 1 i z 1 i z i 2 The above specification follows CLTL which in turn cites PENFIELD81 refer to these sources for more detailed discussion of branch cuts boundary conditions and implementation of these functions When it is possible these procedures produce a real result from a real argument procedure sqrt z Returns the principal square root of z The result will have either positive real part or zero real part and non negative imaginary part procedure expt z1 z2 Returns z1 raised to the power z2 define expt z1 z2 exp z2 log z1 expt 0 0 is defined to be equal to 1 procedure make rectangular x1 x2 procedure make polar x3 x4 procedure real part z procedure imag part z procedure magnitude z procedure angle z These procedures are part of every implementation that supports general complex numbers Suppose x1 x2 x3 and x4 are real numbers and z is a complex number such that z x1 i x2 x3 exp i x4 Then make rectangular and make polar return z real part returns x1 imag part returns x2 magnitude returns x3 and angle returns x4 In the case of angle whose value is not uniquely determined by the preceding rule the value returned will be the one in the range pi exclusive to pi inclusive Rationale Magnitude is the same as abs for a real argument but abs must be present in all implementations whereas magnitude need only be present in implementations that support general complex numbers procedure exact inexact z procedure inexact exact z Exact inexact returns an inexact representation of z The value returned is the inexact number that is numerically closest to the argument If an exact argument has no reasonably close inexact equivalent then a violation of an implementation restriction may be reported Inexact exact returns an exact representation of z The value returned is the exact number that is numerically closest to the argument If an inexact argument has no reasonably close exact equivalent then a violation of an implementation restriction may be reported These procedures implement the natural one to one correspondence between exact and inexact integers throughout an implementation dependent range See section Implementation restrictions Numerical input and output essential procedure number string number essential procedure number string number radix Radix must be an exact integer either 2 8 10 or 16 If omitted radix defaults to 10 The procedure number string takes a number and a radix and returns as a string an external representation of the given number in the given radix such that let number number radix radix eqv number string number number string number radix radix is true It is an error if no possible result makes this expression true If number is inexact the radix is 10 and the above expression can be satisfied by a result that contains a decimal point then the result contains a decimal point and is expressed using the minimum number of digits exclusive of exponent and trailing zeroes needed to make the above expression true HOWTOPRINT HOWTOREAD otherwise the format of the result is unspecified The result returned by number string never contains an explicit radix prefix Note The error case can occur only when number is not a complex number or is a complex number with a non rational real or imaginary part Rationale If number is an inexact number represented using flonums and the radix is 10 then the above expression is normally satisfied by a result containing a decimal point The unspecified case allows for infinities NaNs and non flonum representations essential procedure string number string essential procedure string number string radix Returns a number of the maximally precise representation expressed by the given string Radix must be an exact integer either 2 8 10 or 16 If supplied radix is a default radix that may be overridden by an explicit radix prefix in string e g o177 If radix is not supplied then the default radix is 10 If string is not a syntactically valid notation for a number then string number returns f string number 100 100 string number 100 16 256 string number 1e2 100 0 string number 15 1500 0 Note Although string number is an essential procedure an implementation may restrict its domain in the following ways String number is permitted to return f whenever string contains an explicit radix prefix If all numbers supported by an implementation are real then string number is permitted to return f whenever string uses the polar or rectangular notations for complex numbers If all numbers are integers then string number may return f whenever the fractional notation is used If all numbers are exact then string number may return f whenever an exponent marker or explicit exactness prefix is used or if a appears in place of a digit If all inexact numbers are integers then string number may return f whenever a decimal point is used Characters Characters are objects that represent printed characters such as letters and digits Characters are written using the notation character or character name For example a lower case letter A upper case letter left parenthesis the space character space the preferred way to write a space newline the newline character Case is significant in character but not in character name If character in character is alphabetic then the character following character must be a delimiter character such as a space or parenthesis This rule resolves the ambiguous case where for example the sequence of characters space could be taken to be either a representation of the space character or a representation of the character s followed by a representation of the symbol pace Characters written in the notation are self evaluating That is they do not have to be quoted in programs Some of the procedures that operate on characters ignore the difference between upper case and lower case The procedures that ignore case have ci for case insensitive embedded in their names essential procedure char obj Returns t if obj is a character otherwise returns f essential procedure char char1 char2 essential procedure char char1 char2 essential procedure char char1 char2 essential procedure char char1 char2 essential procedure char char1 char2 These procedures impose a total ordering on the set of characters It is guaranteed that under this ordering The upper case characters are in order For example char A B returns t The lower case characters are in order For example char a b returns t The digits are in order For example char 0 9 returns t Either all the digits precede all the upper case letters or vice versa Either all the digits precede all the lower case letters or vice versa Some implementations may generalize these procedures to take more than two arguments as with the corresponding numerical predicates essential procedure char ci char1 char2 essential procedure char ci char1 char2 essential procedure char ci char1 char2 essential procedure char ci char1 char2 essential procedure char ci char1 char2 These procedures are similar to char et cetera but they treat upper case and lower case letters as the same For example char ci A a returns t Some implementations may generalize these procedures to take more than two arguments as with the corresponding numerical predicates essential procedure char alphabetic char essential procedure char numeric char essential procedure char whitespace char essential procedure char upper case letter essential procedure char lower case letter These procedures return t if their arguments are alphabetic numeric whitespace upper case or lower case characters respectively otherwise they return f The following remarks which are specific to the ASCII character set are intended only as a guide The alphabetic characters are the 52 upper and lower case letters The numeric characters are the ten decimal digits The whitespace characters are space tab line feed form feed and carriage return essential procedure char integer char essential procedure integer char n Given a character char integer returns an exact integer representation of the character Given an exact integer that is the image of a character under char integer integer char returns that character These procedures implement injective order isomorphisms between the set of characters under the char ordering and some subset of the integers under the ordering That is if char a b t and x y t and x and y are in the domain of integer char then char integer a char integer b t char integer char x integer char y t essential procedure char upcase char essential procedure char downcase char These procedures return a character char2 such that char ci char char2 In addition if char is alphabetic then the result of char upcase is upper case and the result of char downcase is lower case Strings Strings are sequences of characters Strings are written as sequences of characters enclosed within doublequotes A doublequote can be written inside a string only by escaping it with a backslash as in The word recursion has many meanings A backslash can be written inside a string only by escaping it with another backslash Scheme does not specify the effect of a backslash within a string that is not followed by a doublequote or backslash A string constant may continue from one line to the next but the exact contents of such a string are unspecified The length of a string is the number of characters that it contains This number is a non negative integer that is fixed when the string is created The valid indexes of a string are the exact non negative integers less than the length of the string The first character of a string has index 0 the second has index 1 and so on In phrases such as the characters of string beginning with index start and ending with index end it is understood that the index start is inclusive and the index end is exclusive Thus if start and end are the same index a null substring is referred to and if start is zero and end is the length of string then the entire string is referred to Some of the procedures that operate on strings ignore the difference between upper and lower case The versions that ignore case have ci for case insensitive embedded in their names essential procedure string obj Returns t if obj is a string otherwise returns f essential procedure make string k essential procedure make string k char Make string returns a newly allocated string of length k If char is given then all elements of the string are initialized to char otherwise the contents of the string are unspecified essential procedure string char Returns a newly allocated string composed of the arguments essential procedure string length string Returns the number of characters in the given string essential procedure string ref string k k must be a valid index of string String ref returns character k of string using zero origin indexing essential procedure string set string k char k must be a valid index of string and char must be a character String set stores char in element k of string and returns an unspecified value define f make string 3 define g string set f 0 unspecified string set g 0 error string set symbol string immutable 0 error essential procedure string string1 string2 essential procedure string ci string1 string2 Returns t if the two strings are the same length and contain the same characters in the same positions otherwise returns f String ci treats upper and lower case letters as though they were the same character but string treats upper and lower case as distinct characters essential procedure string string1 string2 essential procedure string string1 string2 essential procedure string string1 string2 essential procedure string string1 string2 essential procedure string ci string1 string2 essential procedure string ci string1 string2 essential procedure string ci string1 string2 essential procedure string ci string1 string2 These procedures are the lexicographic extensions to strings of the corresponding orderings on characters For example string is the lexicographic ordering on strings induced by the ordering char on characters If two strings differ in length but are the same up to the length of the shorter string the shorter string is considered to be lexicographically less than the longer string Implementations may generalize these and the string and string ci procedures to take more than two arguments as with the corresponding numerical predicates essential procedure substring string start end String must be a string and start and end must be exact integers satisfying 0 start end string length string Substring returns a newly allocated string formed from the characters of string beginning with index start inclusive and ending with index end exclusive essential procedure string append string Returns a newly allocated string whose characters form the concatenation of the given strings essential procedure string list string essential procedure list string chars String list returns a newly allocated list of the characters that make up the given string List string returns a newly allocated string formed from the characters in the list chars String list and list string are inverses so far as equal is concerned procedure string copy string Returns a newly allocated copy of the given string procedure string fill string char Stores char in every element of the given string and returns an unspecified value Vectors Vectors are heterogenous structures whose elements are indexed by integers A vector typically occupies less space than a list of the same length and the average time required to access a randomly chosen element is typically less for the vector than for the list The length of a vector is the number of elements that it contains This number is a non negative integer that is fixed when the vector is created The valid indexes of a vector are the exact non negative integers less than the length of the vector The first element in a vector is indexed by zero and the last element is indexed by one less than the length of the vector Vectors are written using the notation obj For example a vector of length 3 containing the number zero in element 0 the list 2 2 2 2 in element 1 and the string Anna in element 2 can be written as following 0 2 2 2 2 Anna Note that this is the external representation of a vector not an expression evaluating to a vector Like list constants vector constants must be quoted 0 2 2 2 2 Anna 0 2 2 2 2 Anna essential procedure vector obj Returns t if obj is a vector otherwise returns f essential procedure make vector k procedure make vector k fill Returns a newly allocated vector of k elements If a second argument is given then each element is initialized to fill Otherwise the initial contents of each element is unspecified essential procedure vector obj Returns a newly allocated vector whose elements contain the given arguments Analogous to list vector a b c a b c essential procedure vector length vector Returns the number of elements in vector essential procedure vector ref vector k k must be a valid index of vector Vector ref returns the contents of element k of vector vector ref 1 1 2 3 5 8 13 21 5 8 vector ref 1 1 2 3 5 8 13 21 inexact exact round 2 acos 1 13 essential procedure vector set vector k obj k must be a valid index of vector Vector set stores obj in element k of vector The value returned by vector set is unspecified let vec vector 0 2 2 2 2 Anna vector set vec 1 Sue Sue vec 0 Sue Sue Anna vector set 0 1 2 1 doe error constant vector essential procedure vector list vector essential procedure list vector list Vector list returns a newly allocated list of the objects contained in the elements of vector List vector returns a newly created vector initialized to the elements of the list list vector list dah dah didah dah dah didah list vector dididit dah dididit dah procedure vector fill vector fill Stores fill in every element of vector The value returned by vector fill is unspecified Control features This chapter describes various primitive procedures which control the flow of program execution in special ways The procedure predicate is also described here essential procedure procedure obj Returns t if obj is a procedure otherwise returns f procedure car t procedure car f procedure lambda x x x t procedure lambda x x x f call with current continuation procedure t essential procedure apply proc args procedure apply proc arg1 args Proc must be a procedure and args must be a list The first essential form calls proc with the elements of args as the actual arguments The second form is a generalization of the first that calls proc with the elements of the list append list arg1 args as the actual arguments apply list 3 4 7 define compose lambda f g lambda args f apply g args compose sqrt 12 75 30 essential procedure map proc list1 list2 The list s must be lists and proc must be a procedure taking as many arguments as there are list s If more than one list is given then they must all be the same length Map applies proc element wise to the elements of the list s and returns a list of the results in order from left to right The dynamic order in which proc is applied to the elements of the list s is unspecified map cadr a b d e g h b e h map lambda n expt n n 1 2 3 4 5 1 4 27 256 3125 map 1 2 3 4 5 6 5 7 9 let count 0 map lambda ignored set count count 1 count a b c unspecified essential procedure for each proc list1 list2 The arguments to for each are like the arguments to map but for each calls proc for its side effects rather than for its values Unlike map for each is guaranteed to call proc on the elements of the list s in order from the first element to the last and the value returned by for each is unspecified let v make vector 5 for each lambda i vector set v i i i 0 1 2 3 4 v 0 1 4 9 16 procedure force promise Forces the value of promise see section Delayed evaluation If no value has been computed for the promise then a value is computed and returned The value of the promise is cached or memoized so that if it is forced a second time the previously computed value is returned force delay 1 2 3 let p delay 1 2 list force p force p 3 3 define a stream letrec next lambda n cons n delay next n 1 next 0 define head car define tail lambda stream force cdr stream head tail tail a stream 2 Force and delay are

Original URL path: http://www.mazama.net/scheme/doc/r4rs.htm (2016-04-30)

Open archived version from archive - Pocket Scheme - The Artistic License

involved in handling the item It also means that recipients of the item may redistribute it under the same conditions they received it You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction provided that you duplicate all of the original copyright notices and associated disclaimers You may apply bug fixes portability fixes and other modifications derived from the Public Domain or from the Copyright Holder A Package modified in such a way shall still be considered the Standard Version You may otherwise modify your copy of this Package in any way provided that you insert a prominent notice in each changed file stating how and when you changed that file and provided that you do at least ONE of the following place your modifications in the Public Domain or otherwise make them Freely Available such as by posting said modifications to Usenet or an equivalent medium or placing the modifications on a major archive site such as uunet uu net or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package use the modified Package only within your corporation or organization rename any non standard executables so the names do not conflict with standard executables which must also be provided and provide a separate manual page for each non standard executable that clearly documents how it differs from the Standard Version make other distribution arrangements with the Copyright Holder You may distribute the programs of this Package in object code or executable form provided that you do at least ONE of the following distribute a Standard Version of the executables and library files together with instructions in the manual page or equivalent on where to get the Standard Version accompany the distribution with the machine readable source of the Package with your modifications give non standard executables non standard names and clearly document the differences in manual pages or equivalent together with instructions on where to get the Standard Version make other distribution arrangements with the Copyright Holder You may charge a reasonable copying fee for any distribution of this Package You may charge any fee you choose for support of this Package You may not charge a fee for this Package itself However you may distribute this Package in aggregate with other possibly commercial programs as part of a larger possibly commercial software distribution provided that you do not advertise this Package as a product of your own You may embed this Package s interpreter within an executable of yours by linking this shall be construed as a mere form of aggregation provided that the complete Standard Version of the interpreter is so embedded The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package but belong to whomever generated them and may be sold commercially and may be aggregated with this Package

Original URL path: http://www.mazama.net/scheme/license.htm (2016-04-30)

Open archived version from archive