IA36

  • Upload
    maxbyz

  • View
    223

  • Download
    0

Embed Size (px)

Citation preview

  • 7/29/2019 IA36

    1/12The Icon Analyst 36 / 1

    June 1996Number 36

    In this issue

    Building a Visual Interface ........ 1

    Subscription Renewal ................ 4

    Quiz ............................................. 5

    Loading C Functions .................. 5

    Icon Glossary ............................... 9

    Answers to Quiz ....................... 12

    Whats Coming Up................... 12

    In-Depth Coverage of the Icon Programming Language

    Building a Visual Interface

    This is the fourth article in theseries describing how visual interfacesare built using VIB. We hope you arestill with us.

    In the last article on this subject,we added a menu and two buttons tothe interface for the kaleidoscope application.The four sliders are next.

    The image above shows a newly created sliderfor controlling the speed of this display and itsdialog box after editing. Since the dialog has notyet been dismissed, the newly created slider isshown in its original size and orientation.

    Weve changed the default vertical orienta-tion to horizontal and set the range from 500 to 0,anticipating that the left end of the slider will

    The Edited Slider Dialog

    Icon on the Web

    Information about Icon is available on the WorldWide Web at

    http://www.cs.arizona.edu/icon/

  • 7/29/2019 IA36

    2/122 / The Icon Analyst 36

    correspond to slow and the rightend to fast.

    We set the filter toggle so thatintermediate events are filtered out.Thus, the program gets a callback onlywhen the mouse button is released tolet go of the slider. If the intermedi-

    ate events are not filtered out, thereare callbacks for every movement ofthe slider.

    This deserves some discussion.Since most of the values associatedwith the kaleidoscope sliders requirethe display to be restarted, callbacksfor intermediate slider positions arenot useful and would provide no vi-sual feedback for the user. In fact, ifevents are not filtered out, there is no

    way for the application to know whichevent is the last onewhen the user ismanipulating the slider.

    On the other hand, in an application thatallows viewing a portion of a large image througha small pane, intermediate slider events to positionthe image should not be filtered out instead,each movement of the slider can be used to reposi-tion the portion of the image being viewed so thatthe user can see whats going on and when torelease the slider.

    Of course, you may not know whether filter-ing is appropriate or not until you get into thedetails of writing the application code. As withother aspects of a visual interface, its easy to goback and change the attributes of a slider.

    The image above shows the slider after it hasbeen positioned. Getting the size and position of

    the slider just right may take some

    experimentation.Three more sliders are needed.

    We could repeat the process we usedfor the first slider, but we can savesome work by making copies of thefirst slider. Entering @Cwhen a vidgetis selected makes a copy of the selectedvidget. @C stands for entering c withthe meta key held down. This is a com-mon convention for interfaces built withVIB.

    The new vidget wont be wherewe want it, and well have to changesome of its attributes, but it will be thesame size as the vidget from which wemade the copy, which is what we wantin our layout.

    The image at the left shows thefour sliders in place. The interface istaking shape; at this point the resultsshould be satisfying.

    One Slider in Place

    All Sliders in Place

  • 7/29/2019 IA36

    3/12The Icon Analyst 36 / 3

    Configuring the Radio Buttons

    Configuring the Radio Buttons

    The radio buttons are next. As isthe case for menus, three radio buttonsare provided by default. Adding anddeleting radio buttons and changingtheir names is similar to the process formenu items.

    The image at the right shows anewly created set of radio buttons andthe dialog after it has been edited. Theresults are shown in the next image.

    Weve saved the labels until lastfor a good reason: We couldnt be surethe sliders were where we wanted themuntil the radio buttons were in place.Twelve labels are needed and movinglabels around after creating them is alot of work we want to be sure thatall the buttons and sliders to be labeledare just where we want them. This is

    one of several things youre likely tolearn the hard way, as we did.

    As we mentioned in an earlierarticle, labels are vidgets that dontaccept events and produce no callbacks.Other than that, they are created andmanipulated like any other vidgets.

    The image at the top of the nextpage shows a newly created labelvidget and its dialog box before edit-ing. Well use this label to identify the

    speed slider and need to change its text(label) accordingly. The result is shownon the next page.

    We wont bore you with all thedetails, but once one label is created,others can be made by copying andediting as we did for sliders.

    Its a good idea to think about thisbefore starting. Four of the labels iden-tify sliders and might be created andpositioned first.

    After thats complete, the labelsfor the ends of the sliders can be done,

    noting the fact that two sets of three have the sametext.

    Weve created all the vidgets and they are atleast approximately where we want them. Thatdoesnt mean the interface will never change; asthe application develops, new functionality mayrequire additions or changes to the interface. With

    The Radio Buttons in Place

    Back Issues

    Back issues ofThe Icon Analyst are availablefor $5 each. This price includes shipping in theUnited States, Canada, and Mexico. Add $2per order for airmail postage to other coun-tries.

  • 7/29/2019 IA36

    4/124 / The Icon Analyst 36

    a good foundation, though, futurechanges will not be so hard.

    The completed interface is shownat the top of the next page.

    Next Time

    The interface in VIB looks like itwill look when the application is run.Its possible, however, to see the appli-cation in action without leaving VIB what user actions on different vidgetsdo, when callbacks occur, what theyare, and so on.

    Well cover these matters in thenext issue of the Analyst and thenfinish up with VIB by describing itsmenus (which weve not needed yet)and the kind of code it produces.

    Subscription RenewalFor many of you, this issue is the last in your

    present subscription to the Analyst. If so, youllfind a renewal form in the center of this issue.Renew now so that you wont miss an issue.

    Your prompt renewal also helps us by reduc-ing the number of follow-up notices we have tosend. Knowing where we stand on subscriptionsalso lets us plan our budget for the next fiscal year.

    A Label Dialog

    One Label in Place

    Downloading Icon Material

    Most implementations of Icon are available fordownloading via FTP:

    ftp.cs.arizona.edu (cd /icon)

  • 7/29/2019 IA36

    5/12The Icon Analyst 36 / 5

    The Complete Kaleidoscope Interface

    Quiz

    Several Icon functions provide default valuesfor omitted or null-valued arguments. This littlequiz is designed to test your knowledge of thesedefaults. The answers are on page 12.

    Suppose that

    word := "Casablanca"

    1. What are the results produced by the fol-lowing expressions? If an expression fails or causesa run-time error, note that.

    left(word)

    right(word)

    center(word)

    map(word)

    repl(word)

    2. What is the default for s2 in open(s1, s2)?3. What is the default for i in sort(X, i)?

    4. What doesstop() (with no arguments) write?

    Loading C Functions Dynamically

    Dynamic loading provides a way to use func-tions coded in C in an Icon program without modi-fying the Icon system itself. The C code is compiled

    and placed in a library, then loadedfrom the library when the Icon pro-gram runs.

    Version 9.0 of Icon introduceddynamic loading. It is supported onUNIX systems that provide the SystemV loader interface specified by the C

    header file , including sys-tems from Sun, Digital, and SGI.

    We will start by showing differ-ent ways to load a C function from theIcon program library. After that, welldiscuss how to write a new functionand well go through the steps that areneeded to make use of it.

    Program Library Functions

    The Icon program library [1] in-

    cludes an assortment of loadable UNIXinterfaces and special-purpose func-tions. Here is a sampling:

    bitcount(i) count the bits set in an integer

    chmod(s, i) change the permissions of a file

    fpoll(f, i) poll a file for input, with timeoutgetpid() return the process identification

    numberkill(i1, i2) send a signal to a process

    lgconv(i) convert a large integer to a string

    tconnect(s, i) connect a file to a TCP port

    umask(i) change the process permissionmask

    The full set of functions can be found in thelibraryscfuncsdirectory. Documentation and codeare also available on-line on the Web [2]. Well usethe bitcount() function in our first examples.

    Prebuilt C libraries are included with thebinary distributions of Icon for SunOS, Solaris,Digital UNIX, and SGI Irix. Well assume that abinary distribution has been unpacked into a direc-tory named/icon, and so the function library file is

    named/icon/bin/libcfunc.so.

    Loading a Function

    The built-in Icon function loadfunc(libname,funcname) loads the C function funcname() fromthe library file libname and returns a procedurevalue. If the function cannot be loaded, the pro-gram is terminated.

    If loadfunc(libname, "myfunc") produces p,then

  • 7/29/2019 IA36

    6/126 / The Icon Analyst 36

    p(arguments) calls myfunc() with a listof arguments

    type(p) returns "procedure"

    image(p) returns "function myfunc"

    proc("myfunc") returns p

    proc("myfunc", 0) fails

    The following program loads the functionbitcount() and assigns it to a global variable of thesame name. Assigning it to a global variable makesit available to other procedures, although thats notneeded here. The bitcount() function returns thenumber of bits that are set in the binary represen-tation of an integer.

    $define Library "/icon/bin/libcfunc.so"

    global bitcount

    procedure main()

    local ibitcount := loadfunc(Library, "bitcount")

    every i := 250 to 260 do

    write(i, " ", bitcount(i))

    end

    When this program is run, it lists the integersfrom 250 to 260 along with their bit counts:

    250 6

    251 7

    252 6

    253 7

    254 7

    255 8

    256 1

    257 2

    258 2

    259 3

    260 2

    Loading from a Path

    Embedding a file name such as /icon/bin/

    libcfunc.so in the program is undesirable. An alter-native is for the program to find the library fileusing information from the program environment.

    The Icon library procedure pathload(libname,funcname) searches the set of directories given bythe FPATH environment variable to find libnameand load funcname. As is usual in Icon path search-ing, the current directory is searched first. If thefunction cannot be loaded, the program is termi-nated.

    The pathload() procedure is included by link-ing pathfind from the Icon program library. Usingpathload(), the example program becomes:

    $define Library "libcfunc.so"

    link pathfind

    global bitcount

    procedure main()local i

    bitcount := pathload(Library, "bitcount")

    every i := 250 to 260 do

    write(i, " ", bitcount(i))

    end

    FPATH must be set before the program isrun. A suggested value for FPATH is given by theSetup script that is run when installing UNIXbinaries of Icon. For our hypothetical configura-tion, FPATH could be set by

    setenv FPATH "/icon/bin/"

    Implicit Function Loading

    It is possible to encapsulate the loading pro-cess so that the body of an Icon program is unawarethat it is calling a C function. Consider this ex-ample:

    $define Library "libcfunc.so"

    link pathfind

    procedure main()local i

    every i := 250 to 260 do

    write(i, " ", bitcount(i))

    end

    procedure bitcount(n)

    bitcount := pathload(Library, "bitcount")

    return bitcount(n)

    end

    First of all, notice that there is no longer aglobal declaration for bitcount, and that the mainprocedure no longer calls pathload(). As far as themain procedure is concerned, bitcount() is justanother procedure to call, with no special require-ments. This is a nice simplification.

    The new bitcount() procedure is a bit tricky,though. To understand it, you must know that anIcon procedure declaration creates a global vari-able with an initial value of that procedure. A

  • 7/29/2019 IA36

    7/12The Icon Analyst 36 / 7

    global variable is subject to assignment.

    When main() calls bitcount() for the first time,thebitcount()procedure loads the bitcount()C func-tion from the library. The result is assigned to theglobal variable bitcount, replacing the current pro-cedure value. Consequently, all subsequent callsto bitcount() use the loaded function.

    The first call to bitcount()remains incompleteafter loading the function; the bits ofn still must becounted. So, following loading, the procedure callsbitcount(n). Although this looks like a recursivecall, it isnt the call uses the current value of theglobal variable bitcount, and so it calls the loaded Cfunction. The bits ofn are counted and returned,completing the first call.

    After the first time, calls to bitcount() go di-rectly to the loaded code. The Icon procedurebitcount() is no longer accessible.

    Implicit Library Loading

    The Icon program library provides an im-plicit loading procedure for each of the C functionsin the library. Small procedures like the bitcount()procedure shown above are included by linkingcfunc. Using the library interface procedure, ourexample now can be simplified to this:

    link cfunc

    procedure main()

    local i

    every i := 250 to 260 do

    write(i, " ", bitcount(i))

    end

    The link cfuncdeclaration is the only hint thatbitcount() is written in C. Of course, FPATH muststill be set to run this program.

    Making Connections

    The bit counting example doesnt really illus-

    trate the full potential of using C functions in anIcon program. Bit counting, after all, can be done inIcon. Heres something that cant.

    The library function tconnect(host, port) es-tablishes a TCP connection to a specified portnumber on an Internet host. TCP is a communica-tion protocol used by telnet programs, news serv-ers, Web servers, and many other network ser-vices.

    The following program makes a connection

    to the Icon Web server and writes the contents ofthe Icon home page in its original HTML markuplanguage, of course.

    link cfunc

    procedure main()

    local f

    f := tconnect("www.cs.arizona.edu", 80)writes(f, "GET /icon/ HTTP/1.0\n\n")

    flush(f)

    seek(f, 1)

    while write(read(f))

    end

    The tconnect() call establishes the connectionand returns a file that is open for both input andoutput. The internet host www.cs.arizona.edu isour departments Web server. Port 80 is used by

    most Web servers, including ours.The program then transmits a request for the/icon/Web page. The details of the request stringare specified by the Hypertext Transfer Protocol[3], which we wont discuss here.

    The flush() call ensures that all the data isactually sent, and then the seek() call resets the filein preparation for a switch from output to input. Inthis situation seek() does not actually repositionthe file, but its required when switching modes.

    Finally, lines are read and echoed until anend-of-file is received.

    Writing Loadable C Functions

    Weve seen how functions can be loadedfrom the library; now lets consider how to writethem.

    Because the Icon system expects C functionsto implement a certain interface, dynamic loadingusually requires specially written C functions. Ingeneral, it is not possible to use an existing Cfunction without writing an intermediate gluefunction.

    C functions must deal with the data typesused by the Icon run-time system, notably thedescriptors that represent all Icon values. Whilean understanding of the Icon run-time system [4, 5]is helpful, it is possible to create useful functions bymodeling them after existing library functions.Integer and string values are most easily handled.

    A loadable C function has the prototype

    int funcname(int argc, descriptor argv)

  • 7/29/2019 IA36

    8/128 / The Icon Analyst 36

    whereargc is the number of arguments and argv isan array of argument descriptors. The first ele-ment, argv[0], is used to return an Icon value, andis initialized to a descriptor for the null value. Thiselement is not included in the count argc. Theactual arguments begin with argv[1].

    If the C function returns zero, the call from

    Icon succeeds. A negative value indicates failure. Ifa positive value is returned, it is interpreted as anerror number and a fatal error with that number issignalled. In this case, ifargv[0] is non-null, it isreported as the offending value. There is no wayfor a C function to suspend, and no way to indicatea null value as an offending value in the case of anerror.

    Interface Macros

    The C file icall.h contains a set of macros for

    use in writing loadable functions. Documentationis included as comments. This file is not included inbinary distributions of Icon but can be found in thecfuncs directory in the source code of the Iconprogram library. Alternatively, it can be loadedfrom the Web [2]. Macros are provided for:

    inspecting the type of an Icon value

    validating the type of an argument

    converting an Icon value into a C value

    returning a C value in Icon form

    failing or signaling an error

    Most macros deal with integers or strings.Some support also is provided for handling realand file values.

    Counting Bits, Again

    For a concrete example of a C function, wewill revisit the bitcount() function used earlier andlook at its source code:

    #include "icall.h"

    int bitcount(int argc, descriptor argv)

    {

    unsigned long v;

    int n;

    ArgInteger(1);

    v = IntegerVal(argv[1]);

    n = 0;

    while (v != 0) {

    n += v & 1;

    v >>= 1;

    }

    RetInteger(n);

    }

    Like all loadable functions, bitcount() is aninteger function with two parameters, argc andargv.

    The ArgInteger macro call verifies that argu-ment 1 is a simple integer. (Large integers aretypically rejected by C functions because of theextra work involved.) If argument 1 is missing orhas the wrong type, ArgInteger makes the functionreturn error code 101 (integer expected or out ofrange).

    The IntegerVal macro call extracts the valueof the first argument.

    In each pass through the while loop, the low-order bit ofv is extracted (v & 1), added to n, and

    shifted off (v >>= 1). When no more nonzero bitsare left, the loop exits. Note that v is declaredunsigned to ensure that only zero bits are insertedby the shift operation.

    The RetInteger macro call returns the valueofn as an Icon integer.

    Preparing a Library

    To be used in an Icon program, a C functionmust be built and installed in a library. Compila-tion comes first, usually involving a command

    such ascc c bitcount.c

    to produce an object file bitcount.o. Were assum-ing that icall.h has been copied to the currentdirectory, although other methods are also pos-sible. Thec option causes a relocatable object fileto be produced instead of a stand-alone executableprogram. Other options, such as optimization op-tions, also could be specified.

    A C function can be loaded only from ashared library. Even if there is just one function,

    it must be placed in a library. Library names con-ventionally end with a .so suffix.

    It seems that every system has a differentway to create libraries, usually involving specialflags to cc or ld. The program library file mklib.shis a shell script that embodies our understanding ofshared library creation. It takes one argument nam-ing the library to be created and one or moreadditional arguments listing object file names. Forexample, the command

  • 7/29/2019 IA36

    9/12The Icon Analyst 36 / 9

    The Icon Analyst

    Ralph E. Griswold, Madge T. Griswold,

    and Gregg M. TownsendEditors

    The Icon Analyst is published six times a year. Aone-year subscription is $25 in the United States,Canada, and Mexico and $35 elsewhere. To sub-scribe, contact

    Icon ProjectDepartment of Computer ScienceThe University of ArizonaP.O. Box 210077Tucson, Arizona 85721-0077U.S.A.

    voice: (520) 621-6613

    fax: (520) 621-4246

    Electronic mail may be sent to:

    [email protected]

    and

    Bright Forest Publishers

    Tucson Arizona

    1996 by Ralph E. Griswold, Madge T. Griswold,and Gregg M. Townsend

    All rights reserved.

    mklib.sh mylib.so bitcount.o

    creates a filemylib.socontaining the functions readfrombitcount.o. Like icall.h, mklib.sh is available inthe program library source code or from the Web.

    Conclusion

    We will close with a review of the key points:

    Icon can load C functions on many UNIX sys-tems.

    The C functions must be tailored to Icons re-quirements.

    Each function must be loaded before it can becalled.

    A simple Icon procedure can be used to hide theloading details.

    pathload() searches FPATH to find a function

    library. Some useful functions are provided in the Icon

    program library.

    Wed be pleased to hear of any interestingapplications you find for dynamic function load-ing, and additional contributions to the Icon pro-gram library always are welcome.

    References

    1. R. E. Griswold and G. M. Townsend, The IconProgram Library; Version 9.2 , Department of Com-

    puter Science, The University of Arizona, IconProject Document IPD272, 1996.

    2. The Icon Project, Program Library Index:Loadable C Functions, Department of ComputerScience, The University of Arizona, WWW http://www.cs.arizona.edu/icon/library/ccfuncs.html.

    3. T. Berners-Lee, R. Fielding, and H. Frystyk,Hypertext Transfer Protocol HTTP/1.0, workin progress, Internet Engineering Task Force, Feb-ruary 19, 1996, WWW http://www.ics.uci.edu/pub/

    ietf/http/draft-ietf-http-v10-spec-05.html.

    4. R. E. Griswold and M. T. Griswold,The Imple-mentation of the Icon Programming Language, Prince-ton University Press, Princeton, New Jersey, 1986.

    5. R. E. Griswold, Supplementary Information for theImplementation of Version 9 of Icon, Department ofComputer Science, The University of Arizona, IconProject Document IPD239, 1995.

    Icon Glossary

    This is second part of a glossary of Icon terms.There will be one or two more parts, depending onhow much space we have in upcoming Analysts.When the glossary is complete, well provide acopy as a supplement to the Analyst.

    If you have questions or suggestions aboutmaterial in the glossary, please let us know.

    activation: evaluation of a co-expression.

    allocation: the process of providing space inmemory for values created during programexecution.See also: garbage collection.

  • 7/29/2019 IA36

    10/1210 / The Icon Analyst 36

    conjunction: a binary operation that evaluates itsoperands but performs no computation onthem; used to test if two expressions bothsucceed. Conjunction has the effect of logicaland. See also: mutual evaluation and disjunc-tion.

    control character: acharacter that has special inter-

    pretation in an input/output context. For ex-ample, linefeed or newline.

    control structure: an expression whose evaluationmay alter the otherwise sequential order ofevaluation ofexpressions.

    data type: a designation that identifies values thatshare common properties andoperations. Iconhas 12 data types: co-expression, cset, file,integer, list, null, procedure, real, set, string,table, and window. In addition, each recorddeclaration defines a data type. The term datatype often is shortened to type.

    declaration: a component of a program that speci-fies its properties and structure. There are sevenkinds of declarations: global, local, static, pro-cedure, record, link, and invocable.

    default case clause: a component of a case expres-sion that contains an expression that is evalu-ated if no other expression is selected in a caseexpression. A default case clause is indicatedby the reserved word default.

    default value: a value that is provided in place ofan omitted or null-valued argumentof a func-tion.

    default table value: a value specified when a tableis created that serves as the value correspond-ing to keys that are not in the table.

    define directive: a preprocessor directive that as-sociates a symbol (name) with a string so thatthe string is substituted for subsequent uses ofthe symbol in the program.

    disjunction: logical or; used to describe the effectofalternation. See also conjunction.

    environment variable: a named attribute of thesystem environment under which a programruns. Environment variables can be used tospecify the size of Icons memoryregions, thelocations oflibraries, and so forth.

    error: a condition or situation that is invalid. Errorsmay occur during translation, linking, com-piling, or execution. An error in translationprevents linking. An error in linking preventsthe production of an icode file. An error that

    alternation: a control structure that generates theresults of its first operand followed by theresults of its second operand. See also disjunc-tion.

    argument: an expression that provides a value fora function or procedure call; sometimes usedto mean operand.

    associativity: the order in which like operatorsareevaluated in the absence of parentheses. Asso-ciativity can be left-to-right, in which case thefirst (left-most) operator is evaluated first orright-to-left, in which case the last (right-most)operator is evaluated first.

    augmented assignment: assignment combinedwith a binary operation. The binary operationis performed on the value of the left-operandvariable and the value of the right operand,and then the result is assigned to the left-operand variable.

    built-in: a feature that is part of the Icon pro-gramming language, as opposed to a featurewritten in Icon.

    case expression: a control structure in which anexpression to evaluate is selected dependingon a value.

    co-expression: an expression coupled with an en-vironment for its execution. If theexpression isa generator, its results can be obtained one at atime by activation.

    character: the elementary unit from which stringsandcsets are composed. Characters are used torepresent letters, digits, punctuation marks,and so forth. Characters are represented inter-nally by small nonnegative integers (typically8 bits). Some characters have associatedglyphs.Icon has no character data type.

    collating sequence: the sorting order for stringsimposed by the internal representation ofchar-acters.

    command-line argument: a string given after the

    program name when Icon is invoked from acommand line. Command-line arguments arepassed to the main procedureas a list ofstringsin its first argument.

    comparison operation: a binary operation thatcompares two valuesaccording to a specifiedcriterion. A comparison operation succeedsand returns the value of its right operand if thecriterion is satisfied. Otherwise it fails. See alsonumerical comparison, lexical comparison,and value comparison.

  • 7/29/2019 IA36

    11/12The Icon Analyst 36 / 11

    occurs during execution is called a run-timeerror. See also error conversion.

    error conversion: changing run-time errors to ex-pression failure rather than program termina-tion. This is accomplished by setting a pro-gram state using a keyword.

    escape sequence: a sequence of characters in astring or cset literal that encodes a single char-acter. Escape sequences usually are used forcharacters that cannot be given literally.

    function: a built-in procedure.

    garbage collection: the process of reclaiming spacein memory that has been allocated but nolonger needed.Garbage collection occurs auto-matically when insufficient space remains forallocation.Garbage collection can be forced bycollect().

    global variable: a variable whose value is acces-sible throughout the entire program and fromthe beginning ofexecution to the end.

    glyph: a symbol such as a letter, digit, or punctua-tion mark.

    heterogeneous structure: a structure whose ele-ments have different types.

    homogeneous structure: a structure all of whoseelements have the same type.

    initial clause: an optional component of a proce-dure that contains expressions that are evalu-

    ated only on the first invocation of the proce-dure.

    invocable declaration: a declaration that specifiesthat procedures are to be included when aprogram is linked, even if there is no explicitreference to them in the program. Such proce-dures may be called using string invocation.

    invocation: the evaluation of a procedureor func-tion. Invocation and call are sometimes usedsynonymously.

    keyword: An ampersand (&) followed by a string

    of letters that has a special meaning. Somekeywords are variables.

    lexical comparison: comparison of strings al-phabeticallyaccording tothe numerical val-ues used to represent characters. Also calledstring comparison.See alsocollating sequence.

    library module: a file consisting of one or moreproceduresor other declarations that have beentranslated into ucode so that they may beincorporated in a program by linking.

    limitation: restricting the number of times a gen-erator is resumed. Limitation can be specifiedby a control structure or because of the syntac-tic context in which the generator appears. Seealso bounded expression.

    line terminator: a character or pair ofcharactersthat is used by convention to mark the end a

    line of text in a file. In UNIX, the line terminatoris a linefeedcharacter; on the Macintosh, it isthe returncharacter; in DOS, it is a linefeedcharacterfollowed by a returncharacter. Otherplatforms generally use one of these conven-tions. See also: newline character.

    link declaration: a declaration that causes a li-brary module to be included in a programduring linking.

    literal: a sequence ofcharacters in a source pro-gram that directly represents a value, as the

    integer 1 and the string"hello".local variable: a variable that is accessible only to

    the procedure in which it is declared and dur-ing a single invocationof the procedure. Localvariables are created when a procedure is in-voked and are destroyed when the procedurereturns or fails, but not when the proceduresuspends. See also: global variable and staticvariable.

    matching function: a function that returns a por-tion of the subject in string scanning. The term

    can be extended to include matching proce-dures.

    memory: the space in which a program and theobjects it creates are stored. Memory is imple-mented in RAM. Also called storage.

    memory region: a portion of memory used forstoring Icon values. There are separate memoryregions for strings and for other objects. Alsocalled storage region.

    mixed-mode arithmetic: arithmetic on a combina-tion ofintegers and real numbers to produce a

    real number. Any arithmetic operation thathas a real operand produces a real value.

    mutual evaluation: an expression consisting ofan argument list, but with no function orprocedure. A mutual evaluation expressionsucceeds only if all the expressions in theargument list succeed. The result of a spe-cific argument can be selected by an integerpreceding the argument list.

    newline character: the single character used to

  • 7/29/2019 IA36

    12/12/ Th I A l t

    map(word) "casablanca"

    The next one may surprise you; there is nodefault for the number of times to replicate a string,so repl(word) causes a run-time error. This seems tous like an inconsistency in language design; adefault of 1 would have been better.

    2. The default for s2 in open(s1, s2) is "rt". The"r"should be familiar. The "t" enables the translatedmode for input, so that line terminators automati-cally are converted to newline characters. This isonly an issue for platforms such as MS-DOS andthe Macintosh, where line terminators are notnewline characters. The converse operation is per-formed on output. The result is to make line termi-nators transparent.

    3. The default for i in sort(X, i) is 1. For tables,the result is a list of two-element key/value lists.For other types, the second argument is not used.

    4. stop() is tricky. Except for the fact that stop()terminates program execution and writes to stan-dard error output instead of standard output bydefault,stop() treats its arguments in the same waywrite() does it writes them in succession andadds a line terminator. With no arguments, write()writes a a blank (empty) line, and stop() does too.Such a blank line usually causes no harm, but itmay be disconcerting when output is to the screen.

    Whats Coming Up

    We have lots of things on deck. Theres an-other article in the series on building visual inter-faces, another article on versum numbers, an ar-ticle on dynamic analysis that takes a differentapproach from past ones, and more of the glossary.

    represent a line terminator in Icon regardlessof the actual representation used in the under-lying system.

    object: in the most general sense, any value. Morespecifically, a value that is represented by apointer to memory. These are strings, csets,files, real numbers, large integers, co-expres-

    sions, procedures, windows, and data struc-tures. Sometimes the term object is used for justdata structures.

    operand: an expression that provides a value foran operation. See also argument.

    operation:an expression that is part of the built-incomputational repertoire of Icon and cast inthe form of an operator and operands. Some-times used in a broader sense to include func-tion and procedure calls to characterize ex-pressions that are not control structures.

    operator: a symbol consisting of one or more char-acters that designates an operation.

    parameter: an identifier in a procedure declara-tion that provides a variable to which a valueis passed when the procedure is called. Param-eters are local variables.

    passing arguments: the assignment ofargumentvalues in a procedure call to the parameters ofthe procedure.

    Answers to the Quiz

    1. The second argument ofleft(), right(), andcenter(), which determines the length of the result,defaults to 1, so the answers for these are:

    left(word) "C"

    right(word) "a"

    center(word) "l"

    In the case ofcenter(word), ifwordhas an evennumber of characters, as it does here, the result is

    the character to the right of center.While 1 may seem like a useless default for

    field length, it actually can be useful. For example,left(s) can be thought of as producing the left-mostcharacter ofs. Programs written using these func-tions in this way may be difficult for others tounderstand, however.

    The second and third arguments of map()default to upper- and lowercase letters, respec-tively, so the answer is