Dylan Interim Reference Manual - June 3, 1994

download Dylan Interim Reference Manual - June 3, 1994

of 214

Transcript of Dylan Interim Reference Manual - June 3, 1994

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    1/214

    Dylan

    TM

    InterimReference Manual

    June 3, 1994

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    2/214

    1992-1994 Apple C omp uter , Inc.

    All rights reserved.

    Apple Comp uter, Inc.

    20525 Mariani Avenu e

    Cupertino, CA 95014-6299

    408-996-1010

    Apple, and th e Apple Logo are tradema rks of Apple Compu ter, Inc., registered in the United States and other

    countries. Dylan is a trademar k of Apple Compu ter.

    Smalltalk-80 is a trad ema rk of ParcPlace System s. PL/ I is a trad ema rk of Interna tional Business Machines Corp. Eiffel

    is a tr adema rk of Interactive Software Engineering, Inc.

    Limited W arranty on M edia and Replacement

    Even though App le has reviewed this manu al, Apple makes no warranty or rep resentation , either express or implied,

    with respect to this m anual, its qu ality, accuracy, merchantability, or fitness for a particular p urpose; as a result, this

    manu al is provided "as is," and you, the reader, are assum ing the entire risk as to its quality and accuracy.

    In no event will Apple be liable for direct, indirect, special, incidental, or consequential d amages resu lting from any

    defect or inaccuracy in this m anual, even if advised of the p ossibility of such d amages.

    The warrant y and remedies set forth above are exclusive and in lieu of all others, oral or written, express or implied.

    No App le dealer, agent, or employee is authorized to m ake any m odification, extension, or addition to this warran ty.

    Some states do n ot allow th e exclusion or limitation of imp lied warr anties or liability for incidental or consequential

    dam ages, so the above limitation or exclusion may not ap ply to you. This warranty gives you specific legal rights, and

    you may also have other rights which vary from state to state.

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    3/214

    Dylan Interim Reference Manual June 3, 1994 i

    About this Manual

    When the first Dylan m anu al was p ublished in 1992, it was met w ith anenthusiastic respon se. People agreed with our goals for the language, andman y people suggested ways in wh ich Dylan could better m eet its goals.

    Since that time, an expanded group of engineers both inside and outside App lehave w orked to refine the langu age design in response to those suggestions.The language has become simp ler and more efficient. Loose end s have beentied u p. The language has been given a new syntax. Throughou t this process,changes to the langu age design have been p ublished electronically in the formof design notes.

    With the exception of the macro system, the cur rent rou nd of language designis now essentially comp lete. A new Dylan language reference will bepu blished early in 1995. The new book w ill be the definitive specification ofthe Dylan language. App le is working closely w ith other Dylan imp lementorsto ensure that the new book w ill not be App le-specific, but will app ly equallyto all Dylan implementations.

    We realize that many people wan t to read abou t Dylan now ! For that reason,to fill the gap un til the new book is published , weve put together the DylanInterim Reference Manual. This document is an interim user reference for theDylan language. It combines the original Dylan book, the previouslypu blished d esign notes, and add itional previously un pu blished d esign

    decisions as of May 1994.

    Our goal for this interim d ocument h as been to get something useful out toyou as soon as possible, not to sp end time refining it, so its important toun derstand the limitations of this docum ent:

    This is a very rough document, intended only as a temp orary user referenceun til the new Dylan book is ready. The writing and formatting are messyin places. We hope youll excuse us.

    This document is not intended as a language specification. There are placeswh ere it is imp recise or inconsistent. We hope you will un derstand thatthese are shortcomings of this docum ent, and not of the language d esign asa whole.

    This document is not intended as a tutorial or introduction to Dylanprogram ming. We assume that you are already somewhat familiar with

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    4/214

    ii June 3, 1994 Dylan Interim Reference Manual

    object oriented p rogram ming. You will often need to devise your ownexamples and flip back and forth through the manu al as you read .

    Despite these limitations, we think that th is document w ill be useful to peop lewh o want to learn abou t Dylan, especially to those peop le who are u sing anearly Dylan imp lementation. Enjoy, and let us know w hat you think!

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    5/214

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    6/214

    iv June 3, 1994 Dylan Interim Reference Manual

    Defining New Classes .................................................................................... 69Slot Op tions ..................................................................................................... 71Instance crea tion ............................................................................................. 78

    Reflective Op erations on Types ................................................................... 84Coercing an d Cop ying Objects..................................................................... 86The classes , , and ........................................... 87

    8. Control ling D ynamism .................................................................................... 91

    Declaring characteristics of classes .............................................................. 91Declar ing sealing of gen eric fun ctions ........................................................ 92The seal generic form ..................................................................................... 92

    9. Collections .......................................................................................................... 95

    Function s for Collections .............................................................................. 96Function s for Sequences .............................................................................. 101The Instantiable Collection Classes ........................................................... 110

    Op erations on Arrays .................................................................................. 113Op erations on Deques .................................................................................115Op erations on Lists ...................................................................................... 116Op erations on Ran ges.................................................................................. 118Op erations on Stretch y Vectors .................................................................. 119Op erations on Strin gs .................................................................................. 119Op erations on Tables ................................................................................... 121Op erations on Vectors .................................................................................122The Iterat ion Protocol .................................................................................. 122Iteration Stability and Natu ral Order ........................................................ 128Collection Keys ............................................................................................ 128Mu tability ...................................................................................................... 130Collection Alignment ................................................................................... 132Defining a N ew Collection Class: A Summary ........................................ 134

    10. Characters and Symbols .............................................................................. 135

    Characters ...................................................................................................... 135Symbols ......................................................................................................... 136

    11. Numbers ......................................................................................................... 137

    Au tom atic Type Con version ...................................................................... 137Numeric Classes ........................................................................................... 138Gen eral Ar ithmetic Function s .................................................................... 138

    12. Other Operations ........................................................................................... 143

    Function al Op erations .................................................................................143Function application .................................................................................... 146Identity function ........................................................................................... 146

    13. Conditions .....................................................................................................147

    Backgrou nd ................................................................................................... 147

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    7/214

    Dylan Interim Reference Manual June 3, 1994 v

    Overview ....................................................................................................... 149Specification .................................................................................................. 152

    14. Modules .......................................................................................................... 163

    Overview ....................................................................................................... 163Program s, mod ule declarations ................................................................. 164Module declarations .................................................................................... 165Exam ples ....................................................................................................... 168

    15. Libraries .......................................................................................................... 171

    Appendix A: How to get more information ................................................... 175

    Appendix B: Dylan Syntax BNF....................................................................... 177

    Lexical gram mar ........................................................................................... 177Phrase Gram mar .......................................................................................... 183

    Index ...................................................................................................................... 189

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    8/214

    vi June 3, 1994 Dylan Interim Reference Manual

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    9/214

    Dylan Interim Reference Manual June 3, 1994 vii

    Forew ord to the First Editionby Larry Tesler

    In the m id-1980s, a number of researchers in App les Advanced TechnologyGroup (ATG) d iscovered that exploration of their software ideas wasincreasingly constrained by languages and tools. They migrated a significantnu mber of projects from Object Pascal, C, and C++ to Smalltalk, Lisp, andvarious know ledge-engineering environmen ts.

    Soon m anagemen t became concerned that technologies developed in theseun related environments would not be able to play together. Boldly, weprop osed adop tion of a single dyn amic program ming environment through outthe group . The goal was acknowledged, but we soon found that none of the

    environments we w ere using could m eet every need. For some p rojects,Comm on Lisp w as too big. For others, Smalltalk-80s simplicity w as limiting.And of course, there were forcefu lly stated d ifferences in personal preference.

    Hu mbled, we decided to search outside the compan y for an environment thatsatisfied a ll requiremen tsat least technical considera tions, if not m atters oftaste. We encountered some interesting languages, includ ing Eiffel, Self, Beta,and OakLisp, to name just a few, but we could find no environment that m etour requirements.

    Reluctantly, we entertained the thou ght of designing yet an other language.We envisioned a language that wou ld:

    combine the best aspects of Lisp and Smalltalk

    provide static language users an attractive dynamic alternative

    be practical on small machines

    provide high dynamism d uring rapid prototyping and development

    provide tools to achieve commercial performance in production code

    During this exercise, we w ere app roached by an App le engineering groupseeking an object-oriented dynamic langu age for a contemplated prod uct.Instead of developing a language just for research, we agreed that ATG wouldstrive to create a system practical for d elivery of comm ercial applications.

    After some analysis, we conclud ed that a langu age that w ould meet all ourrequ irements w ould be more like Lisp than Smalltalk, except that, likeSmalltalk, it would be objects all the way dow n. By providing alternate

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    10/214

    viii June 3, 1994 Dylan Interim Reference Manual

    syntaxes atop the extremely neu tral base of Lisp, we believed we could presenta familiar face not only to Lisp p rogram mers, but also to those accustomed toother syntaxes, includ ing Smalltalks.

    We felt we could n ot design a good language w ithout concurrentlyimplementing it. But w e did n ot have the skills in hou se to implement thekind of language we envisioned. Around that time we were app roached byMassachusetts-based Coral Software, Inc., which was seeking to be acquired .Coral had created a p opu lar Comm on Lisp implementation distingu ished byits small memory footprint, very usable speed, interesting object system, andthorough integration into the Macintosh. A few m onths later, we acquired theassets of the comp any, hired m ost of the staff, and created ATG East inCambridge.

    We asked th e new group to accept two challenges: (1) continu e to develop

    their Common Lisp imp lementation, add ing CLOS, ephemeral garbagecollection, and other features; and (2) develop a new langu age andenvironment m eeting the aforementioned requirements. They accepted bothchallenges. The first led to the very pop ular prod uct known as MacintoshComm on Lisp (MCL) 2.0. The second led to Dylan.

    Dylan is not yet a frozen language. Debates about p roposed imp rovementscontinue. But enou gh of Dylan has been d esigned , imp lemented , andexperienced that n ow is the time to take it pu blic and benefit from the w isdomof a wider programming comm un ity. We welcome your comments.

    Larry TeslerCupertino, California

    March 1992

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    11/214

    Dylan Interim Reference Manual June 3, 1994 ix

    Preface to the First Editionby Ike Nassi

    Since its foun ding, App le Comp uter has been dedicated to th e cause of movingthe power of compu ters into the hand s of comp uter users. Our m ostsuccessful product to date has been the App le Macintosh. Since itsintroduction eight year s ago, Macintosh has defined the state of the art incomputer ease of learning and ease of use. Macintosh , almost single-hand edly,has transformed th e way we use comp uters.

    Its time to tran sform the way w e program them, as well.

    In 1984, before Macintosh, comp uter users were asked to m ake their work

    pa tterns conform to the requ irements of the machine in front of them . Allaspects of comp uting were presented in terms defined by the comp uter. Theuser w as given little control over the organization of da ta, the order in w hichtasks were performed, and the manner in which work was presented. Themachine presented a m odel wh ich had little to do w ith the users world, andthe user had no choice but to conform to this model. Rather than facilitatework, the comp uter came between the user and the users work. The user hadto overcome the computer before getting an y work don e.

    In 1992, the situation is still mu ch the same for programm ers. There is still alarge gap betw een software p rodu ct conception and software p rodu ctrealization. This gap is filled w ith bits, bytes, arrays, machine-level debu ggers,

    dan gling pointers, hours-long recompilations, and mon ths-long d esign andredesign cycles. Program mers are still asked to p resent their high-level ideasof program behav ior in low-level terms defined by CPU architectures of theearly 1970s. Program ming work flow is still d ictated by the historicallimitations of compilers, linkers, and debuggers. Program design in 1992 isreminiscent of typograp hical design in 1982: design and execution areperformed by a series of specialists, resulting in an aw kward , length y andexpensive design, test, and redesign p rocess.

    Time-to-marketis consistently rated very high in lists of factors affecting thesuccess of high technology produ cts. The end result of poor program ming

    tools is either poor time-to-market or poor programs. Software companies arefaced w ith a dilemma: they can take years, and do the job right, or they can cutcorners and get their software into the market before their comp etitors.Neither solution results in a healthy software ind ustry. Neither solutionallows our p rodu cts to keep u p w ith our visions.

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    12/214

    x June 3, 1994 Dylan Interim Reference Manual

    Software d evelopm ent today also has a large barrier to entry. Only compan ieswith deep finan cial resources can bring a full fledged ap plication to market.The result is a loss of healthy competition an d fresh ideas in the software field .

    Finally, our compu ting engines are becoming more diverse. In addition to theusual dimensions of speed, memory capacity, screen resolution,interconnectedness, pow er consump tion, and size, the underlying operatingsystems and toolboxes are becoming broad er in scope. Specificimplementations can also become more focused, requiring a higher d egree oftailorability. For examp le, with the introd uction of mobile computing,software requirements may change as locations chan ge. Software used onmobile compu ters needs to be able to rapidly respond to spontaneouslychanging conditions in a reliable way.

    Object oriented p rogramm ing takes importan t steps towards fixing these

    problems. By letting program mers structure the text of their program s interms of the p roblem at h and , object oriented program ming narrows the gapbetween conception and realization. How ever, object oriented program mingby itself is insufficient. It addresses how program s are described , but it doesnot address many p roblems of the day-to-day activity of program ming. Itdoesnt change program mings awkw ard work flow, nor d oes it make an yguaran tees about robustness, nor d oes it relieve the p rogramm er of manytedious bookkeeping tasks, tasks which are better performed by a comp uterthan by a human .

    Todays most p opu lar object oriented languages are still static languages. In

    such langu ages, most of the informa tion about objects is d iscard ed d ur ingcomp ilation, so p rograms cannot be m odified without recomp ilation, anddebugging is more likely to occur a t machine level than the level at which theprogram was d esigned . In add ition, these langu ages encourage m ixing objectswith non-object oriented bits and bytes. Even objects can be treated asun differentiated bits, leading to the possibility of protocol violations andobscure errors. Finally, there is no attemp t to pu t the process of program minginto the hand s of the programmer. Generally speaking, large programs muststill be written in their entirety before they can be comp iled and tested.

    Static object oriented langu ages provide only half of a solution. The other ha lfis provided by dynamism , yielding w hat Ap ple calls object oriented dynamic

    languages, or OODLs. In add ition to sup por ting the object orientedmethod ology, OODLs must sup port a nu mber of features which guaran teethat program ming takes place in terms d efined by the program mer, ratherthan in the terms of the hard ware.

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    13/214

    Dylan Interim Reference Manual June 3, 1994 xi

    OODLs must sup port rap id creation, delivery, and subsequent m odification ofambitious, reliable, and efficient software. Among the specific requ irementsan ideal OODL shou ld satisfy are the following:

    Automatic Memory Management

    Memory managemen t bugs are among the most comm on and difficult errorsin static programm ing languages. Bugs involving d angling pointers andtwice-freed objects are notoriously hard to track down.

    The langu age run -time, and not the p rogramm er, shou ld be responsible forallocating storage for objects and reclaiming the storage of objects which are nolonger used. There shou ld be no explicit procedu re calls for allocating ordeallocating mem ory, or for d eallocating objects.

    In a well engineered implementation, automatic mem ory man agement shou ld

    be robust and scalable. It shou ld not create memory fragm entation, or fail inthe presence of large (possibly virtual) ad dress spaces. It shou ld not causeseemingly arbitrary and un pred ictable delays for end users.

    In a true OODL, there shou ld be no machine-level pointers, only objects. Oncefreed from dealing w ith pointers, the programm er can begin to think of objectsat a higher level and the pr imitives become comparably richer. For examp le, aprogram mer w orking w ith collections of objects does not need to worry abou tmem ory leaks as collections expand and contract. The program mer canconcentrate on the task at hand , rather than on the bookkeeping d etails.

    Many large program ming p rojects begin w ith the design of a m emory

    man agement subsystem. There is no reason that this task should not beperformed once, and the corresponding imp lementation of that d esignembod ied in the language ru n-time, and thereby mad e available to allprogrammers.

    Dynamic Linking/ Incremental Development

    Programm ers shou ld have the ability to build u p th eir program s piece bypiece, integrating preexisting pieces when p ossible and wh ere available. Thetransition between rapid p rototyping and m ainstream d evelopm ent should becontinuou s rather than d iscrete. It should not require chang ing langu ages ortools.

    This requ irement affects the program ming p rocess in at least four ways:

    During the initial construction of a program, classes and functions can becomp iled and tested individu ally. This gives programm ers the freedom to

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    14/214

    xii June 3, 1994 Dylan Interim Reference Manual

    use a bottom-up p rogram ming style, if they so choose, obviating the needfor the construction of a comp lex sup erstructure for initial testing.

    During debugging, individu al functions and classes can be redefinedwithout resorting to a full recompilation of the program and perhap swithout even halting the execution of the program .

    Programs can be delivered in components, wh ich can be linked together oneither the d evelopm ent m achine or the end -user m achine, using bu ilt-inlanguage features.

    Program p atches (i.e., field up grades) can be distributed to end-users usingbuilt-in language features. App lying the patch should be a very lowoverhead op eration. There should be virtually no performance pena lty forexecuting patched code. Because you don t need source code for the

    original application in order to app ly the patch, traditional intellectua lprop erty issues arising from propagating source code simply need notarise.

    Self Identifying Objects / Introspection

    Operations should be checked for type safety before they are performed. Ifpossible, this check shou ld be performed at compile-time, otherw ise it shou ldbe performed a t run-time. This featu re guarantees that type errors are noticedas soon as they occur, before they can p ropagate and cause system corrup tion.Because the integrity of the object model is mainta ined, error rep orting canoccur in term s of program mer objects and end -user objects, rather than in

    machine-level terms. In man y cases, complete error recovery is possible.

    The language should contain features for introsp ection. This mean s that thelanguage ru n-time shou ld have sufficient p ower to an swer qu estions aboutitself and the objects it manages. For example, it shou ld be possible atexecution time to an alyze the stru cture of an object, find the su bclasses of aclass, etc.

    To facilitate typ e-safety and introspection, objects are self-ident ifying inmem ory. Unless all uses of an object can be analyzed at comp ile-time, the run -time mem ory for the object shou ld contain enou gh information to identify itsclass and value.

    Object Oriented Programming Environment

    The programm ing environment should present all debu gging information atan object oriented level. Errors should be described in high -level terms similarto those used by the p rogramm er in constructing the program. Inspection

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    15/214

    Dylan Interim Reference Manual June 3, 1994 xiii

    facilities should show a p rogram as a collection of objects, not as a m ass ofun differentiated bits. There shou ld be tools for performance analysis andmonitoring of single objects as w ell as collections of objects.

    There should be rich libraries of componen ts, and the means to navigate withinand between them and to organize and ad minister them.

    There shou ld be a w ell thought ou t distinction between d evelopm entenvironment an d execution environment, and w here they are d ifferent, thedevelopment environm ent should man age the comm un ication between themin as transparen t a mann er as possible. This feature is missing from cur rentOODLs, but it is essential for the delivery of OODL-based ap plications to end-users.

    An imp ortant aspect of these features is that they are mu tually sup porting,

    forming an organic whole. The simp lest imp lementation of each d epend s on theexistence of the others. For examp le, au tomatic mem ory managemen t relies onthe ability to walk memory and identify objects. Anoth er example is that rap idprototyping requ ires rapid mod ification of the p rogram, and so incrementaldynamic linking becomes essential. Incremental dyn amic relinking u tilizesautom atic reclamation of storage occup ied by the fun ctions, method s, and databeing replaced.

    Many p eople in comm ercial indu stry and in the research comm un ity haverecognized the p roblems w ith static langu ages, and some have started to buildproducts that p rovide some of the features of OODLs. For examp le, interactiveprogram ming environments for static langu ages are beginning to appear. We

    app laud th is developmen t. How ever, we believe that starting w ith a staticlangu age requires too many comp romises. If each OODL feature were to beadd ed in isolation, the mu tually supp orting characteristics would be lost,creating red und ancy, conflicts, and inefficiency. When instead these featuresare built together into the core of a p rogramm ing system, they p rovide asimp le and secure foundation for growth.

    The common criticism of OODLs is that we cannot afford th em. Mostprogram mers view OODLs as slow and as memory hogs. The commonwisdom is that OODLs do not m ake good use of machine resources.Fortunately, this view is out of date. The combination of improved OODL

    implementation technology and increasingly pow erful hard ware m ake OODLseminently practical. Every year or two our h ardw are gets twice as fast and hastwice as much memory. Would anyone say that the qua lity of our softwarehas increased at the same rate? Programm ing mu st be made easier, or thefastest hard ware in the w orld w ill only give us incremental software

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    16/214

    xiv June 3, 1994 Dylan Interim Reference Manual

    improvem ents. By investing a few cycles we can enable a new generation ofapplications.

    When Macintosh w as first released, many p eople thought that wind ows,menu s, and a bit map ped display were a waste of machine resources. We seein retrospect that this was not true. What good is the pow er of a compu ter, if itcant be accessed by a u ser?

    This book d escribes Dylan, a new object oriented d ynamic langu agedesigned by Ap ple. Dylan is our attempt at a langu age wh ich is simple, yetpow erful, one which keeps program ming at a h igh level but wh ich can becompiled efficiently and h as a relatively modest memory footprint.

    App le already has one OODL produ ct: Macintosh Comm on Lisp. Dylan isintended to comp lement Com mon Lisp, not to replace it. Common Lisp is a

    rich environm ent defined by a standard and available in compatibleimplementations on a broad range of platforms. Dylan is lean and stripp eddow n to a minimu m feature set. At present Dylan is not available on anyplatform (outside App le), but is intend ed to ru n on a w ide variety of machines,includ ing very small machines that dont have the horsepower to sup port amod ern Comm on Lisp. Common Lisp is aimed primarily at the Lispcommun ity, while Dylan is accessible to application d evelopers unfamiliarwith Lisp. Common Lisp is oriented m ore toward s exploratory programm ingwith delivery capability, while Dylan is oriented m ore towards delivery w ithexploratory capability.

    In our research and development labs, Apple has its own implementations of

    Dylan, wh ich are being prod uced hand in glove with the langu age definitionas a design assurance measure. We wou ld like to see others create add itionalimplementations.1 We wou ld be particularly interested in w orking with agrou p to create a reference imp lementation op timized for portability ratherthan p erformance, so that anyone could try ou t Dylan no m atter what brand ofcomp uter they use. Because Dylan is a tradem ark of App le Comp uter, anyoneimplementing the language must obtain permission to use the name.How ever, it is our intention that p ermission will be granted to anyone w ith aconforming implementation.

    Apple Eastern Research and Technology2 will be the focal point for d iscussion

    of the Dylan langu age, its implementations, and its fu ture evolu tion. Cur rentand prospective users or imp lementors of Dylan, as well as programm inglanguage researchers who are interested in object oriented d ynam ic langu ages,

    1Since this w as w ritten, such imp lementations are w ell underw ay on a variety of platforms.2Now App le Cambridge Engineering.

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    17/214

    Dylan Interim Reference Manual June 3, 1994 xv

    are invited to comment on the d esign of the language and suggestimprovem ents that are consistent w ith the goals noted above. We will alsocontinue our past p olicy of driving the evolution of the language from the

    needs and comm ents of our u sers, who are system and app lication d eveloperswhose prev ious experience is largely with conventional langu ages. We hop e tointegrate all inp uts to m ake Dylan the best language w e can and use it to bringthe benefits of OODLs to as many p rogram mers as we can p ossibly reach.

    Ike Nassi

    Cambridge, Massachusetts

    March 1992

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    18/214

    xvi June 3, 1994 Dylan Interim Reference Manual

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    19/214

    Dylan Interim Reference Manual June 3, 1994 xvii

    Acknowledgments

    Designing Dylan has been a work of many h and s.

    The primary contributors to the langu age design w ere Kim Barrett, Glenn S.Burke, Robert Cassels, Bill Chiles, Jerom e T. Coonen , Scott Fahlman, PaulGleichauf, James Grand y, Paul Haahr , John Hotchkiss, Jeremy A. Jones,Michael Kahl, William Lott, Rob MacLachlan ,David A. Moon, Ike Nassi, JeffreyPiazza, Kent Pitman , Keith Playford, Andrew Shalit, Jonath an Sobel, Walter R.Smith, Bill St. Clair, Orca Starbuck, Oliver Steele, Rober t Stockton, SteveStrassmann , Larry Tesler, Derek White, and Gail Zachar ias.

    Add itional design w ork and oodles of helpful comm ents were provided by Jim

    Allard , Peter Alley, Jonathan Bachrach , Richard Barber, David Betz, John Barr,Alan Bawden, Stoney Ballard , Ernie Beernink, Brent Benson, Eric Benson ,Rasha Bozinovic, Bill Campbell, Steve Cap ps, Yu-Ying Ch ow, Doug Cu tting,Ken Dickey, Richard Duncan, Mikel Evins, Marc Feeley, Gregg Foster, TomGordon, Jed Harris, Alice K. Hartley, Alan Kay, Larry Kenyon , MikeLockwood , Matthew MacLaurin, Robin Mair, Neil Mayle, Tim McInerney,Scott McKay, Jim Meehan, John Meier, Jim Miller, Richard Mlynarik, RobertMuller, Carl Nelson, Julian Padgett, Paige Parsons, Ed Petrus, Peter Potrebic,Jonath an Rees, Kalman Reti, David Rosenfeld, Carl Schw arcz, David Singer,And y Sizer, David C. Smith, An dy Stadler, Joshu a Susser, Michael Tibbott,Tom Vrhel, John Wainw right, Bob Welland , Paul Wilson, and Dan Zigmond.

    Moral and logistical support w ere provided by Donn a Au guste, Chrissy Boggs,Mickey Dennison , Gina Field , Rick Fleischm an, James Joaquin, Rick LeFaivre,Ross Knights, Becky Mulhearn, David Nagel, Wend y Ph illips, Mark Preece,Mary Reagan, Shan e Robison, and Susan M. Whittemore.

    The Dylan p roject is directed by Ike Nassi and Carl Schwarcz.

    The first edition of the Dylan man ual w as written by And rew Shalit w ithcontributions from Jeffrey Piazza, David Moon, and Steve Strassman n. It wasextensively revised by Orca Starbu ck, with ed itorial help from Kim Barrett,David Moon, and Steve Strassmann to incorporate recent language changes.

    The first ed ition of the manu al was d esigned by Scott Kim and SteveStrassmann . The original cover art was designed by Scott Kim.

    The Dylan project is fun ded by Apple Comp uters AppleSoft Division.

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    20/214

    xviii June 3, 1994 Dylan Interim Reference Manual

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    21/214

    Dylan Interim Reference Manual June 3, 1994 1

    1. Introduction

    Manual Notation

    This man ual u ses a small number of typograp hic conventions:

    Body text ap pears in Roman.

    First uses of terms appear in Bold.

    Text which ap pears as it would be entered into the compu ter app ears inCourier.

    In the body of the man ual, the following notation is used to describe syntaxforms:

    {...} Curly braces indicate a group of items.

    {}* Cur ly braces followed by an asterisk indicate that thecontents can app ear zero or more times.

    {}+ Cur ly braces followed by a p lus sign ind icate that thecontents can app ear one or more times.

    [] Square brackets indicate that the contents are optional.

    | Items separated by a vertical bar are mutually exclusive.One or the other may app ear.

    The BNF gramm ar at the end of the man ual u ses its own notation w hich isd ifferent from the above.

    Formal parameters (i.e., place holders for the actual text you would enter)app ear inItalic. The names of parameters are often descrip tive of the type ofvalue acceptable as a value of the parameter. They will often match the nam esof classes, ind icating a genera l instance of the class. For example, numberindicates a general instance of the class , and string indicates ageneral instance of the class .

    Interactions between a u ser and a Dylan interpreter are shown in a mixture ofCourierand Courier Italic. Courier shows the text entered by the

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    22/214

    2 June 3, 1994 Dylan Interim Reference Manual

    user, and Courier Italic shows the text printed by the interpreter. Thequestion mark used in these sections is the interp reters prom pt.3

    The error messages in the manual have been edited for brevity. The details ofinteractions w ith Dylan (prompt text, error m essage texts, etc.) will differamong imp lementations.

    The functions format and print are used in some examples but are not partof Dylan.

    3The term interpreteris used, even thou gh m ost implementations of Dylan are expected to be

    compiled. In most cases, an interpr eter will be imp lemented by comp iling Dylan expressions

    and immediately executing the compiled code.

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    23/214

    Dylan Interim Reference Manual June 3, 1994 3

    Background and Goals

    Dylan is a general-pu rpose high-level programm ing language, designed foruse both in application and systems program ming. Dylan includ es garbagecollection, run-time typ e checking, selective dynamism, error recovery, and amod ule system. These features simplify program ming and support attractivedebu gging and development tools.

    The motivation for Dylan is that p rograms an d large software systems havebecome too comp lex for trad itional static program ming languages. To create anew generation of softwareand to ensure tha t this software is maintainableand extensiblerequires a new, friend lier set of program ming tools. The coreof these tools is a simple and expressive language, one that is efficient bu t

    wh ich p rotects the program mer from crashes and machine-level debugging.All program ming shou ld take place at an object-oriented level. Improvedimplementation techniques and increasingly pow erful compu ter hardw aremake it possible to use fully dynamic object-oriented languages for a w iderange of programm ing tasks.

    Dylan is built from the grou nd up with a thorou ghly integrated object mod el.Like some object-oriented extensions to Lisp, Dylan implementspolymorp hism through generic fun ctions and class dispatch, rather than

    throu gh a Smalltalk-style message-passing mechanism.4 Generic functionsprovide a very convenient m odel for a broad range of programm ing tasks.

    The target aud ience of Dylan is application developers now using languagessuch as C, C++, and Pascal wh o are ready to m ove up to Object OrientedDynamic Languages. Dylan is not intend ed p rimarily for the Lisp or Smalltalkcommun ity, thu s comp atibility with Smalltalk or with Lisp dialects such asScheme and Com mon Lisp is not a primary goal. Dylan has been rethough tfrom the grou nd up , on a fully object-oriented foundation. A primary goalwas to make the language as simple as possible, but no simp ler. We have triedto avoid m ultiple ways to do the same thing , to omit features that are difficultfor the average ap plication developer to un derstand and use effectively, toleave out an ything that w e do n ot know how to implement efficiently in bothspace and time, and to p rovide a clear separation of the langu age executed at

    run-time from the development tools. At the same time, weve movedcomp licated low-level bookkeeping und erneath the language and taken it out

    4Notable Lisp system s that u se generic fun ctions are CLOS (Common Lisp O bject System),

    Oak Lisp, and EuLisp.

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    24/214

    4 June 3, 1994 Dylan Interim Reference Manual

    of the han ds of the app lication program mers, to make them m ore prod uctive.The overriding goal of Dylan is rapid d evelopm ent and delivery ofapp lications and app lication components on very small comp uters.

    Language Overview

    Dylan is built around two central concepts: objects an d functions.

    Objects are the data that exist in Dylan program s. Objects are mapp ed into aclass heterarchy.5 The class heterarchy describes the inh eritance relationshipsamong classes. The class is the root of the heterarchy. Every classinherits from its direct superclasses (except for wh ich has nosup erclasses). Classes may also have subclasses , wh ich inherit from them,either directly or ind irectly. The superclasses of a class are the class itself, itsd irect sup erclasses, their d irect sup erclasses, and so on back to the class.

    Every object in th e Dylan w orld is a directinstance of exactly one class. Thisclass is referred to as the class of the instance. For each object O that is adirect instance of class C, the object O is also an indirect instance of all thesup erclasses ofC(except Citself). (It follows that every object in Dylan is anindirect instance of.) The term general instancemeans either ad irect or indirect instance.

    Dylan defines four categories of classes:

    Abstract Class A class that is not intend ed to have d irect instances. Itsgeneral instances obey an interface imp lemented bysubclasses. The opp osite of an abstract class is a concreteclass.

    Instantiable Class A class that can be used as the first argumen t to make.The opposite of an instantiable class is an uninstantiableclass. Note that an abstract class may be instantiable.

    Sealed Class A class that cannot be subclassed, other than thosesubclasses explicitly defined in the same library . Theopp osite of a sealed class is an open class .

    5A hetera rchyalso called a d irected acyclic graph (DAG)is like a h ierarchy, except th at

    nodes can have m ultiple parents. Dylan classes are in a heterarchy because Dylan supp orts

    multiple inheritance.

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    25/214

    Dylan Interim Reference Manual June 3, 1994 5

    Primary Class A class that may be used only as the primary superclass inmu ltiple inheritance. It is illegal for a class to have twopr imary su perclasses un less one is a subclass of the other.

    The opp osite of a p rimary class is a free class.

    Functions are a class of objects used for p erforming actions in Dylan.Functions correspond to the functions, procedures, method s, and messages ofother languages. Dylan supp orts two classes of functions: meth ods andgeneric functions.

    A method is a basic callable unit of code. It contains a typ ed argumen t list anda code body. The types in the argu ment list are called the specializers of themethod . A method can only be called w ith arguments that match thespecializers of the argum ent list. (In the most comm on case, the specializer is a

    class, and the corresponding argu men t mu st be a general instance of the class.)When the specializers of a m ethod match a set of arguments, the m ethod issaid to be applicable to the argum ents. If a method is called withinapp ropriate argum ents, an error is signaled.

    A generic function contains zero or more methods. When a generic function iscalled, the argumen ts are comp ared to the specializers of all the method s in thegeneric function. The method with the most appropr iate specializers is run. Inthis way, a generic function chooses a method based on the classes andidentities of its argu men ts. This is the basic techn ique for object-orienteddispatch in Dylan.

    In contrast to meth ods in other object-oriented languages, Dylan method s canalso be called d irectly. They do not need to be ad ded to generic functions.Used this way, methods play th e role of blocks in Smalltalk, closures in Lisp,and fun ctions in C.

    Classes and functions are them selves first-class objects, wh ich can bemanipulated by programs.

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    26/214

    6 June 3, 1994 Dylan Interim Reference Manual

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    27/214

    Dylan Interim Reference Manual June 3, 1994 7

    2. Syntax

    Lexical Notation

    Here are the lexical conventions used in Dylan p rograms.

    White space (includ ing spaces, tabs, newlines, andnew page characters) serves as a delimiter. The amount ofcontiguou s white space is not significant. Thus, anynu mber of contiguou s wh ite space characters can be usedfor formatting.

    foo Variable nam es are a series of alph anu meric characters,and characters from th e set ! & * < = > | ^ $ % @_ - + ~ ? /, that do not begin w ith on e of the special

    characters - + ~ ? /. If a variable name begins with anu meric character, the nam e mu st contain two alphabeticcharacters in a row . Variable nam es are not case-sensitive.

    = Infix opera tors are the following one- or two-charactersequences: + - * / - = == < > = ~= ~ & | ^.

    \= An infix operator var iable nam e is the corresponding infixoperator, prefixed w ith the infix operator escape character\. This allows an infix operator to be used wherever avariable nam e is allowed (for examp le, as the variablename in a define method or as a function argu ment).

    123 The syntax of nu mbers is described in the numerics1.5 section of this manu al.-4.0+57#x1f4e

    "abc" Literal strings are delimited by double-quote marks. The

    characters between the qu otes are the elemen ts of thestring. Within the string, white space is significant (itcontributes to the string). Double quotes can be includedin strings by p receding them with a backslash character.Within a string, backslash (\) has the general effect ofquoting the following character. To include a backslash in

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    28/214

    8 June 3, 1994 Dylan Interim Reference Manual

    a string, the backslash must be p receded by anotherbackslash.

    #"Hello" Symbols are interned strings. They are preceded by a.i.sharp-sign. See the section on symbols and keyw ordsfor more d etails.

    Hello: An alternative syntax for symbols is keyword syn tax.See the section on symbols and keyw ords for more details.

    #(1, 2, 3) Literal lists are delimited by open and close parentheses,and preceded by a sharp-sign. The items between theparentheses are the elemen ts of the list. They areseparated with commas.

    #[1, 2, 3] Literal vectors (one-dimensional arrays) are delimitedwith square brackets, and preceded by a sharp -sign. Theitems between the square brackets are the elemen ts of thevector. They are separated w ith comm as.

    'M' Character constants are represented by d elimiting thecharacter with single quotes.

    // A pair of slashes ind icates the start of a comment. Thecomment continues until the end of the line. At the startof a new line, regular parsing begins again.

    /* ... */ Slash-star pairs delimit extend ed comments. Thesecomments can run over mu ltiple lines. Extend edcomm ents can be nested.

    #t The hash-sign t syntax is used to ind icate the canonicaltrue value.

    #f The hash-sign f syntax is used to ind icate the canon icalfalse value.

    #key #key, #rest, #next an d #all-keys are used to indicate#rest special tokens in p aram eter lists.#next

    #all-keys

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    29/214

    Dylan Interim Reference Manual June 3, 1994 9

    Naming Conventions

    Several conventions for nam ing variables help p rogram mers iden tify the

    pu rposes of variables. The nam es of variables do not a ffect the semantics of aprogram , but are simp ly used to imp rove readability.

    Dylan uses the following nam ing conventions:

    Variables used to hold classes begin and end with angle brackets.

    Modu le variables that are d esigned to have their values change in the course ofa program (i.e., variables that are not read -only) begin and end with asterisks.

    *parse-level**incremental-search-string*

    *machine-state*

    *window-count*

    Program constants (read -only mod ule variables) begin with a dollar sign.

    $pi

    $end-of-file

    The names of most predicate fun ctions end with a qu estion m ark. Predicatesare functions which retu rn a tru e or false value.6

    subclass? even?

    instance?

    The names of most operations that destructively mod ify d ata structures endwith an exclamation point.7 These names sometimes contrast with versionsthat allocate new m emory for the result.

    reverse! (non-destructive version is reverse)

    sort! (non-destructive version is sort)

    Operations that retr ieve a value from a location are called getters. Operations

    that store into a location are called setters. In general, getters and setters come

    6Three notable exceptions to the term inal question mar k convention are , and =.7Notable exceptions to the term inal exclamation p oint convention ar e := and all the setter

    variable names.

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    30/214

    10 June 3, 1994 Dylan Interim Reference Manual

    in pairs. Setter variable names are derived by app end ing-setter to the correspond ing getter variable nam e. Actually, this is notsimply a convention. The rule is exploited to generate setter nam es from getter

    nam es automatically, and it is used to expan d calls to :=.

    Getter Setter

    window-position window-position-setter

    table-size table-size-setter

    window-color window-color-setter

    These two expressions are equ ivalent; they both set the color ofmy-window to green:

    window-color-setter (green, my-window)

    my-window.window-color := green

    Expressions

    Dylan programs are comp osed ofexpressions. When an expression isevaluated, it returns zero or more values. Evaluating an expression may h aveside effects and may involve evalua ting sub-expressions.

    An outer expression is an expression that is not a su b-expression of anyexpression. A top-level expression is either an ou ter expression or a directsub-expression of a begin syntax form that itself is a top -level expression.

    (Such a begin cannot have local declarations in it, althou gh th e gramm arallows it.) Definitions (see Syntax Form s, below ) are restricted to be top -levelexpressions. Other expressions may ap pear either as top-level expressions, oras sub-expressions of other expressions.

    There are four k inds of expressions: literal constan ts, variable references,function calls, and syn tax forms.8

    Literal Constants

    A literal constant is an object that is specified explicitly in program text.

    ? "abc"

    "abc"? 123

    123

    8The term syntax form describes both special form s and m acros. They are equivalent to

    macros in other languages.

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    31/214

    Dylan Interim Reference Manual June 3, 1994 11

    ? foo:

    foo:

    ? 'M'

    'M'

    ? #t

    #t

    ? #f

    #f

    ? #(1, 2, 3)

    #(1, 2, 3)

    Literal constan ts are imm utable. The keys and elemen ts of collections that areliteral constan ts are imm utable. Attemp ting to mod ify an immu table objecthas und efined consequen ces. Immutable objects may share structure. Literalconstants that are = may or may not be ==.

    Variable References

    When an expression is a variable name, the expression ind icates a variablereference. The variable nam e evaluates to the value of the variable.

    Dylan sup por ts two kinds of variables: lexical variables and mod ule variables.Lexical variables are created locally. They roughly correspond to localvariables in other langu ages. Module variables are created by using adefinition such as define variable or define method.They roughlycorrespond to global variables in other languages.

    ?

    {the class }

    ? concatenate

    {the generic function concatenate}

    ? define variable my-variable = 25;

    my-variable

    ? my-variable

    25

    ? begin

    let x = 50;

    x + x;

    end;

    100

    Note that Dylan classes and functions are first-class objects and are named byvar iables, like other objects.

    See the chapter on Variables for detailed information abou t lexical and mod ulevariables.

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    32/214

    12 June 3, 1994 Dylan Interim Reference Manual

    Function Calls

    Function calls generally have th e syntax

    expression(arg1, arg2, argn)

    expression mu st evaluate to a function. This is the function to be called. Theargu men ts to the function are the values of the elements in the list.

    The argum ents to a function are evaluated in left-to-right order. The fun ctionis evaluated before the argu ments.9 Once the function and all the argum entsare evaluated, the function is called with the argu ments.

    A function call evalua tes to the values returned by the function.

    expression is commonly a variable nam e. In the following example, thefunction being called is the va lue of the variable factorial:

    factorial(x, y)

    However, the expression in the function position d oes not have to be a variablereference; it can be any expression that evaluates to a function. In this way,Dylan is like C and Scheme, and u nlike Common Lisp. The following examplehas a comp lex expression in the "function position." The complex expressioncreates and retu rns a function w hich ad ds one to its argument. This fun ction isthen ap plied to 99.

    ? (method(x) x + 1 end) (99)

    100

    Syntax Forms

    A syntax form is a form w hich has its own ru le for evalua tion. Syntax formsare introduced by syntax operators. Some examples of syntax opera tors aredefine variable, for, method, and :=.

    Syntax forms may have d ifferent evaluation ru les than function calls. In afunction call, all the subexpressions are evalua ted an d p assed to the function asargu men ts. In contrast, a syntax form can examine its subexpressions literallyand can choose to evaluate some and give special meaning to others. Thespecial evalua tion ru les for each syntax form are listed a long w ith that forms

    definition.

    9Except in the special slot reference syntax argument.function, where argument is

    evaluated first, followed by function.

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    33/214

    Dylan Interim Reference Manual June 3, 1994 13

    Generally, the syntax operator is the first word or words ap pearing in thesyntax form. For examp le, the define variable syntax form begins withthe words define variable, and themethod syntax form begins w ith the

    word method.

    define variable foo = 3;

    method (a :: , b :: )

    list (a - b, a + b);

    end method;

    // Creates an anonymous method, which expects 2

    // numeric arguments.

    How ever, the syntax operator does not have to be the first word in the form.For example, the assignm ent op erator, :=, is an infix opera tor tha t is also asyntax form with special evaluation ru les.

    my-variable := 12;// Sets the value to 12

    There are three kind s of syntax forms:

    Most syntax forms are macros (introduced by macro operators). Somemacros (like the for iteration constru ct) are p art of the core Dylanlanguage. Others are created by individual imp lementations or byprogram mers. Macros can be though t of as expan ding into other,equivalent, expressions.

    Special forms (introdu ced by special form operators) are basic, built-insyntax forms that cann ot be reduced to other expressions. Examples are :=an d method.

    D efinitions (introduced by definition operators) are declarative parts of aprogram . Definitions are restricted to be top level expressions (see the nextsection). They do not return values. Examples are define method an ddefine variable.

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    34/214

    14 June 3, 1994 Dylan Interim Reference Manual

    Statement bodies

    Many kinds of expressions include implicit bodies, which may contain one ormore other expressions, separa ted by semicolons. When an imp licit body isevalua ted, the expressions in the imp licit body are evaluated in order (left toright). The value of the implicit body is the valu e of the last expression.

    The simp lest expression containing an implicit body is begin.

    begin [Special Form ] bodyend

    values

    The body consists of any n um ber of expressions separated by semicolons.begin executes the expressions in the body sequen tially. The values of the lastexpression are returned . If there are no expressions in the body, #f is returned .

    begin

    close(airlock.outer-door); // this

    pressurize(airlock); // is an

    open(airlock.inner-door); // implicit body

    end;

    Programs only need to use begin explicitly in order to limit the scope of alexical variable, or in situa tions where a single expression is expected, such as

    an argu men t to a function call. Many other expressions contain imp licitbod ies. For examp le, the body of a method d efinition is an imp licit body, andthe if statement has an implicit body in each sub-part.

    if (moon-phase == #"full")

    wolf-form(werewolf); // this is an

    howl-at-moon(werewolf); // implicit body

    else

    human-form(werewolf);

    end if;

    Some statements use the word end to mark the end of an implicit body. Other

    statements u se other markers, such as the else that marks the end of the firstimp licit body in an if statement. The syntax description for each statementdefines where implicit bodies may app ear, and how th e bound ary is marked .

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    35/214

    Dylan Interim Reference Manual June 3, 1994 15

    Semicolons

    Multiple expressions, such as top -level expressions app earing in sou rce files,

    are separated by a semicolon ;. Semicolons are also requ ired to separate allbut the last expression in imp licit bodies. The semicolon after the lastexpression is optional.

    Special function call syntax

    Infix Operators

    Certain pred efined op erators are called using stand ard algebraic syntax.Operators and their argum ents must be separated by wh itespace or

    parentheses. All binary op erators are left-associative, except for the assignm entoperator :=, which is right-associative.

    These are listed in descending ord er of precedence. Operators within a groupshare the same p recedence.

    unary - negative

    unary ~ not (boolean)

    binary ^ exponentiation

    binary * multiplication

    binary / division

    binary + addition

    binary - subtraction

    binary = equality

    binary == identity

    binary ~= not equals

    binary < less than

    binary > greater than

    binary = greater than or equals

    binary & and

    binary | or

    binary := assign

    Except for the last three, all of these infix opera tors are functions. Thesefunctions are first class, like all Dylan functions, but in ord er to u se one w here

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    36/214

    16 June 3, 1994 Dylan Interim Reference Manual

    a variable nam e is expected (for examp le, as the variable nam e in a definemethod, or as a function argu ment) the operator must be prefixed w ith theinfix opera tor escape character (\).

    The ord er of evalua tion for general infix expressions is as follows:

    In an expression of the form

    arg1 op op argn

    arg1 argnare evaluated in that order. The evaluation time of mod ulevariables that op s are d efined to invoke (e.g. the plus function for +), isunspecified.

    The last three infix opera tors listed h ere (&, |, and :=) are syntax forms. Theyhave sp ecial evaluation ru les wh ich are described wh ere these forms are

    defined.

    Slot Reference

    Dylan prov ides a shorthand syntax for slot reference. The syntaxargument.function appliesfunctionto argument. This syntax is usu ally usedfor slot reference, to access the function slot of the object argument.This can be cascaded and is left associative (i.e., moo.goo.gai.pan gets thepan slot of the gai slot of the goo slot ofmoo.).Examples:

    ? america.capital

    "Washington, D.C."? me.mother.current-husband.favorite-child == me

    #t

    Dylans left-to-right evaluation ru le app lies here: argument is evaluated first,followed by function.

    Array Reference

    Dylan provides a shorthand syntax for array reference. The syntax foo[i] isequivalent to the function call element(foo, i). The syntax foo[i1, i2, ... in]where n 1 is equ ivalent to the function call aref (foo, i1, i2, ... in).

    ? define constant vect = #[7, 8, 9]

    defined vect

    ? vect[0]

    7

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    37/214

    Dylan Interim Reference Manual June 3, 1994 17

    In expressions of the form

    sequence[arg1, , argn]

    sequence is evaluated first, then arg1 argn in that order.

    The evaluation time of the variable or , wh ich th is expression is defined to invoke, is unspecified.

    Syntax of Dylan Files

    A Dylan source code file is a stand ard por table file format for publishingDylan source code. Such a file has two parts, the header and the body. Theheader comes before the body .

    The body consists of zero or more ou ter expressions and comm ents.The head er consists of one or more keyw ord -value pairs, as follows:

    1) The syntax of a keyword is as follows: a keyword is a letter, followed byzero or more letters, digits, and h yphens, followed by a colon, contains onlycharacters from the ISO 646 7-bit character set, and is case-ind ependent.

    2) A keyword begins on a new line, and cannot be preceded by wh itespace.

    3) All text (exclud ing padd ing whitespace) between the keyword and thenewline is considered to be the value. Add itional lines can be ad ded byhaving the ad ditional lines start with whitespace. Leading wh itespace is

    ignored on all lines.4) Interpretation of the value is determined by the keyword .

    5) Imp lementations mu st recognize and han dle standard ized keyword sproperly, unless the specification for a keyw ord explicitly states tha t it canbe ignored.

    6) When imp orting a file, imp lementations are free to ignore any non-standard keyword/ value p air that they do not recognize.

    7) When exporting a file, implementations mu st use standard keyword sprop erly. Imp lementations are free to use non-stand ard keyword s.

    8) The definition of a keyword may specify that the keyword m ay occur morethan once in a single file header . If it does not, then it is an error for thekeyword to occur more than once. If it does, it shou ld specify the mean ingof mu ltiple occurences.

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    38/214

    18 June 3, 1994 Dylan Interim Reference Manual

    The header cannot contain comments.

    Blank lines may n ot app ear in the header. A blank line d efines the end of the

    header and the beginning of the code bod y. The blank line is not part of thecode bod y. (A "blank line" is a line consisting of zero or more space or tabcharacters, end ing in a new line character.)

    The following stand ard keyword s are defined:

    module: module-name [Header keyword]

    Expressions in the file are associated with the nam ed module. This keyw ord isrequired.

    author:arbitrary text [Header keyword]

    copyright: arbitrary text [Header keyword]

    version: arbitrary text [Header keyword]

    These are provided for standard ization. These are optional, and can beignored by the imp lementation.

    A typ ical Dylan sou rce file might look like this:

    module: quickdraw

    author: J. Random Rect

    Linear Wheels, Inc., "Where quality is a slogan!"

    [email protected]

    copyright: (c) 1993 Linear Wheels, Inc., All rights reserved

    version: 1.3 alpha (not fully tested)

    define constant $black-color = ...

    ...

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    39/214

    Dylan Interim Reference Manual June 3, 1994 19

    3. Variables

    Dylan supports two kinds of variables: lexical variables an d modulevariables.

    The term environment is used to refer to the set of variables that are availableto a given part of a program. It includ es both module variables and lexicalvariables.

    Variables can be set to new values w ith the := special form, wh ich is d escribedin this chap ter's section on Assignm ent.

    Module Variables

    Modu le variables can be referenced from anyw here inside the mod ule. Theyplay the role assumed by global variables in other langu ages.

    define variablebindings = init [Definition]

    define variable creates module variables in the current mod ule.

    bindings are the variable(s) to be created, and mayhave the following forms:

    variable

    or ( {variable }* [ #restrest-variable-name ] )

    where variable may be either variable-name or variable-name::type. Thevariable-names an d rest-variable-name mu st have the syntax of variable nam es,and are not evaluated . The values returned by initprovide the initial valuesfor the variable(s) specified by bindings.

    In the simp lest case, bindings is just a variable nam e, and initreturns one valuewhich is used to initialize that variable. See Checking Types and Bind ingMultiple Values for more complex cases.

    ? define variable foo = 10;

    foo

    ? foo + foo;20

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    40/214

    20 June 3, 1994 Dylan Interim Reference Manual

    define constantbindings = init [Definition]

    define constant creates read-only m odu le variables in the current mod ule.

    This form has the same syntax an d semantics as define variable exceptthat the variables created are read -only.

    Several other forms create module variables. See define class, definegeneric, and define method for more information.

    Source code is associated w ith a specific mod ule throu gh th e program mingenvironment. This association occurs at d evelopm ent time and cannot bechanged at ru n-time. See the Modules chap ter for more d etails about m odu les.

    A given mod ule variable can on ly be defined once, except that mu ltipledefine method definitions with d ifferent sp ecializers are allowed, togetherwith at most one define generic definition.

    Lexical Variables

    Lexical variables are created locally an d can be referenced only in a limitedrange of program text. They correspond to local variables in other languages.

    letbindings = init [Special Form ]

    let creates new lexical variables within the smallest enclosing imp licit bod y

    containing the let.bindings are the variable(s) to be created, and may have the following forms:

    variable

    or ( {variable }* [ #restrest-variable-name ] )

    where variable may be either variable-name or variable-name::type. Thevariable-names an d rest-variable-name mu st have the syntax of variable nam es,and are not evaluated . The values returned by initprovide the initial valuesfor the variable(s) specified by bindings.

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    41/214

    Dylan Interim Reference Manual June 3, 1994 21

    In the simp lest case, bindings is just a variable nam e, and initreturns one valuewhich is used to initialize that variable. See Checking Types and Bind ingMultiple Values for more complex cases.

    ? begin

    let foo = 35;

    foo + foo

    end

    70

    A lexical variable shad ows any mod ule variable with the same n ame an d anysurroun ding lexical variable with the same n ame. This rule means that theinnerm ost version of a variable is the one r eferenced.

    ? define variable foo = 10;

    foo

    ? foo

    10

    ? begin

    let foo = 20;

    let foo = 50;

    foo + foo

    end

    100

    ? foo

    10

    The bind ings introdu ced by the let are in effect until the end of the smallestenclosing implicit body containing the let.

    Several other syn tax forms, includ ing local an d block, also create lexicalvariables as part of their operation.

    Method parameters are another examp le of lexical variables; they can bereferenced on ly from the body of the method . See the chap ter on Fun ctions formore information on method param eters.

    Checking Types

    Variable bind ings app earing in param eter lists and in statements like let an d

    define variable may be specialized or unsp ecialized. Specializing avariable indicates that the variable may only hold values of the specified typ e.Specialized variables have the syntax variable-name ::type . Leaving a var iableun specialized indicates that it may hold values of any typ e. Unspecializedvariables simp ly app ear as variable-name.

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    42/214

    22 June 3, 1994 Dylan Interim Reference Manual

    Each type is any expression that evalua tes to a valid Dylan type (that is, aninstance of). The types are evaluated before the init, in the sameenvironment as init. Each type specifies the type of the corresponding variable.

    Attemp ts to initialize or assign th e variable to a value w hich is not an instanceof the correspond ing type results in a type error being signalled.

    ? begin

    let x :: = sqrt (2);

    x

    end

    error: 1.4142135623730951 is not an instance of

    ? define variable foo :: = 10;

    foo

    ? foo := sqrt (2)

    10error: 1.4142135623730951 is not an instance of

    Binding Multiple Values

    Evaluating a Dylan expression can yield one value, more than one value, or novalu es at all. This capability is called multiple values.

    Multiple values are supported through two capabilities:

    The fu nction values is used to return m ultiple values.

    In the bindings parts of statements such as let, define variable, an ddefine constant, bindings may have one of the following forms:

    variable or ( {variable }* [ #restrest-variable-name ] )

    The second form is used to receive multiple values.

    values #restthe-values the-values [Function]

    Returns the-values as multiple values.

    ? values(1, 2, 3);

    1 // first value returned

    2 // second value returned

    3 // third value returned

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    43/214

    Dylan Interim Reference Manual June 3, 1994 23

    When variables are initialized to values retu rned by an initin a statement su chas let, define variable, an d define constant, the number ofvariables and the num ber of values are compared :

    If there are the same number of variables and values, the variables areinitialized to the corresponding values.

    ? begin

    let (foo, bar, baz) = values (1, 2, 3);

    list (foo, bar, baz)

    end

    #(1, 2, 3)

    ? define method opposite-edges (center :: ,

    radius :: );

    let (min, max) = edges (center, radius);

    values (max, min);

    end method;opposite-edges

    ? opposite-edges (100, 2);

    102

    98

    If there are more variables than there are values returned by init, theremaining variables are initialized to #f. (If a specialized variable defaults to#f, and #f is not an instance of that variable's type, an error is signaled.)

    If there are more values returned than there are variables, the excess valuesare placed in a sequ ence wh ich is used a s the initial value for rest-variable; ifthere is no rest-variable, these excess values are d iscard ed.

    ? begin

    let (#rest nums) = edges (100, 2);

    nums;

    end

    #(98, 102)

    If there is a rest-variable bu t there are no excess values, rest-variable isinitialized to an empty sequence.

    Multiple values can be u sed to p erform parallel binding:

    ? beginlet x = 10;

    let y = 20;

    let (x, y) = values (y, x);

    list (x, y);

    end

    #(20, 10)

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    44/214

    24 June 3, 1994 Dylan Interim Reference Manual

    Assignment

    The Dylan special form := is used to set variables to new values. It can alsobe used as an alternate syntax for calling setter functions and macros.

    place := new-value new-value [Special Form ]

    := stores new-value in place. Subsequent evaluations ofplace will yield new-value. := returns new-value.

    place commonly has the syntax of a variable nam e. Dylan also allows extendedformats (described below). Ifplace is not a variable name or one of theseextended formats, an error is signaled.

    Ifplace is a variable nam e, then new-value is stored in the correspondingvariable (wh ich may be a lexical or module variable). An error is signaled ifthere is no lexical or mod ule variable correspond ing to the place , if thecorrespond ing variable is a read -only variable, or if the corresponding variableis specialized to some type an d the new-value is not an instance of that typ e.

    ? define variable foo = 10;

    10

    ? foo // this is a variable

    10 // this is the variables contents

    ? foo := 10 + 10;

    20

    ? foo

    20

    Extended form

    Ifplace is not a variable nam e, then it may have the syntax of a call to afunction. This is called the extended form of:=. In this case, the function callind icates an accessible location. The call to := should change what futureaccesses of the location will return.

    ? define variable foo = vector (10, 6, 8, 5);

    foo

    ? element(foo, 2)

    8? element(foo, 2) := "bar"

    "bar"

    ? foo

    #[10, 6, "bar", 5]

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    45/214

    Dylan Interim Reference Manual June 3, 1994 25

    In the general case,

    name ( arg1, ... argn) := new-value

    means roughly

    name-setter ( new-value, arg1, ... argn)

    In fun ctional :=expressions

    function-name(arg1, ..., argn) := value

    where function-name is not a m acro name,arg1 ... argn are evaluatedfirst in that ord er, followed by new-value.

    The evaluation time of the variable function-name-setter, which this

    expression is defined to invoke, is unsp ecified.

    Extended form using array reference or slot reference syntax

    The special syntactic shorth and s for array reference and slot reference are alsoallowed as part of the extended form of :=.

    For example, the two forms

    foo[2] := "quux"

    element (foo, 2) := "quux"

    are equivalent to

    element-setter ("quux", foo, 2).

    In . := expressions

    argument.function-name := value

    where function-name is not a m acro name,argument is evaluated first,followed by value.

    The evaluation time of the variable function-name-setter, which thisexpression is defined to invoke, is unsp ecified.

    In imp licit element := expressionssequence[arg1, , argn] := value

    sequence is evaluated first, then arg1 argn in that ord er, thenvalue. Theevaluation time of the var iable element-setter, which th is expression isdefined to invoke, is unspecified .

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    46/214

    26 June 3, 1994 Dylan Interim Reference Manual

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    47/214

    Dylan Interim Reference Manual June 3, 1994 27

    4. Control Constructs

    True and False

    In Dylan, there is a single object that counts as false. This object is ind icated bythe syntax #f10. All other values are considered true for the sake of true/ falsetesting. The canon ical true object, ind icated by the syntax #t, can be used forclarity of code.

    Throughou t the m anu al, the phrases true, false, returns true, andreturns false are used. Its imp ortant to remember that returns true doesnot necessarily mean retu rns the object #t. It simp ly means returns anyobject besides #f. Sometimes for efficiency, debuggability, or informationalvalue, some value besides #t is returned .

    #t [Object]

    This is the canon ical true value. In Dylan, all objects besides #f count as true,not just #t.

    #f [Object]

    This is the on ly false value.

    ~ thing boolean [Function]

    Returns true ifthing is #f; otherw ise returns false.

    Conditionals

    The following syntax forms are used to perform cond itional execution.

    10This is in sharp distinction to C, which equates 0 and the false value, and some d ialects of

    Lisp, wh ich equ ate the emp ty-list and th e false value.

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    48/214

    28 June 3, 1994 Dylan Interim Reference Manual

    if (test)consequent [elseif(elseif-test)elseif-consequent]* [elsealternate]

    end [if ] values [Special Form ]

    if evaluates test. Iftestevaluates to a true value, consequentis evaluated .

    Iftestevaluates to #f (the only false value), and any elseif clauses weresup plied, the first elseif-test is evalua ted. If thatelseif-testevaluates to a truevalue, its elseif-consequentis evalua ted . If it evalua tes to #f, the next elseif-test isevaluated, and so on.

    Finally, iftestand each elseif-testevaluates to #f, and alternate was supplied, thealternate is evaluated. Ifalternate was n ot supplied, #f is returned.

    The consequent , elseif-consequent, and alternate sections of an if statement are

    all imp licit bodies (may contain any nu mber of expressions, separa ted bysemicolons). The values of the last expression in the ap propr iate consequent,elseif-consequent, or alternate form (whichever is evaluated) are returned .

    ? define method test (thing :: )

    if (thing)

    #t

    else

    #f

    end if

    end method;

    test

    ? test ("hello")

    #t

    ? test (#t)

    #t

    ? test (#f)

    #f

    ? define method show-and-tell (thing :: );

    if (thing)

    print (thing);

    #t

    else

    #f

    end if

    end method;

    show-and-tell

    ? show-and-tell("hello")

    hello

    #t

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    49/214

    Dylan Interim Reference Manual June 3, 1994 29

    unless(test) [Macro]body

    end [unless]

    values

    unless evaluates test. body is an implicit body. Iftestevaluates to a truevalue, then none of the expressions in the body are evaluated and #f isreturned. Iftestevaluates to #f, then all the expressions in the body areevaluated an d the values of the last expression are retu rned .

    If there are no expressions in the body, then #f is returned .

    unless(detect-gas? (nose))

    light(match)

    end unless

    case [Macro]test1 =>body1 ;...testn =>bodyn ;[otherwise => otherwise-body] [;]

    end[case]

    values

    case evaluates the tests in order.

    If a testreturns true, the correspond ing body is evaluated, and the lastexpression in the body is returned . If there is no body in the testthat succeeds,then the first value of the testis returned . Subsequen t tests are not evaluated .

    If no testis true, then case returns #f.

    As a special case, the keyw ord otherwise may app ear as a test. This testalways succeeds if there are n o other su ccessfu l tests.

    case

    player1.money end-game(player1);

    player2.money end-game(player2);

    otherwise

    => move(player1);

    move(player2);

    end case;

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    50/214

    30 June 3, 1994 Dylan Interim Reference Manual

    select(target-form [bytest] ) [Macro]match1a , ... match-1n => body1;...

    matchma , ... match-mn => bodym;[otherwise => otherwise-body] [;]end [select]

    values

    Each match-listmu st be a sequence of expressions separated by commas, or thekeyword otherwise. The bodies are implicit bodies (may be any n um ber ofexpressions separated by semicolons).

    When the select form is entered, the target-form is evaluated, generating atarget value .

    Theclauses are tested in order, using the following procedure:

    Each match is evalua ted to prod uce a match object. The match expressionsare evaluated in order.

    If a testfunction was sup plied, this is used to compare the target object tothe ma tch objects. Otherwise, the match objects are compared to the targetvalue with ==.

    If a match is found, the corresponding body form is evaluated and thevalues of the last expression in the body are returned. If there is no bodyform in the matching clause, #f is returned .

    Once a match is found , the following match-object and body expressions, inthis and subsequent clauses, are not evaluated at all.

    If there is no matching clause, an error is signaled.

    As a special case, the keyw ord otherwise may app ear instead of a match-list.This clause will be considered a m atch if no other match is found . Because anotherwise clause matches when no other clause matches, a select form thatincludes an otherwise clause will never signal an error for failure to m atch.

    Since testing stops when the first match is foun d, it is irrelevan t wh ether thetest fun ction w ould also have retu rned true if called on later match-list

    elements of the sam e clause or on ma tch-list elemen ts of later clauses.

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    51/214

    Dylan Interim Reference Manual June 3, 1994 31

    select ( career-choice(student) )

    art:, music:, drama:

    => "Dont quit your day job";

    literature:, history:, linguistics:

    => "That really is fascinating";

    science:, math:, engineering:

    => "Say, can you fix my VCR?";

    otherwise => "I wish you luck";

    end select;

    Dylans select with a test ofinstance? is similar in effect to a Com monLisp typecase statement.

    select ( my-object by instance? )

    , , => "a graphical object";

    , , => "a computational object";

    otherwise => "I dont know";

    end select

    form1|form2 values [Macro]

    | (or) evalua tes theforms from left to right. Ifform1 returns tru e as its firstvalue, that value is returned and form2 is not evaluated . Ifform1 returns #f asits first value,form2 is evaluated an d its values are return ed.

    form1 &form2 values [Macro]

    & (and) evaluates theforms from left to right. Ifform1 returns #f as its firstvalue, #f is returned and form2 is not evaluated . Ifform1 returns true as its

    first va lue,form2 is evaluated and its values are return ed.

    Iteration Constructs

    while (test ) [Macro]body

    end[while]

    #fwhile evaluates the expressions in the body over and over un til the testreturnsfalse.

    Each p ass through the loop begins by evaluating test. Iftestevaluates to a truevalue, the expressions in the body are evaluated an d the looping continues. Iftestevaluates to #f, the loop terminates and while returns #f.

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    52/214

    32 June 3, 1994 Dylan Interim Reference Manual

    until (test ) [Macro]body

    end[until]

    #funtil evaluates the expressions in the body over and over un til the testreturns true.

    Each p ass through the loop begins by evaluating test. Iftestevaluates to #f,the expressions in the body are evaluated an d the looping continues. Iftestevaluates to a true value, the loop terminates and until returns #f.

    for(clauses [Special Form ] [{until | while}end-test] )

    body[finallyresult-body]

    end [for]

    values

    for allows one or more clauses. Each clausecontrols one iteration variablethrough out the iteration. The optional end-testcontrols whether the iterationcontinues or terminates. It does not control any iteration variables.

    The kind s ofclausesinclude explicit step clauses , collection clauses11, andnumeric clauses :

    Explicit step clauses

    {variable| variable :: type} =init-valuethennext-value

    Collection clauses

    {variable| variable :: type} incollection

    Nu meric clauses

    {variable| variable :: type} fromstart

    [{to | above |below} bound][byincrement]

    11Note that collection clauses are imp lemented using forward -iteration-protocol.

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    53/214

    Dylan Interim Reference Manual June 3, 1994 33

    Iteration w ith forproceeds through the following steps:

    1) Evaluate the expressions that are evalua ted just once, in left to right order

    as they appear in the forstatement.

    For explicit step clauses, these expressions are typeand init-value. For collection clauses, these are typean d collection. If the value of

    collectionis not a collection, signal an error. For numeric clauses, these are type, start, boundif it is sup plied, and

    incrementif it is supplied. Ifincrementis not sup plied, it defaults to 1.

    2) Bind the iteration variables of explicit step and nu meric clauses. For each explicit step clause, bind variable to the value ofinit-value. If

    type is supplied an d the value ofinit-value is not of the specified typ e,signal an error.

    For each numeric clause, bind variable to the value ofstart. Iftype issupp lied and the value ofstartis not of the specified typ e, signal anerror.

    3) Check numeric and collection clauses for exhau stion. If a clause isexhausted, go to step 9. A collection clause is exhausted if its collection has no next element.

    Num eric clauses cannot be exhausted ifboundis not sup plied. Ifboundis supp lied , the following table gives the conditions forexhaustion:

    increment >= 0 increment < 0

    to variable > bound variable < bound

    above variable = bound

    4) Bind the iteration variables of collection clauses. Fresh bind ings arecreated each time th rough the iteration. For each collection clause, bind variable to the next element of the

    collection for that clause. Iftype is sup plied and this next element ofthe collectionis not of the specified type, signal an error .

    5) Ifend-testis supplied, evaluate it. The termination conditions dep end onthe symbol used to introduce the end-testin the for statement. If th e valu e of end-testis false and the symbol is while, go to step 9. If th e valu e of end-testis true an d the symbol is until, go to step 9.

  • 8/8/2019 Dylan Interim Reference Manual - June 3, 1994

    54/214

    34 June 3, 1994 Dylan Interim Reference Manual

    6) Execute the expressions in the body in sequence. The expressions in thebody are used to p roduce side-effects.

    7) Obtain the next values for explicit step and nu meric clauses. Values areobtained in left to right ord er, in the environment p rodu ced by step 6. For each explicit step clause, evaluate next-value. For each numeric clause, add the values ofvariable and increment.

    8) Bind the iteration variables of explicit step and nu meric clauses to thevalues obtained in step 7. For each clause, iftype is supplied and the nextvalue for that clauseis not of the specified type, signal an error. Freshbind ings are created each time throu gh the iteration. After variables arebound, go to step 3.

    9) Evaluate the expressions in the result-body in sequence. Bindings createdin step 2 and 8 are visible during the execution ofresult-body . Bindingscreated in step 4 (i.e. the iteration variables of collection clauses) are notvisible du ring the execution ofresult-body . The values of the lastexpression in the result-body are returned by the for statement. If thereare no expressions in the result-body , for returns #f