Applen

.Apple, Pascal
Language Reference Manual

Cu~ertqn(), Calufouliii_ 950 14
(.t06) 996·1010

10260 'Sandie)' Drive

NIl'tlCE

Al?pl,e Compl.lt@:r;" 1.nc. reserves the produ.ct: des,cribed ill, thd.s manual

right to make 1mp:rQVe;iIle:nt,~; the in at arry time and ~thou.!: £lOU ~e.

Apple II

APPLE COMPUTER INC. MAKES NO ~IES, 1l.1'il,"lUR EXPRESS OR [Ml>t.IED. WI'nI RESl"ECT TO 'IlllS MAmJAl. OR WItH RESPECT TO mE SOFTWARE OESCRlBED 11-1 'TIUS MAlimAL" ITS QUALITY. PERFORMANCE i MERCHANTABILITY. OR FI1:NESS .FOR AN"lPAR'.EI GUl,AR PURPO!it. J!l>lE'i.E. COMPUTER INC. sa nWARE IS SOlJi OR LICENSED "AS IS". TlI!! EriI'Ji'UtE RISK AS m ITS QlIllIiITY AND PERFORMANCE IS WITH 'TIllE JiU'i.'£R. SHOULD THE .PIl.iJGRAMS PROVE DEFECTIVE FOLLOWlliG 'mEIR PURCHASE, mE BIJ'lER (AND NOT ,M'FLt: OJMPUTER INC". ITS DISTIH.BUTOI!. .• OR ITS RE1AD.F..R) ASSUMES THE f:Il;UIl:E COST OF ALL NECESSARY SERVICING. REPAIR." OR <OORRiEC.TIQN ANnAN' INCWENTAL OR OONSEQUENTIAL DAMAG~S. IN NO EVENT lIILl.. J!J>P1.E COMPUT E.RINC • BELIAB t, E R 1)1 RECT. INI'HRECT, lJl'CIDENTAL. OR rOONSEQI1ENTtA!. OAl!tAGES,RESliLTlNGFRO"l ANY DE.FECT IN l'1U: SOITlJARE, EVEN IF APPLE OOHPUTERmC. HAS EEEN ADVISED OF ~E POSSIBILITY OF StJrCiB: IDllM/I,OES. SOME STATES 00 NOT M.J:.OW 'I'HE EXCLUSION OR LIl1ITATION OF IMPLIED WARRANTIES OR L1AlHLI"r'l roa. INCIDENT.AL OR

Aplple Pascali
Languo,ge Reference Manual

ro

CONS,EQUENTlAJ:.
APPLY 10 YOU.

Do\MAGES,

00 TIlE ABOVE LIMITATION

Olt EXC].llSIOtlMAYNOT

This manual 1s COP:yrilll:it'l'd. AlI:d ghtsare reserv,ed. .his document may not, in whole. or part, be ,copt ed , ph 0 '!: 0 c:.op:l ad , Ji:leproduced., t r,!!lDslated or reduced to any E1ectron'l c medium or IlIiBcbilIle reada'bl e ferm wi ttmut pti(jl: ccmBent. i.l! 10Trl ting,,, frnm Apph~ Computer Inc.

©

1980 b)' APPLE OOMP'U:lttR INC. 1~:l.6~ Bandley Drl ve Cuperti [10', Cali f erut a 95~H4

(i!ilS) 996-lilU

The word APP!..E and the Apple 11'1.£ COMPUTER INC. APPLE hc a:'Iut. ,,uL0f:U c

logo

are

-reg1.stered

trademark-Be

of

NB0-0Ul-il0)

TAB,LEOF CONTENTS
The Apple Pasc.apM sys,t~m incor'Pot",at~s UCSD Pas ca.I"''! and Apple ext.ens Lous fOI: gr,!'lphics and oclier :EllIm:t..h[J~., UCSll Paaca.l, Was deve.lopc.d l!3JIgely' by the Institu.te for Information Science at the. Univllrsit.y of Calif,rr ..ia. at Sa!! .Diego,. under the. d:!t'e!:I:~.on of Keune.t h L., BQwl'es.

CHAPTER 1

is a trademark o'f The Regellts of tbE" U~verll1ty of California,. Use the:l:eof iil ecnj uuct 1011 wi th any gOQds 0'[' servdces is authorized byspe.c.:LUc Ll.canae 'only and is an indication t.hll.!: the as scc i a ted nroduct or se t'vir:e has quality aasuzance sta.ndard a prell c.:i bed by the ll.rl Versi r.y. Any unaut hor Laed use thae eof is COlltrary 'to the law::! of rn.e, S1::ate of GalHonaia.,
"UCSD PASCAL"

INTRODUCTI'ON
~
:1:

1

_,t;

2 3 4

4
4· 4

Get.tfng Started Se,ope of Thh Doeu:me1'tt How to U,s'e This Document; O'tga.n:t~at.Lon z NQta.t.i.o~ Used .:In This Mli.TIWll Df.ff@l!'ellc,eS :Betlfe.e.1l AppLe and StandardPaBcal hl!defined 'Vat'hbl,~ 'T:ype!! Bui It,-In Proc:e<iM'!:f!8 and FUl'lctions

5 .'5

Br@aking I'rogramJ'i Into Pieces Special Units for the Apple

CHAPflER 2

IPREDEFINED TYPE:,S
8 The. STRING ~yp e H 'Jibe FILE Types ~1 A t;ote all TeI'!lIimllogy llOOllltA.CTlVE F:!_l,es 12 lJ~t.yped :!liles 12
12 14

7

Pl."e.deUned Files
TexrUl6l.8 Th e SET Typ e s

15
15

Pat::'itea Vadabl@$
.PACK j!it>d UNPACK.

15 15 17 18 19

Facked Files P,2c:ked Arra.ys P~cked Reco'rds U~h~8 Packed Varis.bles The LONG INTBGI!R Type

,as, Pa.~a.Il1.el:en,

APPLE PASCAL LANGUAGE

APPLE PASCAL LANGUAGE

CHAPTER 3

CHAPTER 4

BUILT-IN PROCEDURES AND FUNCTIONS
22 22 23 2.3 Stdllg Built-Tns The LENGTH Function Th e POS Funet ion The CONCAT fUllc'tion

THIE PASCAL C,OMPIILER
S8 lot.r,ociuctioll

57

58

Diskette Files Needed

VI
Z~,

The COFY Fuuct ian
Tli

e

Dg-r,ET'f.: Pr ccedur

e

59 Using tbe 'Compile;r; 61 The CO!llpiler Opt Lous Ii,l Compi Le.r Opt ton Syntax
1i2 The; "Comm.e1:!t" ""IO Check'· ''Listing'' Option

25

25
26

The [NSl".!tT Procedure The sra Procedure
Jnp ut and Output Built~los

30 30

26 2'1' 27 :W 29

Overview of Apple Pa sca.I I/O The REl-lF.ITE Procedure The RESET Procedure Tht> CLOSE; Procedure The EOr tUDct ion

Facilities

62 ,&3 63
64

66 66
66

'the the The the The Tbe

Option Option "Tncl.ude File" Option
Option

"COlO Statements"

"l'4cload"Opt :10m
"tage" OpU'on

J2 ]2 3-3
34 34

The EOLN function The CEt and PUT Procedures,

66 67
&7

The IORESlJ1T Funct Ie n Introduction to Text 1/0 The REAlI Procedure READ With a CHAR Variable
READ With
01 ~lumer1c

The "Quiet Compile" Option 1'ne "Range Check" OptJ.on 'th,e ".R.,esid.en'I:." Opt.Lon TIle "Swapping" Option

68
68

The "User

P.ogram"

Op e ion

70

The "llse 1ibTal:'Y" {lp~ion Compile. Option Summary

35

The PEAIlUi Procedure

Variable

36
39 39
~1

the PACE Procedure The SEEK Prof:edure 'l'11e £JNITREAD and UNl'IWR.ITE Pr ccedur-e
The UNITCLEAR Procedure Ih e BLOGKREAD and BLOCKl<TIUTE Miscell~TIcous Built-los '!'h e AT~.N Funet Icn 'l11e V:X: Funct.Lon The TRONe Function The PI-IROrTEN Fun ct ion

The WRITE and ~RITElN PTocedures

CHAPTER' 5
..

42 42
43 ~3

The UNITBDSY Function The U~ITWA1T Procedure

PROGRAMIS IN PIECES
72
14 74

71

Funct

ions

In~roduction
SEG}!ENT Procedures Requirements and and Functions

45 45 45 45 45

L:l,'Cll ens t Ea,;t':I

75
75

L1bracieB and UNITs
UNITs and USBS

76
76

46
48

48
48

The MARK and RELEASE Procedure!l The HALT Procedure
The EXIT Pr ccedure The HF)lAV'AtL Funct 1.on

Regular UNITs Intrlnsic U~ITs

77
78

The INTERFACE ParI!: of a UNIT Tn!" IMPLE.HENTAIION P'an of a UNIT The InitiO!lhation An Example l1NIT
Changing

i8

49
49 51 51 51

The COTOXY Procedure
The TREESEARCHFunction Byte-Oriented Built-Ins The SIZEO' Function ]'he SCAN Function Tbe i'!QVf.LEFT and HOVERIGflT

~o
81
82 Proced uTes

;9

n~

Pan

of a UNIT

Using the Example UNIT Nesting UNITs
A

EXTERJ.IAL P['ocedl.n;es

UNIT or its Host Program
and FuncUons

'j:1 53 5~

lbe FILLCHAR Procedure Summary

APPLE PASCAl lANGUAGE

APPLE PASCAL LANGUAGE

CHAPTER 6

APPENDIX A
83

OTHER DIFFERENCES
84
84 84·
85

DE MONSTRATIONI

P'R'OGRAMS

107

Identifiers
CASE Scatemenes Comments
COrD

85 85
86
86, 86

85

Pr'ogram Rf'.adil'lgs :;·1ze Lim1.ts Extended COllIpari.sOrls £'roced.u~es and Funct10ns RECORD Types The ORD Function

lOS Introduction 108 A Fu11y Anuotate,cl[ Graphics Pz:ogram 12.0 Qther Demonstration f't'ograms 112,10 Dhkette HIes, !'l:~ed!;!d 1:1.1 The "'!lttE" Program
123

as Paratmeters

1:1.4 125 126 126
127

The "'l'IAL.ANCF..ll"Program The "CROSSRBr" Prog'ram

,L28

The "SPlRODE~IO" Prog:ram Thf! "HILBERT" Program lh.e "(;aJ;~nEt,Jo" Program The, "r;,RAFCHARS" Pr,ogram '1'b~ "lnSKlO" P~agra.11I

CHAPTER 7

SPECIAL, UNITS FOR THE APPLE
'90 Apple

89

APPENDIX B

90
90

91
!l!l !H
9:1.

93 94 9S 0;,5,

Hn

96 98

Graphics: The. TURILECRAPHICS TJNIT Screen The INITTURTLE Procedure The GRAFMODE Procedure The IEX.nwDg Procedure The VIEWPORT Procedu.'[e Using Color: PENCOLOR MOTe Color.: FILLSCREEN Turtle Graphic Procedures: TURNTO. TURN, and HOVE Turtle Graphic Functions: TURTLEX, TlJR11.'EY. 'TIJRTL.E.ANG, and SCREE.NBI'r Cartesian Graph.1cs: The NOVETO Proceduce Gnph1c Arnys: The DRAWBLOCk Procedure

the Apple

'TABLES
132 133
1:l4 L:l!i H,I
136 13]

131

Table
Table

Table Table Ta.ble Table Table

1; Exec.ution Errors 2: I/O Errors (IORESOLT

Values) 3: Rese'rved WOl"ils 4. PCed,eE.! ned Ldent, if i er s 5: tden~if1ers Declared in SuppUed 6: Compiler Error Mf!.ssag@s 7 : ASCII Cnaracter Codes


UNITs

'rex!;

as Gr~:ph1cs:

WCHAR. WSTR.lNG, and

CHARTYPE

Othel' Special Apple. Features; 101 The RANDOM F~nct1on 102 The RANDOMIZE Procedure

The APPLESTUfF UNIT

APPENDIX C

ADDITIONAL

TEXT 1/0 DETAILS

143

102 L03
104 105

Transcendental

The KE~P~SS FUnction <'ADDLE" BUTTON. aod Tl'LOUT Making Musi.c; the NOTE Procedure.
FUDctions!

T~e TRA~SCEND UNIT

APPlE PASCAL LANGUAGE

APPLIEPASCAL LANGUAGE

.APPENtDIX [)

APPENDIX F
147

ONIE-DRIVIE ,STARTUP
1.48 You \,lUl Need St arcup 148 Step One of Sta:r.~up 149 Step Two of Startup 150 Changing the Date 1.'3>1 Mak.ing Backup D.~ skette Copi es l5l Why We Make Backups Equipment

APPLE PASCALI SYNTAX INDEX

191

148

Th.!! Two-St'Ep'

205

151 152.
]53

15.5 158

158
158 l60 1M 165

How We. :Make Baekups Geuing 'tile Big Pi c cure Fo:tmatt:i'ng Ne\o1 Diskettes Making !the A!'.cud Cop1.es Dc I it:: Aga.in, Sa,m UlOiD!! the System A Demonst~~tton Do' It Yourself What to Leave hi the. Ddve One-Drive. SU[lliJlfIry

APPENDilX E

ITWO-ORIVE STARTUP
J 70
170 1/'1 E,quiprnapt You Wnl Need More. Than Two D'bk Ddves NUIIlber1ng rhe Dhk lId.ve!>

169

,. I

J. 71
1

n

Pas ca 1 In Seconds
Changing the Oat.e.

t 7J.
17] i. 7'4 174 .175 i. 79

Making

Backu:p' Dislce.ne Why W'e Make Back.ups How We 'MakeB!lckupS

Copies

1n

Getting the lUg P1ctu['e FormBtl:..:I.·[I,g N~ P;t5ke.ttes

180
HlO

MakinS the Ac rua I Cnp;! es Do It: Agajn, Sam USing the Sy~;tem
A Delil.(m~tr .. t.Lcn

~Sl Hl6
186

Do It 'ioDJnelf What to Leave In
Uaing

tile Drives

MQl"e Than. Two Ori\r'e~

IB7

KuHiple-Orive

SUliLrnary

APPlE PASCAL LANGUAGE

APPLE PASCAL LANGUAGE

APPLE PASCAL LANGUAGE

GETTIN.. STARTED G
System for know bo"", te s t en up to ~ Al"llle !'Cl9ca I Op@rat:aug use with the apple Pll_s~aI language, plEase read Appendix [] if you bave one disket e drive, or Appendi~ E if you have two or mo~e diskette drives. _ Each of tbese Appendices i5 a tutorial '~es,· ~ sl,on, coverillf system startup, diskette irdtializotion, diskette copying. and a demons t{'ation of App l.e P~scal programming"
If you don' t Blrf!ady

At va.:rioul;! places

in the

[ext

you

...i 11 see

thO! specd a I

symbol

~I

l;(l'hich 1ml:1cate.s a reature
sp,ec1al

that

you need t:obe

cautious

about.

Another

sJ!lIlbol ill,

SCOPE OF THIS DOCUMENT
This de eumant covers the features of the Apple PIl.Sc.a.1 programming languagE' the [ :UE' di! reT ent f:rom the i'Standa r d Pas,e.al" 1.rmguage defined ~y Jel11len and Wirth in the Fa1lLO_a1 SeI' :Manual and Report (Spring,erU Verlag. Nel<'York, 1978). Th is includes the d Lf fe r e ucea introduced in UCSD Pascal, and a l so special I!lr'rensions of UGSD Pas.ca.I ror the Apple computet'.
The Apple Fasc!l.l system facilities auch as the ~d"1to r, tile Linker, ett:. fire COV'IH"ild in t he Apple ·Pa.8 I Oper~!'[1n.g Sys tern Ref e ronce Manual. ca These facilities a r e useful in va rf.oua app l t.ca t Iens besides Apple Paaca.I prcgr:3_mmtnl!:; they arE! discussed heTe only as they relate speci f i~ally to Apple Pascal programs" Which indicates something t\;·a.t a particularly is l'Iot: obvious).

useful

piece

of

Lnf ortuat t on

(usually

I
Chapters :2 and 3 cover the latge d1.ffe!:encefl in Apple Pascal rhe moll e ll'iilliedia.tce prograL1llll1ng hn,paet I 'the dif hrrenCE'B ptedefim~d typ,es, proc@dul"es, ood function!!, especially the for input and output. that will

have

:ln
pIocedul:'es

Chapter 4 covers tne compiler are poloierful and imp 01;'1: an 1: •
be found i_pt:he Apple

operation

HOW TO USIETIHI'S DOCUMENT
'1"0 use chis dO'!:l.Illlenr you mmH: either have B thorough kJ1owtl!dge of Standard DT lICSD Pascal, or use BOl!lle bOOK or manual that f u.Lf,v describes StaMard or UCSO Pascal. This ill ,<I relenmce manual. designed ro give ycu thaia,!:: t S "OIi t._ho1.l't very much emphas Ls on teach Lng yOIJ Pascal" YQIJ shcu.l.d a.l sn h,av~ the Apple Pascal {l-~erat_icg Sys t~m RE!Eereoce Manlla1, which gives cOI:rplete information on the various sys [em Eac Ll.Lt.Les that support the c:re.ation and deve Lopment, of Apple Pascal prQgrallls
0

Furthe. (If! t a I Is 1"8,8(;,al Ope ... 1:1ng Syst~

and tlile compiler options. which Oil comp'i leT apeTat ion can
Reference KarlUa.l.

Chap t e r 5, covers techniques £0:1: breaking 8. prog.:a'm into' aepar at e pieces which can be linked eO,gether. These techniques are anothar major area of diffeI:e.nce but are not, needed .for small prograuLso Chapnr 6givea for the 1:emain:i!l,g differences most progr,ams.
in,

the

Ianguage , wh.ich are options of Apple

of

mi~].(u impact

Cbapter 7 covers tb.e ~t1["eme.ly powerful 1n,eluding the Tunleg1:aphicS pae1r..age. Appetldh: A preeent~ also describea the Appendix
and the

Li.hr.ary

Pascal.

One aspact;

of the Apple

Pascal

Operating

SystE!l11is eevared

in

this

manual: eh e 'p rocl'durel'l f OT' Il t a rr il'l8 up rhe By,st eJJ1 when your purpose is, to wOl'k 'iJ':I t.h Apple Pascal pH!grams APPE'l1dicl!:!l]) and E describe these
0

a fully annotated pr og ram that uaes MtlWnstration programs supp Li.ad w:lth
various tables r e.Lat ing

graphics" and Apple Pascal.

pl"ocl:!du:res

B

CQUltBiM

to the

Apple

Pascal

Language

0

system.

Aptlendit.es D ,and E coveir Byste'm startup and e5,sential ,procedures f or US~ ,.i t h ,the ,A;pp e Paaca I Language» L
App@ndix F is
II

opeI:a,Ung
the Apple

cilInplete

sec

Qf syntax

dia8:r::am!l for

Pascal

languas,e.

2

APPlE PASCAL LANGUAGE

INTRODUCTION

3

NOTATION USED IN THIS MANUAL
In syn.tax desC[:iptioTls. the follololing

~ A SeJ: of new byte-ilTi.eoted.
:l.s uaed ;

!milt-'ins.

Se.e Chap~er

J. the

convention

- New built-ins called MARK and RELEASE~hich replace DISPOSE of Standard Pascal. See Chapter 3. may
- 0 ther new built-ins and built-inll • Se~ Chapter redef:hrlti~ 3.
M,

- Square brackets U an used Ie-,gaUy be oalitte.d from the

co enclose il)'nt.ax.

anything

'that

of St aada rd "Pascal

DIFFERENCES BETWE'EN APPLE

AND STM4DARD PASCAL
d1ffeJ:'encee are

_ '1'hetraWlcl!od~,lltal f unct; ions EIN, COS. ,SQRT are notbu:Ut-ins in .Apple Pas~al. library functions. See Chapter 7.

E.XP,

MAN. they are

LN, LOG. and provided as

Th"" major enes ,

su.mmarized below:

see

Chapter

(;; for

the minor

BREAKING PROGIRAMS INlO PIECES
_, SEGMENTprocedures and functions, willen active., See Chapu~r 5. .... hdch
reside. in

memory only

PREDEFINED VARIABLE TYPES,
- A new variable type. STRING. IlIllJPport:~d by a sec of Dew bull t-'in proced1Jlt"es and fum::tiOD.lI• See Cl1apteu 2

- UNITS. whi.ch are sepa r.a tely that can be integrated into heHity. See chapter 5.

compiled any bost

coLl.ect Lons of procBdures program via a library

and 3.
A Deli file

- EXTERNAL p.ocedures and
Apple

Pascal program
into

cyp,e, INTERACTIIlE. supported by che exc'endill!d file 1./0 proceduTes, and functiol'ls. See Cbapten Z and 3. nn SET types.

t he n integrated ,See Cha'pter 5•

functions, which are declared in an but implement~d in assembly language and a host jlrogram via the library faC:iH.ty.

.. MinO!:: restrictionS

- Minor differences in tbe treatment of PACKED variables. ,Automatic, PACK and UNPACI( Q:iI\eraHons. with eliminatinn ,PACK and UNPACKprocedures of Standarrd Pascal. See Cbapce-r l. - An extension

SPECIAL UN ITS !FOR lHE APPLE
of 'the
_ Tbes are major

in a system libraIy> for the high-restlluden
Chapter

facilities! EoJ:' the Apple. implemented as mllTs They include the Turtleg.r:aphic5 package color display of the Apple. See

INTEGERis
decimal

of the LNTEGER.type called LONG INTEGER. ,A LONG a value Eepresented by up to 36 binary-eoded (BCD) digits> See Cbapter l.

7.

BUILT-IN PROCEDURES AND FUNCTIONS
These are

the procedures

and

functions

that;

are

Language itself. as opposed to SIH!ci~l-purpoBe the system library. Su.U..t-in ' pJ:'ocedurea and "built-ins" fOI: shoet;

par t of the Ap~le Pascal func'tiolls imple.mented in fu'nctions are called

- New built-ins, and 3.,

!iuppo{ting

'ST:iUNG

var I ab.l ea ,

See Chapters

2

- :Extended def Lnd t100!; of INTERACTIVE fileJ;l. See

the

built-ins
2 and

Ior
3.

11l,e

I/O .• supporting

Chapters;

4

APFtE PASCAL LANGUAGE

INTRODUCllON 5

8 1l'te smJJIC 'l'ne 11 'lit. 1tLI 'iypeIJ
11 11 12

12

, .ote em T.~:tIolOU JJm!,1WJttVI P1.1ee Vu~ 'Ues

PncleUnH '11••

11 1QtfU" 14 T&f11 IypeJ U PIt¢b4 VarUbUa 1S PAC¥. .ad UlPAc::X 15 P.cked :run :p~~ Art.,. •7 lecorill 18 Uqul hebd V..n.b)..... . 19 1'tI,• .to1lG lJInGQ T;pa

m

,.eked

h.~eu

6

APPLE PASCAL LANGUAGE

P-REOEfINEO TVPES 7

In adcl1tio~

to the predefined types of St.andard Pascal CHAR. ARRAY. etc.). App Ie Pascal has a STRINe type. an type, ~nd a LONG INTEGER type. Also. the Pasca.l. deta.i_l!3 of
certain

(REAL, INTEGER,
INTER}ICTI'n file

The individual characters ...nehrn a STRING are indexed from l to the LENGTIlof the STRlI>lG. LENGTH is a built-in, function wbic.n :l.s deecrlbed in Chapter 3. For e.Kalllple. if rITLE is t!:tE llUU:\e of a stri.ng. then TITLE [11

other

'predefined

types

differ

from Sl:and~"t'c1

1s ~ ~afl!rence to the first character

of TITLE,

and

THE StRING TYPE
Apple Pascaf has a nelor predeclared type. STRING. The value of a S"IRING variable is a sequence of characters,. Variables of type S'rRtNC are essen.Ually 1?ACitED ARRAYs OF CRA:R that have a dynamically d1anging numhe e of element.s (characters). Ho""ever, the va Lue of a STRING va.dable cannot be .!3.ssignerl to a PACKED /!BRAY OF C'RAR" and tbe value of 4 I'ACKED ARRAY Ot' CHAR cannot be assigned to a STRING vadable. Strings are auppor t ed by a set M budLt--d n procedures and Eunc t.Lenaj see Chapte~ 3,. The number of chara,cr:ers 1.i:i a string at any mcmen't is the len&tn of the string. The default maximum hmgth of a STRI.NG varl,a!:! Ie is, BIjlI (:.ha.r8Cl:erS, but t:h!_s can be ov.erridd'en in 'the declaration of a S,TIUNG variable (up Ui th'il: absolute limit of 255). To do SO, ,:.~t the desheil maximum lengttl Lu [in:acketsl after the type ident.ifier STRING l':_xample.s .. of dec Iaeat Lens of STRING V:l!'"i!;lbles u:e: ~
TITLE: STR.UlGi
(*
j:

TITLE [ LENGTH(TITLE) J is a rei'erem::.e to the Ias t
character

of TITLE.

A variable of type STRING may be cempe.re d to any other variable of type STRltlG OF to a string conat ant, regardless of its cur-rent; dynamic lena th. The comparison 1B lexieogr~.pbiClll: i. e-•• one scr1.ng 1s 'lg·l'E.~a t.e.r than" anot'heT if it would come first in an alphabetic list of Bl:rin~!l" The ordedng of the ASCII charac:t:er set <Sf!~ AppendiX R) ill used to

detenrlna chis. The folloloring comparisons invclvint variables

pr cg ram is a demonstration of type STRING:

of legal

,COMPARESTRINCSj VAR So STUNG;
PROGRAM

T:

STIUNG Iil~1

j.

BElGW
S:• SOM'ELH.ING , : T :.. 'SOMETIlING BIGGER' ~ IF S .. T TUM WRITELN ('SU1i'ie:;s do nOr .... rk \,IH)' ,",ell') e ELSE IF S> T THEN W1\[TF.I.N (5.' is greate. than • T) ELSE IF S ..; T THEN WITELII (8,' 18 less than 1): IF' ,S ., 'SOMETIHNC' THEN WR1TttN(S .• • equals • ,S)j IF S ) 'SAHE'TIHNG' TtiEN WRITELN(SJ~ is greater than SAMETHING'): IF S ~ • SQ}IETH1NG .. TIlEN

defaults
(:II 8.11Q ..... B

to .a ma.1!imum. lll.ngch of 11 charact ene "')
to he
lie

NAME.: STRING [J~I

the STRHlG e.l'i41Oacters"')

m~ld~um

of

311

The value 8'tarement
'fITLE

of a STRING variable can be altered by using al'!. assignment with a. stri.ng constant e'r another STRING varl,able:
:'''' THlS IS A TITLE

r,

or
NAME : .. TITLE or 'by mteB.tlS of

the. RE.AD ~u'ocedu:rB as described

in the next

chapter:

WRIT!!:LN ,'BLANKS ELSfl

PON' 'f COUNT')

REliJJLN(TITLE)
0['

WRITELN ('SW\NKS
S::::;"'XXX'; in. the

.l\PPEAa TO MAKE II DIFFERENCE").:

by me.aDS chap t.a r :

of the STR1NGbud Lr--d.ns, aliSo described'
i, 3'1)

next

T:-'ABCDEF'j IF S > T THI::~'
WR1IELN(S,'

NAME: = COPY ('In:L.E.

ELSE
'WRITELN (S,'

i~ greater
JLs

tban than

',T)

less

" ']')

Note. that a Btring constant may not contain must 'be on 8. si'ngle lIne in t.be program.

an end-of-line;

the

constant

ENlI.

S APPLE PASCAL LANGUAGE

PREDERNED TYPES 9

The abtWl! program

pnoduces

~he follol.':i.ng

OU!;P1.lt:

'TIHE FILE TYP'ES
A NOTE ON TERMINOLOGY

SOMEl'RI~ is less than SOMtTl!!NG :BIGGER S·OME'flUNG e qu a La SQI-lET.IUNG SOMf.'I'lU:NG Ls g~ aa te. r e~':1il SMt:ETHING BLANKS lU'PE:AIlTO ~!AKE; 11. DIFfl:RENCE XXX is greatl"'I" than ABCDE.F'

Strings

can

also

be dec Lared

a.s CCflSt<3l1tS, aa

J.p.

'the

folloidng:

PROG R»! full Z j: CQNS! SAl-mY ,," "Hi
t he ru ,

!' 'm Sammy

the

St:dng!';

BEGIN
~ln.I.N(SAMMY) Effi). The

For ~very rUe named F that. La decla.r~d ill II Pasca.l program, tl,e-rc :1.9 an au'tomattca.lly d@c.lared vllri.:)Iblena.med F. TI-ri-a 1'5 the "buf f e r var t ab Le" of the file, Some Pascal manij),. Ls also . use the lDos~_'r term "wimlow" to de sc r Lba the way t;~at d.iffenmt HIe records can be loaded into the buffer va~i1)ble. T1;,-;ts manua L. tl"lSti!a'rn, t aLke abol1ta"file pu i.nt.e r " associated with e~ch open file. The jfil~ po1nte. points to one record :ft_ the file, wh1cn is, ce.l.Led the "cur r en t recDrd." Please understaml that che file pointer ts not a Pascal POINTER variable but just Ii c:ol'lvi!n1.ent way of disCUJ3;s ing file 1:ecord:~:.
1]

The follow'fng
f ur ther 1n thE nex t chapter, in and funct.Lcus of Apple Pa sca'l , the INTERAC'I'[V£ special format

sections

use of STItING variables ·is d1s~lJssed c:onn£!t'tioVl with the bud lt~itl If ro cedur'es

describe Apple Fasc,al's speci,al Ule fih type, tmtyp",d f LLea , predef.inml, files, EO'T files of ch 01 cte:rs., t'a

featu'lres; and a

IINlERACTIVE IFllES
A V<l-ri ab Ie of tll'P~ STRiNG
COlflUO!:

be Im:rexed

hi> yond

1 ts

cur rear

dynaed c

Ieng t h ,

The follow:ln&

sequence

w111 resuH

ioao

invalid

ipdex

run-

t :Lme e·r·r'or:

a 'tEXT file. is in RESET. READ,. and Like

difference

an iNTERACTIVE file is <'l file of chBT.'I<l:tM!'fS. the Yay INTERACTIVI'; nd TEXT filea a are handled READLN pr oee dur es the

ThE' by the

TITLE :.- • J 234' ; TITtErS]:'" '5' Sew-are of: zero-Ieugtll string s : they cannot be indelted a taIl without causing unp r ed Le t ab Le resul es or I'! run-ti~ eTJ;[)r. If I! fl.oirll11l 1tJ.dexl!~ a 5tl'111g that Illi,g],t. h<3\!"~zeTO length" it IOhould first use the LENGTH fun(:ciotl to see if t.he hH'l~,th is zero. If the l@ogthJts zero, the pFogr<J~ shQuld not execute s t.a t eme nr s the e index t he string, See Ch<t-pter' :3 ror tIetlllls on t he LENCTII f.m~tian.
tloticli! that a str·fng value cont;aipin,g only one char act.e e is not. the aame th:iTng as E! GHAR vEtlue: s tri nilS iii nd CHARs are di s t Lnct data types", The Oll!? excep t i01'l Ls t.ha.t <J s trl r.gco 1']8t.a nt c.ontai m ng Dt1i]l one ch.ar act e r

When

mu!> firs t opera tion:

program performs a GET th..a r :15" 1 t loads the Ei.rst cl1,a ae t e r of the file r into the file"s buf f er va.riablll: and thenadVBrtees the Ule pointer to the n"':H;t character" Ii. subaequent; READ 011" REAfiLN 'i1:i t.h a variable of type CHJ\R be.gins its oper a t ioi'l by ftTS t taking the charm::tei: that t5 already in the buffe. v.u:1ablElIIIl.d tnen pe rf o rtnf.ng ,01; GET.
,&

Pasca I program READ5 c:11<!;l"l]etersfrom a 'rElIT Ed Le, t ope~thE file wi. t h RES,E.1'., RESET a!Jtamatically

I:E the'

has
used

axac t ly the
as e Lt har

same
S

f

orm as a CHAR COnS
01': OJ II

tant ,

and such a cons
.

1:01at,

can be

CHlIll value
II

I:r~ ng vatue

file ill of ty:pf" nrreRACTIVE Lnat ea.d of TEXT,. the opellil1.p; RESET does!!£! perform a GET. 'the buffeT Viar1!l.ble 1s undefined 8:nd the file pointl!l- point: s to the f :1I:rs t ehar ac t e r of the f:Ue ins tead nf the. secofLd. There! O:rlll. a subaequeri t READor READLN has to beg:[:n its ope.ratio~ by fj,'rsi; pllrforn:lng a GET and chen taking the cnaract@t" that ",,<IS pl:;uoed -:In the buffer vae Leb Le by '~hg GET. T~!l5 is the l'!Ner.se of t.ha REJJl .s~quc_nce used with TEn 'fileI]

't cu cam not daf Lne In f't.lnct ions o[type

fune

t

STU

we

iOll

of
<IS

tYPI? STRHle. Hewe ve r , t: here des ~ ribed in the 11.'1,,),; t ch ap ter.

a 1:12 bll:U.ilt-

T.here :1.s one prilll<ll.7 r eas on f.or usLng the INTER1I.CTIVE type. If a fHe is not a d1s.kette filll: bur. :reprl!sE!llts 1) device 8uchas the keyboard, :it is not peas Lble to peTiroJrIll a G·~;'F it un t il a charl'ir:ter has been on typed. If RESET t'ded. to do a GEl'. the p:rr;,grarn would then go no hr t her until II char.ac t e r was typ ed .Wi til t11e INTERA.CTIVE type, the progr.am doeso't: pe rf urm B GET until it. is ex,ecLltill~ a R.EAD or READLN- The s can,dan:! predec lared fi les I_Npm" and OU'i"Pltr are INTI::RACnV~ files rep:resentine the cn!'l~oll" keyboard and screen; another predefined ftl,e called KEYBOARD Lse rep-resents a the keyboard {see the aect Lon below nn Predefined Piles)-

10 APPLE PASCAL LA.NGUAGf

PREDERNED TYPES 11

U'NlVPEID FIILES
In addt t Lon to the si:anda:rd

''untyped'' rILE and nothin8, mOl"tE!.
Pas('l!3!lal]_Cllws

[He' types and the files - objects tba.t. Exam'ple::

ItlTERACT[lliE
are

type,Apple

he,!lil.er. Whet! a user P.,B~<l-l progl:am accI!SiH~9,an existing tll'xtfile (via RESET) I;.he. s,ystelll skips the l:loi!nde:r. 10 other words" 'the header is invisiblE' to a uae r PascalpTogr<l.m using REWRl'lE and. RE.SET.

declal:'ed

with the. 'WOn:l

VAll. "F: FILE; files can only be BLOCKWRI'rE for high-speed

4,
functi,oJ'tB nlLOCKIU:.ADlltld

Untyped

used! With
da.ta

the built-in t.ral!l.sfe_t:&.

Whe.n a. progliaJll use.llIU.OGKREADand BLOCKWRITf Sj)eeial 'texi;tile s t ruc ruz e 1s D..QS:resp~,~ted.,
r;)~

to access'

fi.llits,:.

the

An untyped fHe' 'I" can be thought or as 11 file without a buffer va:r:lablll j:l-., All I/O eo thls lite mast. be accomplished by HLOCKREAI[) and BI..OGKW1U'TE. Th@se.runcrt:ions are d·[!scr1lbed ii'll the nex.t cb. p t.er , a

'['be sys tern will u:ansf ~J" the h.eadeI" en ly a dd ske t ce-to-dtskert:tE' t r~ms,f eel:". and wi 11 OtJi1it t Oil a t ra nsfer to a ae.rd.a.I devi.ce (thus t:nnB,fers. from dil'-kette [0 !l. 'prin'te'': Dr [0 the console will omit the header) • Following r;h~ header page, the te:!(t eOn.Cent it!lelf appea ra in 1~2.4-byte text pageS. I-:sch text page "iii a s£quen.ce of: line",. and the last line on a page is fq;dl<lwe'd by enough nlill ctul.:(i!cten (ASCIi ~~) 'to £ill out the l~2.4 bytes" A Un,e is defined B.S.
[DLI!: 1 nden t I [tex't

PRiEDEFINED FILES
The standar.d predeff.!l.ed. fi.las INPUt and OUTPUTref@;!: to the keyboard and 'the scree.n re!l,pect:.iv[!ly., III addd.t.Lon t.o thf!se. Appl!O!Pas.caI 'pro,vidll's a. pe adef Lned file caUed KEYBOARD. The difference bet .... en INPIJT and e KEYBOARD that when INPUT is usee! t.o refeJr to, the keyboard, is the i:y-ped ehacaecees are -Il:ucOl'IlaUcally displayed On. the screen; when KEYBOARD is uaed , the chaeaecees aTe not au tomat:lcaUy displayed., Thisal1ow!l B. Pascal program to have comp l.e t e control ave.]!: the. 'response to cbarac:tenl typed by the Liller. All rh:j:{!f! pred',ef:hl;e;d tiles are of type INTERACTIVE, and all three opaned vi~ RESET whell the Pascal:. program begin" are

I

CR t

whe'['e the br acke 1:5 indica te tha.t the DL~ and rh I" inden 8.bSe11'[ and 'thE' text its~il may be absent.
CR Ls th.e "Cal:1"iage

code

lIlay

be

automatically ex ...eu ti02"

R<ltur'n"co~u:al c.har.acte.r (ASCII 13). and may ba cabs:ent at the end of t.ne last H.ne in thE! file. OLE is the "Oa.ta Link Esc<'!pe" COI1't'Lol chaeae t e r (ASCII Hi). If pr,ee.ent it H followed. by a code iodiicating the. Lndent a t t en of thE! line. The. ·code is )Z + the number of s:pa.ce:s to inden.t. 'rhus any leading RpaEes on a Lfne <lire :j:~pl!!ced by t.he OLE ani! the. ind'ent I':cde, Th!! OLE and Lnden t, ~ode and thl! nulls a'~ 'the end ofa text par;e are, ilk!" the headar , invisible to <I P.a!l'caJL program. Th,!! DLE'. and indent lire aut craa.t Lca l.Ly trallsla ted to leading spacas , and \dee ve rsa.

TEXTFIIJES
The Appl~ Pascal .sys'tem pr ovd.de s r:n.a,[ a 'rt::XT or tN1ERAC1'lvt disk,ette f He that is cn"ated. with ",,'lEX,]:" Br,S:the l:;ist part at' its title has a spe.::!al int,ernal format. Such filers a.'1! called ""uxtflles" tnt.his manual. Do n,ot confuse teXl:.file.~ wtth files thll't are of type TEXT or IN'I'E·RA.CTIVE but do 'not. have !:itl£!s f!.l'taing, i.n "; TEXT" •
All parts of ttL@ Pas.::!!.l Sysce,l1I. that deo<l.l.wit:h files of charaeuer's (such as tha E!ditor) ar'll: .o:l!signed to UB1e t.he special te:;;tfile [OTiruJt; and if a textiil!:'! i,:;I acces:l@.d by a Pascal program, then the Pascal program will also use the speeia.ll. :Eo.mat. l'1J..eref'ore, 'the no:rmal pr ccedur e :[5 to USE' a 'tit: l.e ending .til ", 'fEXT" 'whell!!V'E'ryou cr ea te a df.ake t 1:13 H.l~ of che Pascal type TEXT or INTERACTIVE. The format: of a textfl1e is .lie
fCi,110WS~

At the be!1;:i.nn:!.11.8 of the Ule is a li)1:t<'I-byl:.e heade!" page, wh:ich cuntaf.ns inior-m.atiQn fOl: the use of t'ile t~xt editor. This spac~ is, respec'ced by all port:iolls of the sys.tem. When a user P,!lJscal program cr~~tes <I teKtfile (via REWRITE). the system will automaUcally ct"""'.ate' the

12

APPLE PASCAL LANGUAGE

PREDEfiNED fY'PES ,13

THE SIET TYPiES
APPLE Pascal supports all of the Standard Two limitations are i~posed on sets: A ser
,- .A ser
In<i.)' not

PA.CKED VARI ABLES
PBl5cal

constructs

for it. than

sets.

PACK AND UNPACK
assigned
to than

have more than, 512 elements have any' INTEG·Ells less to it. 32 ~ords

ilWy not

511 a.ssigned A sa
t

g' or greater

Apple PII!>Ca.1 does not require the Standard l'a.selll pr ccedur ae PACK and UNPACK, and rh es.e procedures are nnt ilTovided. If a variable is I'ACI<l:D, all required p.scking and unpa eking ;3, re d.one aut.ema t; i~1I Ll.y on an
e lement:-by-elemElnt basis.

of 512 e le1l1ent.s wj_11 occupy

of memory.

and operations on sets are allowed emly be'tw an sets whose individua.l e Lemant s are of the same type. For examn Le , in t'he sample ]l'cogram below, the bas,lI!! type of 'the set S is the subr ange ICype 11•• 49, while the. base It:ype of the se't It is the 8ybrange type 1 •• 1.011,. The ~nl'!et'l!.ying type of be hse'ts is the type mTEGER, so the compadsot1!i and cpe ra t tons OlJ [he sets Sand R in the foll{)1;<in,g program are legal: Cml!.p'8t"i.sOlHl

PACKED FILES
Apple Paaca L does not support PACKED FILE 'types. A PACKED FILE can be declared, but th~ data in thQ fil,~ wO 1 not actual ly be packed.

PROGRAM SET~OMPAREj
VAil S: R: S'ET flf' ,13 •• lt9;, SET OF l •• ~~~j

PACKED ARRAYS
The Ap'ple Pasc.al compf.Le r suppo r t.s PACKED ARRAYs as d(!:fined 1n Sta!id~rd

BEGIN S: ~ [Ill, 5, Hi, 15, 2~, 25, 31il.35,t.'~.,4 51 :. R:- [U.2'~.3\J.4~.51il,61il, 71ll,8Ql,,90'1;.
IF S = R TH~N WJtl'r EU! ( • • •• oop S ,••••
)

Pascal.

For example"

consider

the

following

declarations:

A: ARRAy[~ ••91 OF CHAR;
B: PACKED ARRAY [~ •• 9]

OF cHAR;

ELSE WRITE~N('aets work'); S := S -+ II. END.
In the foJLJLowil'lB example, the comparison 1" two set.:s arE! of h~o distinct undez Lyf.ng types. PROGRAMILLEG,ALSETS:
TnE STU'fJEl=(Z~O,O~<E,,1'WO); VAS. I: SET OF STlIF}': J: SET Of ~ ••

The az r ay A will occupy ten 16-bit words of melllory, with each elemenc of the array occupying Cine 'w'ord. The PACICED ARRAYB on the other hand wrill occupy a total of only 5 words, since each Iii-bit word contains two II-bit characters. Each element of B i8 8 bits Leng ,

.r

is

not

legal

since

tb",

PA,CK.EDARJU,Ys, need

nat

be r eat.r Lc t.eo to arrays

oE type

CHAR.

Fol':

e xa: liiP Ie.'; C'; PACKED .IIJUlAynJ •• ll OF ~ •• j; PACKED ARRAY,[L.9] OF SET OF r;I •• 15; D2:: PACKED ARRA'{[\Il, •• 239,1!l .. 3191 OF BOOLEAN;
D;

2:

BEGIN
I: = [ZER:O]; J;- n.21i IF I - J :mEN

END.

««

error

here

Each element of the PACK£!)tJ1..RAY is ooly 2 'bits long; since C only 2 b1lt:s are needed to represent th,e values in the range ~ •• 3,. Therefore C occupies only one. iii-bit 'word of memory, and 12 of the bits in that word are unused. The PACKED ARRAYD is a 9""Word ar ray , s Lnce each el@ment of D is a SET .... bieb can ge represented in a minimum of Iii bits. Each elernHnt of a PACKED ARRAYOF BOOLEAN, such as D2 in th~ above example, occupies only one bit.

14 APPLE PASCAL LANGUAGE

PREDEFINED lYPES

15

~I

Th@ details mo.si; a'.ases,

word

(two BlTS;

of C'xa~·tly ho... variahles ,,~@ packed are Uflllljj~cifJl!!.d. the. 1ll1T1:!.rnuln o:psl:'e tn to ~ 1c~~ an array can be packedi!;l e1gh t-b1t byt es) •. Fell: eX!li1lIpl·e. c.o(lsider

In
One

be packad i r the I:ype ·of each ele.ment. of the arTilY 01: .!I 51'" and each "rray t elemen t: c@n be repre5en ted b~ S bitB or fewer. For an ar ray ...hose ell"'llIent:!l a.r e s,ets. til il;l DEanS ·~bB.t the underlyl.n,g t:J'pe of the Set; mtls.t no t cotl.t:a.inmore than a e iEmeuts. and !Jll!.!! t not contain any integer gr ea r er dum 255. l'"e arl'ay Irlll only it:]. :llca.Lar, 8ubrange, The following decla:rationwill the fin.sI typ,e nf the a:tray rcsu l.e in ~o packing ilfhjj·tso.evl:'r becauae cannet; be repr:f!se.fll:ed i]] a field nf 8 "l'>1'Hi:

PACKED MAAY[~ •• 7) OF BOOLEAN;

Tllis Ls au ei.ghl:-de:me·nt. OI!l'l.'Bywhe:c:e aaeh ·e.lement: requires one. bit, so ym) migh t ,ex.pect: it to occupy eight bits or one byte. In fact, it ocelJpte~ on.>! word Oit' two by·tees. Fur the l:1!lo're, the two-dimefl9ional m:'r-IlY
BATS;I'iACKED ARRAY [~ •• 3J OFPACKEU A!lMY [11•• 71 OF .1I00LE.AN;

G will Note

be an attaywhich

o(:(:upies

four

16-b1t

won!.s ..

or
BAT S :

its

l!'Cluivalent

tl!at a SUing constant may be asSigUl""d to a. [iACKEJ)ARRAYOF CHAR (:ILf it has exactly the aame le.ngch I, but not to 3r1 !.Inp<l:~ked ARRAY OF CHAR.. L1kelOise ,cQlIIP'aTlsoo.!I I:mtwe en. an ARRAY Of' CRAR .anill II. s~lfif18
CO!1StOlO't

PACKED ARRAY [ (;J •• 3, ~ •.• 71 OF BO01EA.."l'; array ,

are illegal.

cons Ls t s of

occupies

f cu r an:ays. Each of them. Uk'! t:he pr,,",vioYtl DTI{l' word. Iher·efo];€: SATS occupies four '>Iotds.

Because ordinary

of their d:tl:ffe1:ent unpacked ARRAYs.

sizes, PACI<:ED ARRAYs cannot
eue 1oI.i tb a single

he coiTIp.ar<l:O to wrir:e s t at.emeut;

'!>late tlla t 4 PACKED IUUV.Y OF Cl:ll!Jl a twa)'s occup Les one by t e pelt ehc es e t er .and a PACKED ARRAY OF C!., 255 always OCCUpill:8 OUf! by to! pel.' elemen!;.

A 1'1ICKEDARMY OF GIlAR .may bl! printed (exac I:ly!l:s if it !Uerf! a !'l t r i[lg) :

Also"p.~cking never occurs across r"Tord bounda 1::1es. This realls t:hll.t if the type of element to be pa cke.d requires II number of b.l.ts which does not divide· evenly into 16 ,t.he·[·e will be. sOllie unused bite In. each of the "'Qr~ where the aTl\ay is stored. The foll.Qwingtwo dE!clan,tion8 are 1'<01" qt.livalent e PascBl GOIDp11er is implemented;
E:PACKED ARRAY [Q". 9) F:: PAC](.ED ARRAY [g... 9, I!'I the! d-ea'.lat"ation because

PROGlU!M WR'iSLI<CK;
VAIl"r, BEGr:tl PAGKEDARRA'i(~ ••
T::"-RELLO THERE'; WIlIT£LN (,T} ii;ND.

r!l'~

OF CHAR;

of the

'Way the

If! ••

OF ARRAY [~, .3] 3] OF CIiAR;

OF GHAR1

PACKED RECORDS
The. follo ....ng RECORD declO1t'8t ion dccla.res i a RECORDwith four f 1.elds. The. e:nt:1re ItiB.CORD uceup Laa one l6-b1C "lord as a resull; of declaring it
~obe a PACI<£[l RECORD. VAR R: :F'ACKRD RECORD

(If E, thl? seeo!'ld OCCUT]rIH1C12 of i:hl:' re se rvad w:ord ARRAY causes the packing opt :fiA:m iii. the compiler t:o be turned on·, 'Ii: be['o!!lE.s (lI.O unpa~ked 3rray of 4~ word.s. On thl" ot.har hand, the PAcCKED AI!.RA~F Ot.'cupI.ea cnl,. 2Q words because the rese:rved word ARRAYoccur·s only once in the dee:iarBUtHh If E: is dec Lar ad 48
E;

PACKED ~AY

(~ .. , 9)

OF PAC!{f;D ARRAY [~ •• 3]

OF C1lM.;

I, J,K: 1'•. 31: B; BOOLEAN

ENn;
Th", '1ariabh.5 valfiable :B is In IWc~~he
I, J, K each .. lloel! ted to
lOO.fine::it"

or as
E; ARRAYlijll .... 9) OF PACKf:D AARAY[r;I •• 3]

take

up

f!ve

bits

in

the
S.!J.me:

word.

The

'bDDlean

OF CliAR;

the 16th

bit

of the

'oi'ord,

F and

E

will

have identical

confLgtIT.<I'tioQS.

same

that

J'II.C~D ARAAYs c'!m 'be mul t idimens Lona L

In dechring <i PACKED ARRAY. tll~ wo-rd PACKED is only_arn.io.gful before t;h~ last a'ppj;!_aranc~ at the w'o"!"dARItA.I i.n till'" d.eclar.at.im,. When in dcubr , a good rule. of thumb for ded_<l'l"fng al!JJltidi!!!~Il.!3i(lna.l PACKED ARRAY 1s 1:0 ·pla.cet'he word PACKED' befoJt"e every appearallcf!. ~.f the wordi

PACKED MlRA:ts, ],'ACKEDR.ECO!Ul<S may .:;ontain fields which themselves ~:re l'i\,CKED RE'.CCIUlS or PJl.CJ{ED ARRAYS. Ag,",in, Slight differ-em::!:"", in the way i'n .... ch declarations hf are made will aff<2U the deg:ree of packing

ARRAY 1:0 ensure

that:

the

!lr1?6l1Jltat!lt

ar ray will

be PACKE'D.

16

APPLE PASCAL LANGUAGE

PREDEfiNED TVPi:S 17

achieved,.
equfva Lerrt ':

For

example,

note

t.ha t

the

following

t'Wo decb,'rations

a.ee not

THE ILOING INTEGER TYPE
In Apple

VAR. A:'l'ACKEU RECORD C:INTEGE.Ri F:PACKED RECORD

VAR ~:PACKED RECORD
C:INTEGER; (":RIECORI)

attr:I..l!mte.

Pascal, as in

the pre.defined the follow1ng

INTEGER examples:

type

can

be 1lIOd1fied by

a length

R: CAAIt:
It: BOO'LEAN

R:CHAR:
K::1l00LEAN it: PACKED

tYPE 1HGN!i}1 = llITE:GElt {12J ; VAR FATS: lNTEGER [25]; This defines BIGNUM as a. type which can have any integer value requi.ri.ng 12 decimal digits. FATS can have any integer value not DIlt'S than 25 digin::!h Tt1~ length, at t.r Ibute can bl! any INTEGEB constant up to and includirng 36.

END;
H:PACKED ARRAY [~ •• 1]1 OF CHAR

END:

ARRAY[til •• J] OF CHAR

END;
~a ~1th PACKED ARRAYB, the word PAcKEO should appear with every nccur-r anca of the. word RECORD in ordel' for the PACKEtl RECORD to retaill Hs packed! q~aUties throughout. aU fields of the RECORD. In the above example, only RECORD A has all of its fields packed into one word. 11'1 B. the F field! is not packed and therefore occupies e;w.c, L6-bi't words. It is i1!!Portall~ to note that a packed or unpacked ARRAY 01:' RECORD Which Is a field of a PACKE'1l kECORD will a lweys st ar't at; the beginning of the next word bOUJld.,n'" This means that In the case of A" even though the F field does no t camp J.e tely fill one word, the ~l field at ar t.s at the beginning of the 'next ward bounda rj-; variant may be used as the las r field 0'[ a PACKED RECORD" and the amount of space alloc.~.ted to 11: '01:1.11 be the size of the tr>rg@:l;it var tant "!!long the var Lcus cases. The. actual natu:!,"e of the packing is beyond the scope of this document.

nor more than
1'~quir'in!!

ullsigned
lhis is manual.

a new kind of type, which is called a LONG INTEGER in this The LONG INTEGER is suitable fOT bus 1.ness, scientific or other applications t.!hlch nee d ext ended number lengths wi th coep Le ce ae cu racy. A LONG IN'IEGER. is t'epresented int,ernally as a binary-coded dec:l.!nal ,(BCD) number; t.hat Ls , ea,c.h decimal digit of thE! value is repr e seut ed iTl binary. This liIei!LilS that the:re can be no r ound.i.ng errors in wor~ing with LONG INTEGER values. LONG INTEGER constants, are aLs o allowed. Any intgge~ cmlstan'~ whose v.uue exceed!! HltXTNT ie ..u t oma tically a cons tall t of' the tY1;Je LONG INTEGER. The integer'a:rnhme~ic operations (+, ~. *, and I:ltV) 'can all be Ilsed wHh LONG INTEGER values. He .... ve r , HOD cannot e be used l-nth LONG INTEGERs. In inte~et: arithemet1c. Dverflow occurs if any i.nterr.1ediata e r final result: r,equires more 'than ~!'. decimal digits. lJhen a LONG INTE,GER value is ass Lgned to a LONG INTEGER variable, over-How occurs if the valul!' reqUires more ded,pal digits chan the dcf Lned lenll!;;h of the variable.

A. case

VAR K:

PACKED RECORD

B 1 BOQ'LEAN

j,

CASE F: BOOLEAN OF TRUE: (Z:INTBGER)j
FALSE: (I: PACKF:D ARRAY[r,J .• 3) OF CHAR)

END;
above el!:alllPle th.e 1'1 and F fields are s~o.ed in two bits of the l6-:b1 t 'Word of the recm::d. -("II1l rema:1i11ngEcuT teen bi rs are '!lot usedTh e size of t'he r:ase variant fi,eld is al .... ys the si~e a of tbe La rgee t Variant, so i1'l the above example, the case variant field will occupy two words. Tb\ls thu entire PACKED R.ECORDwill occupy three words. In the
t

An INTEGER value

f:n. rs

can always be ass1ened [0 s LONG INTeGER variable; it is au tom~t.l.c:al..ly COllver ted co the appr op r La t e length. Howevcr. a LONG INT])t;ER vaJl.ue cat! neve.r be assigned to an INTEGER va:r:lable. If iNTEGER a nd L~),!<lG INTEGER. vaJ.ues are mi.-xed ip au expression, the INTEG~fl ",.. lues are. converted til tONG INTECER and the result is a LO:iG INTE)G)';]1. value. LONG INTBGERs Bud REALs ar e in C01llPatI.b Le ; thC!)' can navar be mixed iII .!1Il

a,rithllle't:i.c

expression

or as s f.gnad

to each

othermay be used

All of the standard r'eiational INTEGER and INtEGeR values.

operators

wi tb. nii.xed LONG

USING PACKED VARIABLES AS PARAMETERS
No PACKE.D v~riable may be passed as a VAfr.(call-by-reJer:ilflce 1:0 a PROCEDURE or F1lNCTION. !.lacked variables may, how,evel:. oTdinary c~ll-'bY'-v"31ue pal:ameters .• l para:rnete1:' be pSf;sed n

The built-in procedure STR accepts a LONG I~'l'EGER. value as a parameter, and conve r cs 1 to a string DE decimal digits. The built-in functi.on TRUNC accepts ~ LONG tNTEG~R value as a pB~amete1:'. and ~eturns the . correspond1ng lNTF.Cr.R va Iue if the abs o Lue e va Lue of the LONG INT.EGER is :less 'than Dr equa I to MAXINT. 'J:he,ll,e buf.Lr=Lna IiU'Il' descr tbcd in the next: ch<l[)ter; I:'hey are I:he only buile-ins wl\:ich accept LONG INTEGER

parameteTs.

18

APPLE PASCAL LANGUAGE

PREDEFINED lYPES 19

An :B.ttempt to d",~brea LONGIN'TEG~R iLn,a pazamet.e e list will reSult in a syntax error. This rea!:;l:ictic;rn rna,,!,be Ci:rC.uiilVi'mted by defining a tll"pe whi.ch Is a LONG INTSCER. For £!X<lWFlle:
TYPE LONGE INTEGER! 18]
j

PR:OCE!l1JRE :51 GNUMBER (BANKACCI : LOIlG):

;;tAR,

L ': IN1'EGE.R I;, (wh(!re IN 11.,; REALi I;.,. L
{synt!lK

I: INl'EGEll;

N ia, lin Lnege.r

coaar ant; .;'" 36 }
C<lt1be

.errOi'j t he !RUNC function LONG INTEGER to an INTEGER) L: "'~L {c:orrect.. if ~L does not r,equlre

used to CQmrer't a

IMr€;

than 36 d1,g:i.t5j the

Lo_ L;-

EGiIH!S

s:fi.grl dcasn " t:

COllI]

I: as a digit}

I {al~ay5 cC:l'rrec.t) R {never 8c~epted)

R;" L {never 'l'h~ marnn:ry space number of words.
(n

acccapted} allocated foli' a LONG INTEGER ts ,always an int.@gra,!_ 5peeificglly. a variable of type INIEGE.Il;[n 'ftt:~upi",s J

+ 3} DIll 4 +~

words. Therefore. the actual limit on the value of a: LONG INTR.GE.R !!IA}" exceed the nU!lIber of decilll8.1 digits specified i!.ll i.1i:5 decla.ration" For omamplo, a Length of .5 thrQugh 8 occupies t:hree~o:rd9 and. can !ltorevnlu,e.s up to lind including 99999999. B. bngth of ~ through i 2. occupies four words and earl S!:ore v,allJes up, through 999999999999: II length of 13 t hrough 16 ceeupaes five 'Word!! and CBn B tore values up tb.rough 999999999'9999999.

:20 APPLE PASCAL LANGUAGE

This chap t e r descdbes all the 'ou,LiLt-in procedurres and func~loM of Apple Pascs I that d:1:Ue:!:.from Stand.ard Pascal. Th:ts doe5not indUd", ;he procedure:.s and functions ~ila t ,are. ptovidB.d as H b r s ry UNITs. e. g ~ the grap1l1c5, pro~edure6 and fum::tions. Chap t:t!.l' i cove r s the libra ry [lin!!! provided w:H.h. ApplePasCBJ..
TraliSCendenta 1 funet:[onB (~. Ii! '. the trig func t::!.ons SIN, cos" etc.)1 a.rea !lp,".cial case" III S'tandard 'Pascal they ar e lm:Ut-in functions" but tn Apple. Pilililcal t.hey ,ar" in a libury llNIT. The ATAN and LOG functions cliffe!" slightly [roil! StandardP,asc.aJ.; a~dthey are described in this

'lHE

pas

FUNCTION
t t on

Tn!! pos Iune

rat urns SiRe)

all

integer

vallie"

The form is

POS (5UBSTRG,

where both SUB,s-rRG and STRG r.o B[ln the first

S1'RC aCE st1:1ns V6.l!.H~S, The occu e rence of 5UHS'I'RG within

pas

func eLnn aca ne ST.RC. PO:; rat urna
t e rn

dual?ter. Cha~ter 7,.

The other

~ran!icendent:alsdif:fe"[

only

in that
as

p rogr a III mull t inc:lll,dta B, USES TRJ.NS'CENJ) s tat:eme.nt

described

to ~:me them. in

YOUI'

the the

index ..n_thin BTRGof the first chabact~r in the [[Bt.cl1e.c!pat p.~.tr e rn 1.5 not . Eouud , POS r~~U1:ns ze r n» tKBmple:

.

If

STUn' := 'TAitt TH.E. IlOTTLE WITH A METAL CAP':
PAl'TERN ; = 'TAL': WIUTELN ( ros (PATTERN, This will print: ST1.!Pt',)

I

~i

Since rang!! 're.sul such

!lolDe. Df tl:U:!n:: bU.1.it-ln procedures and :fIJ,ll.c,tlQns do no checking for ·..alldtcy of 'parameters, they may easily cause unpt@d.:h:ca.ble ts. Those built ~1.!lS wh Ich are p~rtiC:l!la:r!.ly da.nge.rolJs: ,SJre nQu!d as :t.n the! r des~ rip,t 1.ClOS • Any neceBaary range or validity checks !l.re Four responsibility.

26

11

I

'THECONCAT FUNCTION
The CONCAT function GONCA!
J:et-tIl:n5
ill

string

value.

The form is,

S1RING B'UIIIL1 ..INS
I" thefDllowiD8 d,e:scripticllll" a Us t ring value" lIIeans Be at ring a qucte.d scting, or ~n)' function oc exp'['e!lsion ~hcse value Ls Unless (l,thel.'Wi:!l@ 9t;·!lI;.~d aU. pa:tarcec@u are. c~Ued by value. wu:iable., !lJ .'I'trinE'

< SIRGs

~
J

where SIRGs maana Blly number [If 5 rr tng values separ s ted by c:omwas" Th1~ function ret;url'ts a s tr Lng wl1Jth 1s the concatenB[icn of a 1]. t:he sn:1ngs p~sBod to fr. EXBIDple:
SHORTSTRING ;. 'THIS IS A STUNG'; LONGSTRING := 'THIS LS A VERY' .LONG Sl'RlNG,'; LONGSTRING: : = CaNeAT ('START '. SHORTSIRlNO,' WII.ITEUI (l.ONGSTR;(I>lG)

[3
lHIE LENG1H FUNCTION
lll..e LENGTH iEunctiC:l1l returnS Il,tring. The. form is,
I...FJlGTtI (STRG}

J~
~h€ integer va Lua of the
.h!l1!!t:h

,LQNGSU.ING)

;

of

Ii

]

I~
J
• LENGTH{" l)

START THIS IS A STRING-THIS

IS A VERY LONG STRING.

f~

GEESTRHlG

;'" '12345,61': WRITELN( (L..E~GT1l: (GEES1'RINC).

-

T]!]i.!imIl

pdnt:

22

APPLE PASCAL LANGUAGE

BlJl[f·IN PROCEDURESAND FUNCTIONS

23

THE COpy fUNCTION
COpy (STRG. INDEX, COUNT)

niE INSERT PiROCEDURE
the 1s UlSERT (SUllStRG, STRG, INDEX)

mSERT :procedu~e

mDdifiea

the

value

of

03.string

va.riable.,

The

[Oml

where STRG1s a strinE values. This fum~tfon

copied

frol!1 STRG ~tart

va.lue and bntb lNUEX .w.d COUNTare integeI: returns a 6tr1.ng cont.a Indrrg COUNT c.!laracte.s iIl.g ae t::he INDEXth p05it.il:m in SIRe. Example:

where SUB5TRG :Is
reference, and

,<I st r Lng valLle. ,STRG is a !ll:ring variable called by INDEX is an intl!geT value. Ttli'!> inserts SUJI.$TRG into

TL : = 'KEEl"' SOMEfHING HERE': KEPT ;= COI'Y(TL, PQS('S'. TL),
h'RlTELH (KEI"'T

S'rRG ,H[he
9);

UfDExtl1 podtion

in STRG.

EK8.tople:

I

This

will

print.:

SOMETHING This

1D := 'l~SERTIONS'; HORE r= • DEMONSTRAU'; DELEU (HORE, l.ENGTII (MOR E ). INSE;RT(tlORI!:, !D, POS('10', WRlnLN(ID)
w.:ill pr Lnt : INSERT DEHONSTRATlONS

1.1:

IDll,

THE DELETE PROCEDURE
The DELE'.!'E pro·cedure is O&LE"T.E(STRG. ilDdif Las

tIle value

of

a sl; Tins vs dahle.

The

.form

THE STR PROCEDURE
The STR procedure modifies the value Qf a G~ring variable. The form .is
PROGElJURE STR ( LONG , STRG ) wh'fl.re "LO~G is an 1n!;~ger r III er ene e • LONG may be

[NDEX,

COUNT)

t~bere STRG is a sning ·,rar.iahIe ~al1ed by re Ee r ence and lfOaified, and both HlD:EX and COUNT B I"e i~ tc~cr values. Th is pt"oc'edure~emoV€.e; COUNT char-ae c ars f r'om S:r~G g[ar~in& at the INDEX spec1f :led. Example: OVERSTtlFr-'"E;O :" 'THIS OELE.TB (mrE.RSTUf feD. W!Un:UI (OVERSTUFFED
STRrKG

1

PGS {'HAS

HAS FAil TOO UANY C;RlIRACTF.RS r" OVE~.s'ItrFFED)+:l. 13):

IN

U.';

value. and SIRG is a string a LONG INT.EGRR.

var1abl~

ca l Led by

This corwe r [9 [he va Iue ,of LONG into !l: S trillg. phce<l in STRG. See Chapter 2 for IlUl:e abou~

The ["~sull: ing 8 tring is ~he us~ !LIf WNG INTEGERs.

Example:
TKIS STRING HAS !1J\.NY CHAMCTE!\S 1N [T.

INTLONG := 1~2~395~3;
STR (IN.LON"G,, INT STRING) ; INSERT INTSTRING. LENG'fH (INTS'FfUNC) W~tTEL~('$·.INTETRINC)

r' .'.

- [);

This will

print;

Ttle

fc 11owing

prDgraln

seglllEntwill

'provide

8. suitable

dolls rand

eent

I"Du~i.ne:
STR(L,S); IN5F.:Rf{'.' ,S,LENGT1HS)-L)i, WRITELN~S)

:24

APPLE PASCAL LANGUAGE

BUILT-IN Pl<OCEDURES AND FUNCTIONS

25

INPUT AND OUTPUT BUILl-INS
OVERVIEW OF APPLE PASCALI /0 FACILITIES
t_'

This (:ec I:1 Oil dea Ls r.ri t.h dB La trans fers to and .hom a 11 periphera 1 devi~es, :i.m::ludlng disk.etl:.e drives, t.ha screen, '~he keyboard p""1' t Th 1 ,. . ..' , •n

eauaes tile operating ::;y~tem to c r eat e a di:rectil.Y entry Eo!" the file. If REWRITE is used with ~he tlt.le of an existio, fil~, th[;' ~xistiTIE file f.s deat r oyed and i) ,.,ew directory entry Ls cr ea ted . P.t:SET is u se d to Opl! 1'1 8.Il el":i" tillg f!leo and ca n al So be used to move t he f 1101 I'oi nt e r ba ck eo the beginning of a file that Ls already o periA CLOSEproc:~dLll;-'" Ls al ao p:nwided. It of f e rs several options for the d.!spns1.t1on iilI tJ.~ file IOheo the pro~ra1:l is t hr ough usi ng it.
Elrs.

e ~,' ere are a s~ certailJ 'integl:a! rI devices auch aa the TIL game. ~on ere 1 , C!1.1 tpu t~ and the boil t+Ln apaaker , wh:l.ch <lFe no t considered Il:!l, 1/0 dev1~es; S(l.il! Chapter 1. Por compl,ete information On Apple l'ast!al f He '~'ype!l, 5Be o..apH!1; 2,.

If

t ercrf

Ls 'uns'LLcce:;laful" t.he ope t at Lng syl!ltl!J'1 will norms l Ly execut tonHowever, there iii. a compile. i:lpti('lr1 re df 811b Ie th i'6 fea tu'r e , The 1011£5ULT f unc r Lrm allows the progr;:Im Lt se Lf a n I/O operation
progralll

ne t e

to

cha ck on

the

s ta

[U

s of

t he

mos

t

recent

1/0

ope rat: 1011 and

t.ake

.app ropti

.. t e act ion.

hpp It! Paseal I/a different levels: -

f acd.H rt:ies can b~ though

t

of

as

exf s tin!l

iU

fou.r

Ha.dware-ori~[!lted 1/.0: the procedures are the low@s[ E'aseal progr<lm to ~ra(l6f~1: by tee betWLlen melllOt')! and a filelu;lIle:s, dl Tecto.ieG, et Dnd (fer diskette drive,s)

1JNITREAD, UN! 'fWR ITE. and UNItCLEAR liWel of controL They allQW 3, Ii .E;peci:Hed numhe r of l:onsecu'cive device. They a r a no t cont r o LLe d by ~.. oor mar e Ly use dav1e,e numhe ra block numbers"

THE REWRITE PROCEDURE
This prQcedu r e c caa t es .. ne". file andll'arJ.:s th~ erxplain!':d below, it ca n also be uaerl to ope n au
f LLe :95 open. A.. exlst:1ng f LLe , ThE'

form is PEWRlt£ (
FILEID ,

,1tiE )
and TlTI,E

.- UntYlle.c fUe I/O: The l!LoCkREAD and Bl.OCKWRITE fUncti.ouB provide I/O :f01" untyped files (see Cnapte':l" 2)" 1hl;;Y make USe of filetlames and directories 'but consider a file [0 be' me~ely a sequence of bytes -- not a ser,plf'n~e 01' re cor-ds ef s ~articulaI type. Typed file 1/0: The GET. PUT. and :H:EK pnll~edurl'!;S t.rea r II file a,s a, ~eq uence (if l:e~Ords. GET and PUT pt cv i~e tr'ansf !':rs be tween tnd1vido,tll.l file recm::ds and ~b,! file" ~ buff e!: v~r1ab ie. and S.EEK moves the ped nt e r to a sp!"C:JLE :ted record Inth.in 'che file. The. EOF Eune e Lun provides an Ind l cat i.nn of "'hen ~hE! end (if ~l1e f.ile. has buen rea ehedText file I/O: 1'he RliAD, REAIl!..N, ~ITg,. ani! 1ilRITB.LN procedures p rnvf.de transfers. between a file of type TEXT Of" INTf:RACTUE and pTogrraJQ V-'l;ria.bllOs. The PACE procedLlrE! writes II top +cf -form cent ro l, cha ra crar- int.~ !l. cex t f l1e. The fJOLN f unc t:l on prov1d,es an indication of when I:.he end of a tel<t l111E! has been r.eachet:!. '[his is the hig!;~~l level of I/O cuntrol. w1 th many sop,his t iea.t ed 'f.~al:ures.

wh!.lre FlLEID is dB" tdenrifier of a p r cv Lou s l y d.ecl;aredfile, is i'I Hdng cnnr ainln!:; any lil gal file t Lt l e .

If the device J!lpe~ified Ln the-'t1TLE is not a qhke[:l:~, then the file openad for bot b input and out.p ur , If the TITLE indic.ateS a dl.ske[t<>: fLLe , RE:,,'RI1E: CTeati$ a neW fll~ and opens it [or input and O\itpll~.

is

Ii the file

is already
ope n. ~l1owing tne of GET an~

ope n , an

I/O

e r ro r occe rs

(se~

IOltESUL,

bel(l~')"

:!II

'['he

file

relnl3i ns

An el'lample des'~Tip'tio[l

~se l'tiT

of !<EWRITE in a prDgran beloW.

1011(1\.9

the

-

THE RESET PROCEDURE

A.,. meo.c:l.oned in CiJ.ll.pte.l' 2 ,the INPUT. OUTPUT. and KEYBOARD file.'! IHe p n:def ined and need no t be declared irl a prograllh All othe r HIes IIIJSt f irs ~ be dec.La (ed in the VAR sec 1:10111of a pT~graJT1" and rnus t then be opened by means of RESET t'H' REWfl:.I1'Ebe fore [hey c.an he used in anyway. Opening a file is a means of asso!:'i:. t 1118 til e flIe's Ldent irier i n ~he p !:or, ram) wi·th i [8 tttle (used by the ope ear.Lng system.), f fle I~O be used does not a] ready ens t. open 1 t with RE!J1UTE.; "declarecl U ~he t 111s

I _!I
I

1"-

This pro r::edure opens The.H! are ~W!l f OTIIlS
RES:ET

an ex Ls tinr.
:

f Ll.e f 0 r bot h l'e.~d i ng and

wr! t Lng ,

L3
I
I
I I~

RESET !.ihere
1.8 [f
UtI:'

FlLEW FlLt:tJ:J

, TITLE

)

rILrID

is thE' identifier
~.Il)'

of

a s t r tng c onr a tn Lng

LegaI Ei1e

~ previously t i r tc-

declaTed

fLLe,

end

TITLE

I
I

m:r.I.!TS

a TIIL.F Is used and t he specif ted f l1e is a l r eady ope 11, an I/O .. r rur (s~e lOR [SO LT. be 1 ow 1 • The f i Le '" s t a te rel1l:cl i ~B U ncha ngod • 1£ file doeA not: exis c, anI /0 error: o cell lfS •

26

APPLEPASCAl. LANGUAGE

J

I ..

BUILT~INPROCEDURES AND FUNCTIONS

27

A Rf;SET wi t!JIH.l1:: th E! rrn,e can anI)' be used on un open filE!; is !'Ii'rnply to reposition t~e file palnte'r as 11 the fUe had opuned , I.f the file CET aC[ioD

th(!
jtl.!lt

e.ftect beEn

[f

~he OPTION 15 omitted"

~hi:! NORUAL close op[iolJ will mark

1::. perfo.med.. ~he file: closed and 101111 CLOSE 00 B CLOSEd ftb

AlLl CLOSEs rug a rd Iesa of the make the HIe buff e r variable
CB.USO!tS tlO

FI'LJ:Hl~L:mdefine~..
GLOSE: i~

Is not of type INTERACTIVE. RESET au toma i;:lcally perfQ:rIllE e -- that i~. it loads the first recaEd of the file t~to the fl1,,'9 buf faz variable and adV<lncell the fll.'E pointer to the second re 1::0 rd. If the file is INTERACTIVE, no GET is pe:tl~ulllEd; the buffer v·sria1'lle·.s value is undef im~d and t he file pointer poi nr sto the first re cor.d., \C~t Is desc rib!!d f ur·t ner an.l ,,"01:,1' thB t RESETting a non-DHERA{',if. \IE Ii l·~ tD ;a fI OIJt.pm.-onl. y devtc:e, such RS PRINTE.R:, may call se B run-~.ime Err-or as a res 1.11 of thl" t au.t oma t.Le GET caused' by the RESET. When zm exist only 1;.11,,· £ lIe An exawple of C,ET and in!! f 11,11' 15 op!:med lo1i~h R[SET and 1 s t.he n used rE[: o rds Bet ua Ll y j.;r!:i t t en to are af f,1'ct ed • use of RESET in for ou tput ,

act ion.
use of
<I

An ex amp Ie showiIlg the of GET am! p'UT oelClW.

progl".arn

f ,,110,..3

the

descr1p

t Len

THE EOF FUNCnON
Th.is f un c t Lo n re tu rns a BOOl.EAN value to lndlci3t~ whet.her the end of a speC'i f fed f i Le has been .each ed • Wh!".n EOF i 5 true. not h Lng meH: ca n be

read

frOID

the

Ul,r<;.

The form is

EOF ( ( FILFID ) J
deg~t'lptio.n

showing the PUT below.

aprograrn

follows

the

If (F1LEln) 1s not
EOF is f He.

pTes~nt.

lNEDT

is

assu~ecl.
on a closed

TIt1ECLOSE PROCEDURE
This. prClcedure closes RE!.'RITE. The form is CLOSE' FILElD ['0
II

fel~e 'immediately sf t e r the file is (Opened, and t rue \lhenevel: F:Of (f11.F;!D) is true. FILFn)~ i 5 lind ef Lned,

Eile

'Wh"i{~1 WB.'!

]Jrevio~"ly

opened

with

RESET or

Ai te r 8 GEt, 'EOF La true if c.he e'Er a.[te!"lpt:eo t.o ac.ces s a t'eco)"d after the end of t he file. AI te-r a PilT or ~IRIT[, EDr 11': tl'ue H file cannot; be expanded t n <lccornIoodatE' the PUT or WilJ'n: (bccau se limitoo d:fi_s~ tt.e space, e fOI" exampl!!). Fe r de UllI 5· on BOT- af t e r des c r Ip r iO!1.B of RI'1ID and Appen.dix c. a READ oTIH':AJ)tN opera ti.a n , se e the R:s...'DLtl f u I: the. 0111 1 nthis chap te I'. and

t.hllt the of

is

OPTION] of : a pT~'###BOT_TEXT###quot;io!Jsly dec Iar ed file
0

whi::!re. fILE!!) is t.he ident1fieT may be lilly one of the E' ollnwing

and

OPTION

NORt1AL -- a 11oI1l1031 clOSE is dnna , 1 ..e. CL05I simply se r s thO!l f i1 e state to c lClseil.. If the fil·e Io'a:< opuuad 11 ~ in,g~ E'k'RITE and is a ~lsk file, it is d~let~d fEom the djrectory. LOCI( -- t he file 1;; lIlade'perrnanent; in the direNory if t he fHe i~ on a disk and the fHE' .... as opened ,.,f·rh a R£l..TRITE; othe""i~e a NORMAL e Lcso ;I.. don·!'.. If t he 'I'ITLE Jll(ltc'~es an ex I s t Lng dIlsket[>l fIle, the origll1al contents of rbe t'ile are
105

Wnenl':OY beco",es true dudIlI!, f'1L.'fID~ is !lot clef; ned. When kel"lwa rd Lnp ut is he tn,g

a ~fAD or

rjj:T

ol'eratio[l,

ULI" vs Lua of

r ead
tr

KEYDOARD) .EOf

only becDl'l~£

uc

""hEn

r;:ypi::!cl. The ~!ld-[lf-fili::! character unti I tne file. INPUT OI' KEYBOAPD can m, r end unr iJn: his is dorn1I[] example :;;ha'Mii'lg the GET and PUTfuelow .•

til!' P r ede f 111.. d f1l e~ INP'[;T or tI,e eod-of-f iJ O! CltBHICt er 1s is ct:rl~C (ASCII 3)_ EOF remain» rrue is RI:SE.f, and no TIC!:"E typed Cn;3T<lct~rs

(-{ia

t .•

PURGE -- if the fU e is a disket te file, 1 t is de]c!2 ted from thp directory. In the specl.1l1 Cll5~ of a diskette file that already exists and Ls openpd 'l'ith Il.D'l1In;, che original f Ll.e 1I'P'maJins if!. the d Lr cet c ry , un ch angad , If ~he file is not a dt.sk et r e file,. t he 2ssllcia~ed unit w:il1 ~o off~1.:Iine. CRUNOJ "his 15 likQ. l.OC;!(except that it. Ie cks ths end-of-fil~ to the point of Laat "C~"5~, i0l1o e

E'ry[j,i'~g After the 1£1 t element a at: ces aed is thrown awa.,. If t hs TITLE tna tche8 an ex is t in,e diske t t e file, the 0 riEl L1<I1 c cnr en.~~ of th~ fIle aTe lo~t-

or

use

ot

EOF ln

a program

fol10'0'5

tll ... de s e r Ip t Io n

28, APPLE PASCAL LANGUAGE

BUlLTIN PROCEDURESAND ~UNCTIONS

29

TIrlE EOLIN FUNCTION
EOLN is dLlEingd Dilly for a file of Lype TEXT,. I'llE OF CHAR or INTERACTIVE. Th.is function returns a BOO·LEMI value tel 1nd; cl"lte the poi.nt.El.r .for a sp e c Hi ~d telu:: fIle 1:; at the end o[ a 11n~ " :ham· J5 EOLN ( Fll.EIII )

RtAL ,,\.I'ir.h values are

ehe ti tIe, eup·pIied

REAL. DATA. by t:.hc user.

and puts

ten

RF.AL va l.ues

l. nco

it.

The

To Dbtaln t.he screen

IRITE ,o.re

thE' va.Lues , the pTogI:B.m ual:!S III WRITE til disp lny and Ii READ 1;;0 ac cep t the. value tY·!Jeil by the user desr::rihed :in de.tailfurther on ill I:_hi~· chapt.az ,

Ii

promp ~ nn .RMD and

J
VAK F: I: FlI.E 0.1' REAL~ INTECER.;

EOLN r at u rns elO:'led f1.lE.

fa Lae

i1J1ll1ed a t:ely t

af ter

the

f:! 11"

j

a opo;med,

and

Lt'Ue.

on a (*Opeu

~E.GIN
("'R~d
(*Put of

When a GET finds

au end-of-Une c:harB!:tl<'r (the CR character, in the f:!l~. ~ Se't!! ~OLN to tnm. ~ Instead of loading the charlie t e r in to tne Ii Le" s buf f er vart able it l.oads a space For' ChI". behavd or I:hese statements 01 C:OLNaf t.er further on. a READ or R&

IiLN. see the

ASCIT 13) etld-of-Linf! (ASCII 32),

w:1'th REIo.TRITR s:[OI:e th is is a del.! f He. B.EWiRITE ( F, " "'REALS " DATA' ) ;

,.,)

1,0 number s and st cre
a pro~!;

chemin

tb E' file

,."')

des('_r1 pt Lens

OIl. the screen. *1 WRITE,' ->'); (;tRead. a number ham the keybQa:r.::l.~)

FOR 1:'" 1 TO ~0 00 lEIf)t::lt4

(*Sto:[e

THE GET AND PUT PROCEDURES
a i:yp<!d f1 ~,e. The forms are

'Tne.e,,., ~ rocedu

re s

are

use d to

read

or

wi t.e

OHe

]

0(;1 tal

r~eord

I r atn or

tlJ

Rfu\D(F~I; "WIlber Jn the fih •.*) PUT (F) mID; ("'t:la~e the rUe and Lock 1t. >11:) CLOSE (F. LOCK) EI,m.
till:!

FlLEID
rILt;;ID

The second program reads vBlues from the p rogr aa .• ana d:isp!a.ys them on thB; screen.

fi Le cr ea ted

by

t~e

if rs t

,..tltlre F:LEt~
typed

is t:b,e jdentH'jer of B previo!Js1y declar:ed typacl file·. f I Le lS any C:[lo= for which a type Ja spectft ad In rh e variable decJ, a T<l t: lon, ,H. oppoSl:!d to untyped HIes (s.ee t::lmp e r 2). t

A VAR 1": FILE OF REAL;
RE.GIN wi tn RESET s Lnee "'e wa,fit to :read the fi lei< 1 RESET(F. 'I<REAl.S. DATA' ) : ("'Read each numhe r hom the file and d_hplay tllem*) WI:ULE NOT EOY(I') DO BEGiN (lI[jj.J'lpla), tILe cunent numbe r on the e:CI"l<'en"'l WRI'I'ELNn'~) • (";Advanr:e to the naxc number'" J .E.NLJ ;, {"'Close [he ti 11";1.) C10SE(i) I!:ND. Note that rhaae p rogr ams v_tIer Ill] fll".xfb.Uj ty as to the c:ltle [lfthe file. T~.,~example unde r ilEA111..Nbelow shews bo .... to let tll1~ USE_'r !lpl:!c:ify the ti tLe of the HIe 'to he us,ed.

G!l.T (.FrLEIlJ) advance s th e f j Le po:! nt.e r t o the ne .... re co r d and moves the e ccn ten.ts of this record into the f1 Le buf [e:1" VElI LahLe FlLE1D~. The nex ~ G I';'r or PUT wi ta tb",,~al!le FILEID wtll a\:cess the nex trecord in sequencc. pm' (flLEID)
COli can

(1IOp,en

adv.auces
aCC~~;5

~fj of FILEllr
lOt 11

FII.. r.IIJ

the fjle pointer to tile next record and p u t s the i n ~o this 1:ecord. The nexr GET Or P~'r 1I1til the s;1me tile 111'" rucur d i 11 sequ enee " X.L

GET(F)

Tho actual phy~icall!ljsk sccess umy no!:. cccu r until ;:h~ Ilext t f me the phys i ca l.Jy 1iJ>.'iocia~ed block. of the: disk Is no Iongar consd der ed the curren!: working block. The kinds of opel:.1tionwhlcli tend to force. the ~1o~k to bOi wrt [ten at'''; S SEEK to els~where In the f] J<3., a llESF.T, and L;!..O:SIL Suc~(!_sliive GETs or PLI'l:" ,"Q the HIe will cause the phys Lca.l, I/O to happlo!ri wl~en the hlo!.:k boundar I es are crosJ>ed, folloo"ri rig, CI,/o example CLL.lS"E, EOF, r.:"'r. and PUT.
TtH'

prcg r ams i 1l1lS ~rat e the uae of I:i.EWlnrf:. RES I:;r • 'Tho fiTst ~m!lrs.rn c_rE!fJt~9 a new fHe of [yp~

30

APPl E PASCAL LANGUAGE

BU1LT·IN PROCEDURES AND FUNCTIONS ,31

THE IORESUlT fUNCTION
This
Las
t

function r e turns e~ in.eger completed I/O oJ/era l:iot1..

value
The fOl:m

which
is

refll!cts

the

st:!3.tu~. of the

The values

rr:eturned

by

IORESU.I.:r

are

as follow5

(also

see Table

2):

1/0 p.ocedUl::e:s can only be usad wi th fUc~ of ty~e 'rEx-,: or lJl'IERACTIlIl'.:_" As already ·mel1l[·ioned. RESET IIUlkes a dis t Lnc t iOll bet~een .hese t.... _f 1l..ei:yp e!l; 'when .OJ! TEXT file o is RESET, em GET is aut. oms t 1c.0I.1 1)' per f,ormed but when an INTEUC'[I1iF. fUe Ls RRSIIT. no Grr hi perf o rmed " This :requires READ and READLNto be l:lltllN." comple~ pr ccedur e s , Like many other oo:mple.x ct aa tur e.s , tDey will roehave sirn,ply if you, IJIiH:! ~h= !li1llply. Therefore, this manual is written wii:h same assump'~l,Of)6 ~nwind about how t:iley will be used. The.sl!/3Js:liiumptiofiS can b!:! translated Into the following spae If i~ eugge s ei.ens : Tll.e text:

~
1

2 3 4 5 7 B .~ l~
1I

NQ err~r: normal l/o completion Bad block OlU diske t t e (not. u sed 011 AppLe) Bad device (volume) numhe r Illegal oparat ton (e.g., read from PRINTE.R.:) Unknown hardware error (not used on Apple)
Los t device -no Lcnge r on line

_ When using tHe text I/O procedures don't use GET or PUT,. and dQ~rt refer exp LLc Lr Ly to th~ f t.l e buffer varianl€! r. Iile r·e.ason f9 '~bBt ene [·ext [/G proced~r~s themselves use GET and PUT in t:.olllpliC:lI.ted '-lay s •

s

12 15
l~ 54

13 14

-- file 1s no long:e 1:' in. dit:.ec·to ry -- ill@gal filename No room -- ins I.e f He:! eut spa ce, on ·cl.lsk.e t t@. No device -- volume :ILs not on line, No such file on spl!.c.ified vo Iume Duplicate file title Attempt to o~~m an a Lr eady open file kC~empt to ac ce.ss a c los E'd .E :U_I! Bad Lnput, format. -- error 111 r"e.adlng r euf. 01" in~egl"'r Ring buffer overflow ~~ input lI.rriving teo hf>t Write-protect e r ro r -,- di:;lke~ ~e Is wri t e--pr at ect ed Device et't'or -- bad ad dras s or dar a on diskette

Los t Ule ~ad title

- Don't mix readIng
t

and ext f :1.11'.' If you read befor~ wr! tiilt to 11:;

writing operations from a t ext EHe. and vi ce vena.

on the same diskett~ CLOSE it and reopen 1t

~ Te open
RESET.

an ens ~ing dt ske I: te tex'tf ile 1'>0 otnl!n an existing diskene

fo E Itead.:Lng, always te-xtif'11e for writinf.\,
Us e READLN. ir

use

sl",ays use REWRITE.
Don t 1JseREAD wi uh
II

STRING va. r f.ab Le ,.

P'on"c use rbe I::OL~ Iune t Lon wi th JtEADLN. and dOT)' t use STRING vadables.

wi ~h

oper~!:1on. the Compl1eJl' ""ill gen!);race code to perfoJ:ll!t'lInt Lme checks .sf e er each I/O ope 'l'ii! t ion exc ep t tlNITREAD. UNlTImITE, IlL{lCKREAD, r BLOCKWRIT.E:. o this C~115ei9; the program to get B. run-t1_Cle e r ror' on 8 be d I/O Ope-Lilt ion. The ref e r e if you want to clled:t IOR:t:SULT ~H:h your own code in ~~c program, ynu must disable this ~ompi12r feature by using t:he (*$1-"") opUon (see Ch:!l:p![('r 4).
Note that IORESllL'r 0111:,0g Ivas a v!llid r'!iH:llr1'l the first time it Is ref e rl!!nced afte r an I/O ope ra ~Ion. If:l t is ref e r enced e.ga in (10:[ cheur another I/O openU:io.n) ,. it w1ll al .... oys r e tu r n 0,

In normal

1f yon follow these suggast Lons, rhe text I/a pToceom;e5 .rill wOTk exac t Ly as de.sc:dbed in t.he fa Hold ng pag;e5. These arl!- no r ru Les of Pas caL] there 1B no :ching in tbe sYBtem that will enf o r(:!! enem- HG1-l('vl".l', the exact. de.tu.Ll s [1£ whll.t: ha,pJl€.[l5 if you i.gnore ~b(! 9ugges t Lens are
'beyond The"e the
BCOpe

of

·>.his chapt er , f.n whitb these aaauap t Lons and suggestiQ~s ar e the corrp Let e details 011 how !l.E:AD s Hua 1:10n8, as gLveD. 1n A.ppel'idix C.

lllBy be6.1tl.lEl.'cions

too rest r1 ct1ve .
andR]::A!)LN In particular, read1ng and file without behave

If
in

so.

you,,",f 11 rteed

11 possible

'You need '(he iniOi."tlMclofl in Appendf,x C if you w.. nt; HI wt':i Cing ope ra t Lona or ove-.wr:l,,~e peen of an existing I:ext destroyi.ng; all ofche. or1ginal con<:ents.

THE !READ PROCEDURE INTRODUCTION TO TEXT ,I/O
In ad Mtiollt:O PUT and GET. Apple Pascal p r OV.:ldes the s tanda rd pTQc~dl.lI:·es Rl:JID, READ LN., WI'ff., and WRIT·m..~, collectively know as the t<e:!!'t 1/0 p["oceduTes. They perio'rm the same t:aBks e.s In s eanda re Pascal and have t he same Sytlt.1lX (wi t h the ad dit ion of S'[RI NC vllr'iaIJ les) " HoweVEr, r he de r a Lf a of tn~ir opeI'at1on aze specific 1:0 Apple Pascal Olrnl can be camp lic;!. ted.
dill'Cinr::tion between p'rocedure Jr><Iy be used <t:Inly en TEXT ,(FILE. OF CHAR) or INTERACTIVE It allows clHI.1rl!Jctel:'S and fllJmeric ~'alues ec be Tl!a~ from a £lie t the need to'r expli cH_ Llse 0' r GET or exp.l Le I ~ 'refl!HmCe to the w1ndow vs rrab le, The for1!l is Tl;ls

file.s.. .... i thol.!

PMCE!llJil.ii: READ ( where
f'lLELO is the

! FlLEIU,
of n TEK'!'
01"

4.150.

TEXT and

the use of STRING Var! ab leg and t.rte rNTERACTIVE fHes have irn;pQrtMt effects.

identifier

IN1EltA.CnVE

file

",hichrnust

32. APPLE PASCAL LANGUAGE

BU!LTIN PROCEDURES AND FUNCTIONS

33

be open> Xf the FILEID 1~ omitted, INPUT is assumed. VBLs meaDS one or mOire variables separated by commas. 'the Wlriables may be of type CHAR. STRING, WTEGER, LONG INTEG"BR, Qr REAL. (13ut you should USe READLN [or SIRING varIables).

If the Laat; character of the numeric:: string is the lase charact.er on the line. t.hen EOLNIo'i~l be true. If tl1e las t character of the. fIllnmr1.c::

strt~g
true.

iB

the

lost

ch~ract~r
ere

in the

f~le. then BOF ~nd EOLN will
the EOF. a value of

both

be

RE.AD reads sequence.

values

.from the file.

and assigns

them to the variables

Ln

if

nD~hing th.llt

but the

spaces
behavior

found

befora

g

1~

READ.
thn

!I
READ With a CHAR Variable
For !l! CI:lAR variable. READ reads that character to the variable.t~e end-af-lioe ~h~racter (ASCII CHAR variable is a space (ASCII true, tJ1E value <lssi!l:ned to the At tl!'r the cha eact.er RRAD, "he next READ UlllllI~dj_at:ely followins

Note

same regardless

of whether

of REJlD Iolith a. f1uIDG!ric variable i5 exactly Lite file is lEXT or lNT~RACTlVE.

enc character fr·om the fil@ and assigns Thcr@ are L~o spe~lal CBSe.s: !~enever 13) is READ. th~ value assigned to the j2l. not a CR. ~~e.nev~r EOF betomes CHAR 'Vll.ria.ble i·snot defined.
REAOUI will alway!! s tar·!; wi tht

THE READlN PROCEDURE
proced,un 1lIIil' be used only on TEXT (FILE OF CHAR) or INTKRACTIVE f ilea '. It allows line-oriented Tead1ng of ehar act eza , strings. and nUL'I1eT·ieValIH!!;;' The form i.E!
ThiB PROCEDI.IR.E READLN ( identi [FIl.EID, VEll.s which
IWI>

or

the ~here
TEXT

~he one just

READ.

The workings af EOLN and EOr depend on wherher dl~ fil@ ts of type or INtERACTIVE. for ~ TEXT {tIe, KOF iB crue When toe last text

character In the fi..le has bei:m READ. EOU\l ill true when t.he last: text cha rac ee r on a line has bean READ and! whenever EOF .is true. (A "text eharact e r" here liIf!tl.nS a chaxact.e r tnac is not the end-o(-l_im~ cha.rnc re.r or the· end-of-file char ae t ar , )

be open. If the FILEIC is omitted. INPUT is assumed. VBLs ruean~ one or more variables separated by commaS. The variablee may be of ~pe CHAR, STRUlG. INT E.GER, l..ONC !rn:~GER, or REAL.
atADUT

rru:m

is

the

Lar of a TEXT or INTERACTIVE file.

t

for the las~

Fa". an INTERACTI"llEIi Le , EOF is
has end been READ. IJf the line E01l< is ne t true has been READ or

[l1J

t

true

until un t i1

unti 1 the end-or-file· character thl!' ('nd-af-line chflracte.r at the
EOI' is true.

w(l;rks exactly like READ, except that af t.ez a value has b@en Teed variable, the remainder of the line is skipped (including the end-or-Tine) _ After any READLN, the next READ or READLN w.ill always B I:art with the firs t charae ter of ~he next line. if tiiere 15 II nexc line. Lf there is ne neKt line, £OF will be [rue. with STR1NG variable reads all the characters u~ t.o but not charac~er. Thus repeated READLN's with 8 variable have t.he efEec t of :reading successive liiH~ii of the file
8

READLN
including

using READ with a CHAR variable and you need to use EOLN, yo~ may be able to simplify the s Lt.ua t.Lcn by uaf.ng READLN witll Ii SrRING var tab Ie i.nstead; this gives YOu Lfne.-o Lent.ad reading wit110Llt the need r t o ch eck EOLN Cs.e" below).

If you are

STRING
llii

the end-of-line

strings.

READWith a Numeric Variable
For a va r Lab Ie of on e of the nume r Lc 'types, READ expects to r'ead a st r Lng of chanll::teIs which can he interpreted as a mIln~ric value of the same type. Any space or end-of-line charact;erspreceding the numeric string are sk1.pped: and a space , end-or=Lf ne , OJ!" end-of-file is expected after t.he aume r Le string. If a numeric sering 1_8 not found a car skipping spaces and end-of-11l"1es, an I/O error occurs. Otherwise, the string is converted to 8 nlJm€ric value and the va.lue is a.8s1sned co the
next RENJ or READLN ~ll always ",tart [allowIng the last character of the with the numeric

One of t.he 11106 t common mH!B of READLN .###BOT_TEXT###11 t.h a STRING variahle til to read a str1n~ of characters from the CONSOLE: device. In thu fallowi..ng example, ~ich ts a IIlOdii:'tcat.ion of the previous example undsrr GET and PUT, R£ADLN is used to read a filename typed by the user:

variable.

After ~he READ. the character immediately string.

34

APPLE PASCAL LANGUAGE

BUILT·IN PROCEDURES AND FUNCTIONS

35

I

_I
ilpe~i.f1es the number of rlig:U:8 1:.0 be W!:"itten after the decimal peLnt; 1£ EXPR 1s of type; !.leAL. The de.f,alj,l tF'IVICTHlNl.ENGTH is 5 j, the de [au 1 t !FIELDI-IIDTIl is 1. Fot i) no n=nega t 1:Ve R£A1 val.ue , one space is alwiJ:Ys vI'1'~ten bef nr a th,~ .fil'st digit; for a ne~atlve REAL \!'~lue. th~ m:hms sign occ!.!p:l.I1lS th1.5 .~061cion. WRITE eva Ius til:> th~ express ione and w.i t es th@il: v.allue.s to t.he file; in Gequ~n~e.. If EXPR is of type CRAR, STR.ING, 01' PACKED ARRAY DiE !:MR, WIUTE write!l the cnarae tj!ds) to tl"m r He and advances the file P01T1 tlll.'., If a FIELDIi'lDUI has been gi \Je(l and tllf! number of cha r act.er s .... rittcn is leas than spec Lf Led , Leadf.ng spaces are. added to Ull the. EieM.

V.AR

~':

1:

HI..:E 0 F IlliAL.; ]N'i:'I!'.GEIl. ; STRING;

TlTLE: ~EGI.N

("'kook usez for tit Ie. WRITE {'Type name. of fj Le {*"'~c.ept line typed by lI.ller.*) <*I.E td
t Ie has

'Ii.,

l

-);

READLt<l (TITLE); no suf f t x;

add

.DATA suUh:.."'l
••• DATA');

I:F POS" _', Tl'l'LE}=G mEN TITl.:B:"'CO!lCA'l:('tl'fLE (*OP!::[i, "111:l:J R.E[JR1'1'.E st nee thl s is a new fil@"") RIl:WR_llE{F, TITLIl);. ("'Remainder: Another
of program

is 1den.c:l

clll

1:0 p!:'eviol.!s

eK<llllplO!.:II)

WI~fu1

elCample

1S Il,ive:ubelo:w

under

WRITe and OIRITXLN.,

THE WRITIE,AND WRllELN PROCEDURES
These p rocedure-s maJ' be used aoly on TEl\:]' (rnE OF CHAR) or INTERACTIVE

a. nume r f c type." WRITE CDn:v~l't:> the value to a !ltring of standard Pasca 1 Ilur:ter I e forma t , "ffites this :!itrill!: to the file, .snd ad\IaL1CeS the painterIf fhe va Iue 1.5 REAL and ,a FRAI':TIONLfJolGTll has been g.1.VI!'tl." rhn spcc LfLed number' of digits are written a:.f eer eha dedr.lal po inq iff no Fl\P.CTIOlrLENGTH Is giveI'l, five dee:irna 1 places arE! l,Iyi t t.e!lJ. 1£ nece.ss a ry, t11<:> value is rnlllfllled (not [TIJ!1cat:ed) e e t ha numhe.r of dE'c:.1i:.Illalplaces avaHal~le. If!)' FIEUJIHDTH h as been given and the nutabe r of characeer s t.'l:~' c t an f.s less. 1:1u3O ~peciEted, leading spaces are added to fill th~ Eield. WRITELN works be.en l<1:'i t tell I :rl.n~-o1[Lent ed exae tlj' lik'i! WRIT". excep t ·~ha.t a f t~ r the ]::IS t va Lue ce turn charac ter is IJr:l.t tl:ln 1;0 and the H ne , 1'his au tpu t with 9 t 1'1~il. '!1XPl'CSS Lons . hns
1'l1101-l'9

If EXPR is of charac t:e'!:S in

II

E I Les , Ihey allow chaeaet e es , sl:.1 ng!l.and numer I c values to be W1;":i I: ten 1:0 a ;file without the nee<;] for expllc1~ lWEI' of Pm or exp Lf.cdt. nofe.renee 11:0 'I1he ·l.Iiudow vaz Lab Le , Also, WRITI~l,N allow~ line-oriented uuq;lI.~t. The fo:rms are
WRITE [rIl...EIIl; l [IUMs Il WRI1'EJ..1I [ ( I Fll..EID, J I ITEH.e I ) I

wlun:e fIl,EID is
be open. IE

the l,dencH.:te'l:

of

;:L

T.EiXTor

INTE.RAC'nVE

Ei lewhj

en must:

OUTPUT is the identifier of a pr~de,cl:n:ed IN'lERACTIVE fill:' whi~h cal] be uaed \oii t.h WRITE andl.'R !TELN. All ch,,'[:l c.l:e u writ t I<.Tl [0 OUIl'UT ace d Lsp Laye d On the cOl1sole !>creen. Wherl a. pl:ogrs'r,l is ","iring !:o OUT,'UI, the user L1aY type ctrl.-S ~o s r op the out pur . The prop.,ra.n halts <U!1.til another charec tel' iJ> t)' ped. then rl2~umes th", nn cpu t where it lef r off. I\lso, rh e usc!" may cype n:rl-f. 'fhi'5 halts th~ displ.ay1ng of cha rac t e r s on rhe console sc.reen, but the program continuos to ·run. The following example pl!:ogl::arn 111u!Ot('ates a number of ~s{'ful t echnf que s , It us es line-or-iented 1/0 with STRING val'Labtes, p e eEor ors cha ra cter manipulations on t.he STRING VB r tab LeeIt a >lse[ul trick hI: iJPe:rulng a (ile foy olltpLltwhlch may Dr may ~ I re-ady , Th e ef fee t of ttn:~ p.o~il"ilm 1" to rea d '..110 input: f i Le 11n~, I'ErnGVe any leadinl, p·e'(lodll from tl,<3 I tiles. end wrf rIO rhe to tha outp~t file. PM G!'MI

~h~ FLL~ID j6

omjtted,

OUTPUT 15 BS6umed. IXn,.lllas" Ea.ch ITEM has one of bur a 1,81:1 sho,,",s nor ex~!;t line by lines alJ t

l'IEMs I!I~ani;l !me. or more. ll'EMG ~"he Fo Ll.ow Ing forms:

BeOl<l.["ated by

EXPR

EXPR

: FlKLDWIDTH

nus

11E' E1U ODS;

or
EXPR ; Fl~IHDTH
where. EXPR
i.5

:' FRA.C1'ION1.F.NGTH
011

VAR IN FIL E • OUT F:l.L E : TEXT: I NNA.l , OUTNAHE. LIIIEIlUr: !E
WI:I

8m lNG,

an exp rc.ssj

wi1-O.~oI!: va Lua :1s to be

c Lefl.

FIELDlHDTH

hi

an INTEGER exp ce ss.I on whi eh sped fi es the Jjlj oi IlIUI!I !lumber of cha r ac t er s to be wtl.uen,. and FRACTIONLENGTI! an INTEGE.R exp r eas f ou ..,h1ch is.

36 APPLE PASCAl lANGUAGE

BUILT-INPROCEDURES AND fUNCTIONS

37

BEGIN C*Fil"Ht get the filel'; open. *) f*Get Lnpu t filell<l!lle.*1 WRUE('tlil.fjjil of input fil~: ');, REAlll.N {INNAME) ; ("Supply rhe default sllHix .TEXT if needud , ,") If 1'0£ ( , • '. I.NNAl1E) ,,~ UH~N INNAHE: =CONCAT (lNNPJIE, ("Turn

THE PAGE PRQCEDU RE
This pt"ocedur~ sends a top-af-fom

chilra~~e1"

(ASCI! l2}

to

the file.

'Ih e [O]:"m is· PAGE •• tEXT ' ) :

<

FILEID

) "ide.Dr if Ler of at] open file

whiore FILf;lD
INTERACTIVE.

iJO the

of type ttXT

or

off au t oma t Lc E'TrO[ c"ec!11n~, so pr'o~(Bm can do H.ot) (*$l-*) (;;Input file should alre.a[[y el!:ha. So open 1O';t~1J reset."') RESET rUl1"I LE, INNMrE 1; (*1 f it deean " r work, complain 8..nd stop program.'" J IF IORtSllUor;! THEN BEGIN WRITEUl ('Pile nOI: found.'); f,J:U (PROGRAM)

THE SE'EK PROCEDURE
Ttl is procl:'dure, allot.)8· ctle prog~lim to move I;! Ed Le 110 inter t-Il any .Ilpec:.i:I'1('.o record in a file t hat is not a !;.O!x1:file. Th1lO a Ll.ovs
acces:a
!:Q

random

END;

ft Ie

re.co"rls.

T\,e forl1l is

('*Turn

aucomac fc (1'$1+*)

e.r r o'r

checking

back

(ill."'}

SEEK

( FILElII

• REGNID>1 )

filename. "") W'R UP. ('Name of our.PlJ t file: '); RtAnUl (OUTNIIMI: ).; ("'Supply de f au.I t 9ufl'ix "T.ElIT H needed. *) If rDS ( •• " OU'INhlIE) _!Ii THEN OUmAtu:: (*Opl'n fHe t.Titll rewrite."')

C"Get outJllit

'Wn ere.

FILE1D

,
=CONCAT (O!JTNANE.,

te:xtfile intf'ger

i5 the i·de:nt1f i,O!r of an open ft 1~ t ha t is [Jot a (i.~. nO[ created with tho:! .TEXT :'luffh:), and REC~If~ Ls an value Lnt e rp r e ted as a r ecor d number in the file· changes the file pointers so that the next GET []I:" Pm:

-. TEXT' ) :

This

pr-ocedure

REWRITE(OUTFI~E.OUrNN~);
(""NDw

do the job."')

I-mILE (1101 roy (IN!' Il.f.) AND (rIOT Ear (OIJTfH.F.» DO BF.GIN Rl::A1lLI>l(UIFIU.:r..UlEBUF l; IF LENGTI:I{.LDI!::BUIi') >Q 1'I1EN IF POS (P£RlOll, LIJ:EBUn =] T1J EN DEL!i;r.E:(L lliEBUf' ,. L, I); WRITELN (OUT,FI LS., L I1H::SUF I ENlJ;

31

f.oPl!to the fj 112 uses the 1:ecord of F11EIIl specified by RECtfUl1. RecOI:d~ in HIes a ru numbered f r om r;J. A GET or PUT must be execut ed becl:'orE'f'I1 SEEK ea Ll s s Lnca !:t.loSEE.Ks in B TIl~lIlI1y cause unexpected. IJllpredicts,ble junk to be held in the windm. and as!>od_ated buHers. Immediately af t.er a SEEK.!l.Or will retur n hJ.se. Ii fo llowi.ng GET cr PU1' I.till cause EOY to r e turn tbe, llpp ropria te va.Lue « The follow1ng SaJnple p e og ram accel5l5ond update r ecur ds ill demonstrates fill"; the use of SEEK to r::andomly

!II

<l

.PROGRAM RANllOMACCESS;
(1oAllows VAP. upda t.e of any 6elect~~ record in a fU,.~.:t)

(*N~w cl~An Up."')
("'(f ou cpu t fl.l~ isn't comp Le re ••• ,1!) IF EOF(DUTFILE) THEN a~GI~ WRrrELN "Not enough r com in cu t put; £il~!' ( ...... Then t.hro,", it awny. *)
t he

RECNUMBER: iNTEGER;
).; 'F'NAMr:;~ STruNG;

VITAlS; riL~ OF RECQRD

CLO~EcaUTFILf..PVRGE) END
(*If okay, [h~n lock F:LSI'.: CLOSf.(OUTFILE, CLOSE (INnU:) END. it's it into LOCK); the directory.1!)

!lAME: SlUNG 12~1 ; DAY. MONTR, n.AR:, II':TECER; ADDRESS: STRING [5(1 I; All Vt:: IlOOLEAN

El'lIJ.,

38

APF\f PASCALLANGUAGE

BUILJ-IN PROCEDURES AND FUNCTIONS

39

BEGHl ("'Obtain filonllme,'*) IoIRITIl:("En t·~r fUf!.n.ame. : '); REMlLN (FNANE);

THE IUNITREADAND
russs

UNIITVV'RmE PROCEDURES
ARE DANCtJl.mH.i PROCEM~ES prOCedUI€S which do devicf'-[lriCl1t "d I /0. 'In,~

(*lJse Rll:SE! 'Co pres,EIVe.
E.xi.s t ,. use REWRll£co

existing
c.reaLi'!

contents it. "')

of file:

but

11' 11:. doesn't

'[']]ese are

the

lm.-Ievel

('*$1-"')
Rl55ET (VITALS, IF lORESULloi;! FNANE):, THEN REWRITE (VITALS ,liKAblE) :

.Ec,.rps a re
I:HHtREAD ( UNIINTJUE1!.R, ARRAY,. LENGTH

("'$I+"'l' ("'Re'pea t the
typlmg ~n:l-C

tJ.t..m[WRIT[
by USer spaCe for

( UNITNTIMBER, A]!.RA~, LENGTH

I,. 1Bl...OCkNUNBEF] r, [BLOCI(I;1lMIlERJ

I. 1I0DE.]] ) t, [!-lODE]}

new records. '* l' W1ULE; TRIJJl: DO BECIN ,,*ObtaiI'! record number; qui.
!>TRITE('Eate.r reco:rd

.following "E Ore-veE, or i. Gl:. un til .EXIT .110eauaed and cau~ing EOF(lNP'lIT}, or by hck of diskette If user
i

numbe c

types "1 j

I:.trl--C,

causing

EOf.

"'l

IlNITNUMB'EII.,. an in r eel" r, 1 g the volume nU'rr,be of arl 1/0 r device, The App l e "Pascal Ope r atLng Bysl:emRefe.e.nC6: Ma['U.L.eJ desc'!:ibes~he:8e mnJ:be·r5. ARRAY is the Dame of a packed array .• w~ich ~~l" be subsct"ipte-C to 'il1dicat:e a starr ingpas:i.tiQl1. ThLs is tll:;~d as the s tart Lug .lIddr ~ss to do the trans fer!!; fr Dm/ to. A s n;!. n"" may also be UJsIOd,bur it should have" sub.o;crlpt gr eat er than ~. since. the ~th element of a s t r i.ng contains. d.e:ltawhich uaua l Ly sh(!uld rmt be tTtll1SrnH t,12'(! • LENGTH d s an iot ega
1""

READLN(RECNUMRER); H' EOii'TH"E~ BEGiN
CLO'SJ'l(VITALS, LOCK);

~XIT(PROGRAMl END,
< *GET the sp ec Lf Led r,ecord*)
SEEl( (Vl'tALS • RECNmlB Ell. > GET (VlTru:.Sl;

;

val ue des Lgnat; i~

the

rmr.abee of

byt

I!S

t~

r r ansf a r , BLocnmUBER. an iQ!;ege.r. is me.aningful only 'wh~n l~!l:tng 11 disk. drive ;].rUI 1sthc ab so Lut;e black numbe r a twhich th·!! tra elSie r
<..rt..ll start. Htlle HLDCKNt~~E1ER Ls Lef t cut ,

f "'Up da.t

B

the l!:l!cord"') WITH VI'I'ALS- DO BEGIN W!U'JELN (NAME) j, WRITEC'Er1:t<!l' C01i:1:'e.ct name: '); II. EJillLN fNAME) :' WIUl'.ELN{TIA't) • WRnE ('ElUeT COHect: dl'l.y;'); RUDLN (DAY) j.
Sil i:Q-rtl1 .... ith EN:Dj

G

is

AS.!HIJ'Jed.

MODE, an int@ger in the range 0 •• 15, Is optiQnal; the defaulr is ~. It COt'l tr'olst;wo UN lHJ'RlT E op t ions wl1 f.ch are de s c r i be d beJo~. ~ODI has no ~ffect on DNITRf,AQ. The U].lITT,.,'RI'TE op t iOT'l5 COQtr ollec:lby the NODE pa ratJ.:! t er app ly 0111 Y ce text~orlp.nted 1/0 devf.ce s such as U~e console or a vp rd.nt er ; [hey do no' /;Ipply to disll.·...t t e dr Ives , Bct.h options are enabled by default, if no MODEpa;r~me t.e [" is suppl1.ed.,

("' .••• and

ether

fields·

of record.*) GET advanced the .Hle ClITI[!n't ·rec.ord "into

I

('"No'" SEEK t.h·[! same reeoTd

allia:ln,

pflinte'l: to th·1! next record
VITALS~ ",.) SE.EK(VITALS,

alter

sillce the it gc't the

RECNIIMliER 1:

("PUT upda t;ed record

l.nto

:tile,;.

eltH

if

this

C~US[!s IWF. "')

PUT CVIT ALS ) :. IF EOF(VITALS)

One op r Io n i.lO COVLVP·rs1.on of OLE codes.In a Paaca I t.extfile, any leading space.s at the beginning ef a Bn", are t ep'r ase nt ed by II (H.E cna-rac t er (ASCII ]6) f ol!crwed by Ii coda valuewh icn is 32 plus the nu'ii1beo of' spaces. r On ell tp u r ro a non-b lock-s true t urea devt c e such as a printer" the DLE. conversion (ireton detect;;; the or.1': code and converts it
into a sequence' of
0.E

TEtEN BEGIN \~Rt'l't';,LN ('Not

spac es ,

enough

fill:' space!'):

'EXlT{l'fr.QGRAi1)
&:ND .END ENIl.

Conversion Bit :3 (S'2C

DLf codes bdow).

Ls disabled

by a MODEvalue

tlUlt

t-RIl

11

one in

Tne other op t Lon is aut.oma t Lc line f,"cdB. In a Pas ca.I t ex t f Ll e , the end of each line is rnadeed by the end-of·-li tHO, ch a r-act er CR (AS,en I J) without any line-feed ehar aet ~T. On 01J cpur [0 II lion-block-s cruc rured

.40 APPLE PASCAL LANGUAGE

BUill-IN PROCEDur~ES AND FUNCTlONS

41

dev Ice such as. a pot'inter, the automatic line-feed opt1Clti Lns e rt s B[JLF rharacteT (ASCII l~) af t e r every cs enaract er- (ASen 13). AutOmatlc line fel!d~ Bil 2 (see b~lowl. are disabled

THE UNITClEAR PROCEDURE
Thb, procedure canc~ls all Ij[) operations resets tbe har dvs rc to Lcs pcowe-r"up s t:ate. [o~he splE!cHied
b;

by

B

!IODE value

t ha t has

a

oDI'!

Ln

unit

and

Th e form

O!'1ly n t 2 and 8f t 3 of t lre ~ODE val ue have ~ [1j s Lgn if 1~il rm~ • Bit 2 by Lt se l f , co r r espends to a value of s , ami Bit 3 by t t ae If ccrre5pond 't OJ. value of 8. The fcl1o~il1g values can be uaed to c nnt r nl t he oPtl:1W~ - MODE-fj I~he default "".;tIue) oatn,:e:5 but h options
til

IORESITLT is se.e to a non-zero value ti thE specified unit is not present (you cen U5~ th Ls til ~es~ t.lhQther IJr not a given device i!l presen.t 10 the !l)'s r err) • UNt"tCLEAR The Fo rm (1)

to

bE': enab Ie d, !.;thil~

- M'[]J)["-I.'icau aes au t eraattc line feeds Ie#l'~1 1''; OLE COlIlJC rs Ic n e nab l.e d " ~!Oor=1l cau ses ULE com;ers 10ft au ecraat Ic line feeds enabLed. ~ MODE"'l2 feeds.. d l aab l.as loth
[111':

bl;! d:!s<lbled,

to

be

d.l s.ah led.

wh1Ie

Le av i ng

flUGh~s tile type-ahead s~rclling to full left
SCbcenJ.

buffer for CONSOLe.: amI r~s{!ts horizontal (disp1aY5 bftmost AI#cn.aracters ~n Apple~s

ccnve rs Lon and

automa.tic

Li.ne

THE BLOCKREAD AND BLOCKWRITE FUNCTIONS
These hmetians ~ranaf{! .. da.t a to or from ,!lfi ~nq'lled file,. They an in t eger value wh Lch is the nurnbez of blocks of etata act ua Lfy tr8nsfern~d. The :fOI"tnS <I,E! Bl.OC!{REAIl BLOCKWRlTE FILEID, FILEID, i\.RAAYNNfF., A.RMfilA."!·E, ret'urn

THE UNITBUSY FUNCTION
This is a Ll(;SIJ Pascal r:rocedU'l'"E IL!3ed to Indicate= wn['rhe.r jl5pedfierl dsv t ce 18' ~\Js)'. !lUi: 8 ~ nee th-e I/O dr i ve rs "n r neApp Ie I) I:~ not in te r ru p tori yen, UJ1l:TJRJ,s'l' wi II al"<iys r et.ur n t.h I' .... I UE FIILSE. a To w~ether a charact@T Is availablc from the Apple ke,board, u~c the K~YPRESS function [see Chapter 7).
t es L

at.ocxs
BLOCKS

I, RELBLOC1<]

r,

REL.BLOCK]

FI!..EID must

be

the

identifier

of

a previou.sly

dec Lar ed

untyped

THE UNllfWAIT PiROCEDURE
_.

file.
-

.

AlUUIY'NAME is
II

This is II LCSn I'llfical procedure ..m.ich wait!> for eomp l e t e the 1/0 in ~1:ogLe5s. But Educe the I/O are 'Mot Lnt er rup t dri ve n , UtlITWATT doe.s nothing.

sped(i~ device [0 drivers on t:he .Apple

I'll e length I:Qe array-

0

r

th£! 1denUHer

the array
b£! indexed

ARRAYNAME~y

of a pt"eviously dec.Lar ed arra:!'. shou I d be an intege;!.r u:uJ. t Lp Le of 512. 1:0 indicate a starting position in

3

BLOCKS RllBLOCK

is
is

I:ne number
the block,

of blocks
numbe r

to be
r e La t Lve

t r ansfie r red ,

co

~he at ar t of

the

Hle., the :;:ero~th block being t.ne Hnn b lock ill the file. no RIlLBLOCK hi spectiled, the reads /wrHes will be done
sE.quen[lally,. Specifying RELBL(lCK
lII(];,reS

If

th~

Hie

'poiGte.r.

I.IARNING; Cauti.oD should hi': exerci5 ed ..,hefl using thf'!lf' fllnc:.tions. a Ha.y bcuada ar e not; he ede dROf"(FILP;rn) bE'C:omf's true 'Wh',!1l the

as [he las t.

block in a rile ia read.

42

APPLE PASCAl LANGUAGE

BWLT-INPROCEDURESAND FUNCT~ONS43

The

foll(jwil1~ PROGRAH

p:rogl:am FIL.EDEMO:

illustl:ates

the lise

of

HLOCKR.l1ID and

BLOCKI;ffiI'l'E.

MISCELlANEOUS BUILT-INS
THE AlAN [FUNCTION
The A'TAN func.c:itonis sill!ply a Mfferen!: 1derl,t:1fie:r for the AltctAl'l f uric tioli of S I:,artdard ~ag cal. Along wi th ~he oth.er tl"ammE!1:Idental .func ti ous , 1 t i~ part of 'the TRANSCeND maT 6l.1p'pl:i ad wi t h Apple Pascal

VAll. B1OCKlIUMllRR, BWCKSTRANSFEttRKiJ: BADIO: BOOLEAN:

lNTEGER;

G.F: FILE;
IMJFfEH: PACK.E.n ARRA'l[\l (* Thi s pl"ogram reads the fUe into anoth@r rUes and the b,dh-iu!'!

•• 511J

OF CHJ\R;

a d15kfile

taIled.

'SOURCE. DATA
'!J~ST!NAT1(JN'

dlskfile called IlLOCKR.E.All and

' and cop ii'S using un typed

(,see Chapter

7) '.

BtOCl\WRtT! ,,)

8EGl~ MD i.O; =FALSE; RESF.T'(G, 'SOITReE. DAT"'); REWRI IE (F, 'UES,], lli'ATrON' l ; BLOC KN LIMBER : =Iil ; BLOcksTAANS F E:RRED ==oBUJCKREAJJ (G, BUFFEll, l,ELOCKNUMBJER): Wl1l1E (NOT lEOF(G)) AND (IORESULT-In AN'[) rNO! MinD) AND (BLOCl\Sl'RAN5FERRED=1) DO !If-GIN BLOC KsTRAN Sf ERH E1l : =HLOCKHRlTE 0' ,£lU~ FCR. I , ~toCKNlJ}IBEll )• BADta: .. ( (RLOCKS1"P.ANSlF'ERRED <1) OR (lORES'LTU<>\ii));, !ltoc~:N!n-'I1r::R; =BLocKNlJ!o.mER+l ; BLOCKSTRANSFI!JtIUill; "IlLOCKR EArl (G. BUfFER. 1, BLOCKNillIBER)

THE !jOG FUNCTION
Ih~!lI hlU~. !OIl retu'nl!': t

a rea.l, value whi en is the 10g<l r:I t hm (base 10.1 of its OIl:' gu:menc.. Alon.g wltfl the other t.an~c",nden tal func ti ons, il; is part of th a TRANSCENDUNIT supplied with Apple Pascal (see ChOt:pt""r 7). ThE form 1s
LOG ( t>lUMllER )

~h~rc

NUMIlER I::llJn be ei'ther

a :relll

o!: an il'ltege:r

value.

~tm; CLOSJ::(l',LOGK)
gNP"

THE TRUNC FUNCTION
Tila fu ne.t Lnn TRUNC 'Wi 11 accepz a LONG INTEGER as; well a.~gument.. Overflow Idll resu.l~ .if the ab501ut::e value as a REAL
0115

an

of the arglJmen.t

exc.eeds ,MAXUrr. Wit:h 8 REAL ar'gumen]; ,TRUNC rat urns an IN'rE:(j,ER va.l.ue formed by dropp I ng the fra'ct.ioual par r. of the REAL value. Wah til 'LONe INTEGER vallle. nUNC re t.urns <I nLlme<:i cally aqud VII len i: INTEGERvaJ.ue"

THE PWROREN FUNCTION
This
functio'n The

re eurna
is

a real

v<l_lue which

Is

10

to

a specified

(:Integer)

po~er.

form

where EXPOt'lENT 1 s an ret.u fils the value of

HI

integer
to

value 10 the range ()•• 37. the EKPON:E.NT pow-e!:.

Ih:l

5

funet t cn

44

APPLE PASCAL LANGUAGE

BUILT·INPROCEDURES AND FUNCTIONS

45

THE MARK AND RELEASEPROCEDURES
Th e St andar d Pascal

Below isa pLct o r i .. description J program" S axe cu t ion ~ in ilpple returning Pascal" dynamic lOP OF HEAP ,->

of

the

heap

at,

this

point

in

the

Instead.
memory

the

procedure DISPOSE is not. provid~d MARKand REL:EASE er ceedur es are used for to the sys tem., The f o rms .are

<--

HEAP

eLl.ccatLona

MARK

r HEAPPTR )
MARK to

RELEASE ( fl]W'l"'rR whel:!! E!.EAPPTR is of type "'1:N'J:'EGEIt nd ts called a by l:'E!feronce in tile p r acedu re. HARK sets HRAPPTR to the value of the sys tOim' 8 current top-o:i'-ilgap pO'i ntel'. RI!l.LUS1\:5 et s the systeTIl's top-or-heap pointer

cont.enrs of heap at s t.a ct, of p.ogram
NI!.)!t the pr-ogram calls the standard new var tsb lePwhi ch is Luca t€d in below;

-procedure
the heap

the

value

of IIEAPPT'R.

NF.'il and this H!Sl,dts iTI as shown in the diagram

R,

The process of re~overing memory llpace described below is only an approx.:lrnatloll 1::0 the fun e t Lnn Cl1; DISPOSE as OI1e canno t expl i cHI)' ask th~1: the storage occupied by Clne par~tcularvaT1able be released by the sys tern for other uaes. Variables created by the at and .. rd procedure N.Et/ are at crrad "in B at a ek+ LIke strut.ture c.ali.ad '~he: "hi1al'''' 'J:'he f o I Lowi.ng program is a s LmpLe dmllons cl:atioli of how IiAIU: and RELE.ASE can be used to chanp~ t.he size of

TOP OF HEAP

-:>

c~nrent9 of heap ~t stRre or prog~am
After the

the heap. R~LEASE the h~ap i5 as follow.:

TYPE

PEEl$UN=
RECOIW

TOP OF I'If.AP -->

<--conteTIts of heep at at art of pl'o~r<lm

lIMP

IlMlE: ]>A.CKED ARRAYlr;l" •• 151 l[); [N1'eGER

UF

CHAR;

I!!i:

END;
V:AR P: ftPF.IUlON; tlEAP: ~nITEGER;
BEGTN

:
I

~I!!!I

~~

I
I

Onr:e. the. prOf;ram {I,CI Longe c needs the Jat'iable P" and wt shes to "release" this Dll!f:!Clry ~p<lce to the sys cen Eor o tbe r us es , it <":eils kELIiCASl::. whiel1 resets th e t.op of heap to the addr e.sa con t;i'l i ned in the va r Lab Le Il'f.AP.• If f:E'l1 had been ea l Lad SI:V" rOll
t iDles

MARK (REAP) ; !<lEt.! (P) .: P~.NAHE;"·FAftkLE,

bNIJl':en

t he

c.i Ll.s

to

lL-"JlK a nel it the

IrEmlY J.';,

P-.ID;"999;
REL[ASJ:: nn:AP)

END.
3JlfOgHHIl shows a par-til:1l1arly handy method fo r dllOH IHO!T;! 1:1" Ly acces~ iIig the ~.ont:en!:.s of mo=mory loI~id, is othen.rise inar:ccssllble:. Ie first call:'l MJ!J!.K to place the addr eas ot tlle cur raut top of 'heap into the va .r iJ;lble

The W~.

I. I
I

1-3

RE.LE:ASt~, rh e stor.age nC:C1.lpie~1 by Seve La 1 var lab Les wou'] d have boon REL£1I.5Ed at ,mee., No!;o tt);lt be-l::'IU~~ of the st ack nature of the heap
is not posllible to middl e of th E' heap. r e Lcaac !;h" memory SPIIC~ used by
,j

Bingle

item

in

Calrl!li!SS IIS,e of ~1ARK and to a r ea s of memory wldclL

RELE.ASE can Le ave "danGling n re >Ie lOllge t' p~ rl "r the

pnint~H5". de tineD heap

po Lnt Lug SP!lc",.

46

APPLE PASCAL LANGUAGE

BUllJ-IN mOCEDURES AND FUNCTIONS

47

THE HAll PROCEDURE
This procedure generates

THE 'GOlaXV P,ROCEDURE
wiu!.n l!7:fllcut@d. ia causes a ThiS procedure The form is ( XCOORD • YCOORD ) ","nds the cur sur to
III

non-fata

l J:'un-ti,me error

a 1:IALT epccde thet. to nccur, The form

ilpec1fied

pas :!.tic,"

Oil

the Ill!reel'l.

HALT For

GOTOXY way to ~I!rminate

B. more orderly

pt'ogralO uxecu cIoa , see

'EXIT belo"'_

THE EXIT PROCiEDURE
The EXt! prccedura causes or from th~ program itself. ElUT (pl:'ocedurename) EXITCprogramname) an orderly exi.t frem The forms aT~ a procedure. or function,

where XCOORD and YCOCRD are Lnteger values and Y (verticlll) c:oordinat,e's. XCOORDnrust '!CQORD mUJ;lt be tn the zenge ~ through 23. coord.inate:s. '[he uppar lef t cornet" of the

interpreted as. X (horizontal) be in the range iJ through 79; The CUCSO[ is sen£ to ehaaa screen is assumed to be

01.i!'1.
This P !:Qce.dlllr.e is _itt: en to \oIo·.k with th a Apple II' s scre@!h !£ you wish to use an exte~aJ terminal, you will need to bind in a naw GOTOXY us tug tile IIINDER p&t::kage desc.dbed t., the Pascal Ojl@ra.n:ing Syst:em

Manual.

EXIT (l'I.l.OGItAH)
In the firs t Eo rtn ~hnwn, EXIT accep t s as 11:5 sang Le p.a"t'amerl!!r che identifier of a. procedure or function to be eldted. Note chat; this l'lE!ed not be the procedure or function in which tha EXIT at at ement; occurs. EXIT .follo~s dIe trail of procedure or f uncr Lon calls back to the procedure or fUDction specified; each procE!dure or fuoc~ioD in the trail i:s exited. If the specified procedure is r-ecu.l'si

!;!, the most receot invocat Lon of cha t proceduru wi 11 be exi ted· !
't'Ien a J)lrocedu['{! are au.tomaci.cally The use undefined of or Eonc t Len Is exd ted Ilia rouT, a'l1Y files Lnca.I closed. just ali if it ha.d teT1ll1nared normally. can caU.se the the function ro it

THE 'TREESEARCH FUNCTIONI
This

kind oE

a faJ!it Eune eLon far structure. The

searching

a bi.ne.ry

~re!i! that

has

i!l.

particular

form is
N01JF.PTR.. NAME)

'l'I!..EESEARC¥! {ROOTPTR,

w'here ROOTPTRts a poin ter til th~ roo t "ode DE tl'l e; tree to be searched. NODEPTR ;is ;) po.inter vadable co be updated by ttEESEARCH. and NAME Is
the identifier S-c:haracter Th.@ nodee of of a PACKED ARRI\Y nllm!! to be searched for the biJlary tree are

n.. B)

in

OF CHAR whic.h the tree. to be lin~ed

e.Ontains

the

EXIT t o exit a function value 1f no assignment

function
identifier

to

to

return is In'iIoe

an

;!ss'U.rnu:ad

TB(!ords

of

the

before

EXIT is

eXl!cuted.

.form NODl!-RECORD

When tne prog~am name. or the reserved 'word PIlOGRA.."1 used as th[' i.s p a r ame t.e r for !!:XIT, EXIT br:lngs the progra.m to an orde.rl~' ha l r ,

NAME: PACKED ARRAY!1 ••8] OF CHAR;
RlGE1iTLINX: fields

LEFT~lNK,

l<iODE.;
can

THE MEMAVAIIL. FUNCTION
This function returns the nureber of words C\lrrBntly betwe rI the r.op-ofstack and top-o.f-\,eap. This can be Lnterprl!tlOld aB the anoun t of T1IE'mory available at that I:.~me. The form Ls NDtAVAH.

••.• (~other

be any th1t'Lg~) ••.•

END;
Tbe type name and the field namas are no t lllipor~ant. 'fREESEARCll. only assumes that [he f.lrs't eight bytes of the record contain an B-charact.er name and are followed by LWO pointers to other nodes.
assumed ehat; names Bre ncr duplicated within the t.r ee and are nodes according to an alphabetical ru.I e e for a give;n node, name Q·f ·the leh subnede is alpflabe.t·ic&lly less than the, narn.e of the 1'I.ode:, and tl1e name of the right si.lbnode is alphabetic.all? greater tha" the: name of the node. Pi na.lly. !'Illy 11nks that do nil I: po:l.ntto other It is also

,u:signed

tn,,,,,

to

nodes

should

be NIL.

48

APPLE PASCAl LANGUAGE

BUILT-IN PROCEDURES AND FUNCTIONS

49

TREtStARCH

can rl"tu:r~ any of three

vaIuea :

BYTE-ORIEINTED BUILT-INS
'the tr<l.e, 'to by
~I

~:, Th e NAMK passed to !REESEARCE has been f.ound in the traa , 1l0DEPIR now po Lut s to rh e node ..nth the. spedfied nafile.

i:, l"he NAME is [lot in the treO!. If it 1.5 added. to it ahou ld be the dgh ~ sub node of the node pointed tl"ODEI'TR.
-1; The NAME is [lot f t ahou ld be the Id tlODEl'TR, ln~he
t

TheseprQC'.edures not protect

and

Eune.t

Lons

~re

all

byte-oriented.

The

syst.l!.m doe!'!

trel!!. If it iB, added to the tr~.e., sub node 01 the, node pointed to by

iI:.se.lf f r om them, as no range che~king of any sort Ls performed on rhe pa1:amel:erB and 110 type checking Ls pe.rf o rmed on t.he source and deBtination parameters. !lead tho descriptlona careflllly before 'trying them out. Also,. some rsach Lne dependE!~(!ies may 10Lk i.,; the implement.~tinn5.

Ttl e T[l.!l:E.SEARCH fune: t Lon does parameters passed 1:0 it.

Dot perform

,my type

a:hecking

on ~11e

THE SIZEOF FUNCT,ION
'fill,s Eunct Lon HH;ur1l5 an inteFjeT value ... 1ddJ 1.5 t.he number of b,yte.s occlJ,pi'l!l..a by a Ilpec:i. f ied va r t ab Le , ot' by emy va r tab l e DiE a .specifie.d t.ype. Snl!Of is p~rticularly IJseful Eer nLl..GRAR, NOVE1HGrlT, and 110VELEFT built-inE: (seE below). TIll! ferr.L is

SlZEOF ( InENTI~IER )

THE SCAN FIJNClI'ON
I.hiH

funct.ion scanll a range of ehars cte. target. The. targE r auj' cha rac t e r that does nnt P'ia an lll.tege<: valUi:!, which is the
SCAN ( LIMIT , l?EXPJ{ ,

lnell10ry lhlytE!s,

looking

for

a cna-

can be

<l

~C'11 r.he number of hytes )

spec! f ii::!d char-act er , or H csri be apec Lf led ella rae Un:. SCAN e et u.rua
scannQ.CI. The fOm Is

SOURCE

LTHIT Ls an 1nt age. vs lue Io/h ich gi ve.s the maxl11lum number of !bytes to ~ca1h If. LIMIT is nega t Ive , SCAN will sc an backwa r dIf 'SCAt! falls tfl f:t~d the. spec Lf Lad targec, i tw:Ul return. tile va Lue of LilIII. l"E;XPR is
t h.es'~.lI.Tl "
<I,

"pa r t La I exp reS6 t on" w"fLic'h spec t ties '~he l'EX.PR tt1.ke.:9 one of th G! f 0 110w1ng fa rms : (tar::get is

t .. t'ge t

of

II char ac t.e e equa L to 01)
0'1

(t.<Lrget is .... ere h
type

char ac t e r

Dot

equal

to
t

en)
of

~ s.t ands chaco

'Eo[" any exp cess f en that

yf'c::'ids a r eeu I

50

APPLE PASCAL LANGUAGE

BUILT·INPROCEDURES AND FUNCTIONS

51

SOURer:: is :Il VII '[tab Le 0 E first by t e of the variable by Celi,., It

Ih~y

t}'

pe excep
the

t

II

E il.e typ~.
point of

The

is

starting

til,!,; ac au ,

is cr1t1c!11. each byte must be rncved before. :i.I: gets auoth~r byt .....

oVIHWTlttep

by

:SCMI ter-miua't<'l> wheu it f Inds the target or wheu Lt has acanued LlMIT zheu reL~rhS the lIUr-ID of byt~s sCillllied. er 1£ the ts rgE t 16 found at t he Sea rr.illJor, po iut. [he va Lue (I" [UTII!!d will be zeJ:O. If LIMIT

is uega t 1ve, '~h'i:':Stan be tlli!'!l/l t.rve ..

.... :111 go backwa r d ami

the

value

r e t u r nad 10.'111alii 0

In gi"ue tal t.hls COns Lde nl t iOI1 .6PP H I"S .,m eu SOURCE aud DESTINATION are auba'r raya of the 5~ PACKED ARRAY OF CHAR. If byte.a arebc.ill,!!: moved to the [1gh t (llESTtr:ATWtI has a highe r subac r Ip t ehau SQml.CE}, use HOVRRi GRT. If byte!! an<! bei~lS Iliove.d to the l'i"ft (DESTINATION has a 10'l.le:L' 51J.b~c,[ ip t rhan SOURCE), USE MOV f.L E:FI' ..

THE FILLCHAIR PROCEDUiRE
aud t.heu ••••• the f Lr st; .53 e.Leme.u t.9 of IS A MRlillER DEM n.re loaded with the eha Tacit: Ers

Ttlie. pr oc edur e fUh
ch~racte!' v.alue,. The

a specifie.d
farm til
I

t'dnge

of

memory bytes l

with

a specified

TnI'" !'TEllO

OF THE PTERODACTYL l"AH1 LY • FILLCBAR ( O.ES i'INATHlN OOUN'l', CrsARACTER

We

cheu

have

the

fo 1l0tlilig l
,DEM{30])

SCAN(-26,=':' SCAN

.... 111 r erur n -21} will
T@I:Ur'11

(101! ,<;.'.

SCAN(15,'"

.

" ,OEM)

5

where [JESTUIATlO~ is o!l var'Lab Ls of allY type exeap t a file type. The Ii ra t byt.e of IlESTINA'fION is the beg! ~Hlj,lI& of rh e r auge of byt es to be t Hled. COUNT is aL~ :btteger value ami Spe"t fie!! the lIumber bytes to

b~ f'HIed.
ill the

GH.AIlACfEEI. is a charec r ~l" va lue to be copied
ruuge ,

iuto

of

i"1ichhy ce

,Dm[S))

will

Tetllnl

3•

BpeJ::if1ed

lHE MOVELEfT AND MOVERJGHT PROCEDURES
ThEse forms pr oc edu res !lJI:e i1aVf;J.P.FT Ilen/ERICAT whe!::e typE' do mass
1lDve B of

... .s PI"I:i f ied

!mrnh ET

of byt es ,

ThE

( SOLIRCE , !JES'l1.NA tION ( S{lURCE • PESTll1ATION

,COUNT ) , COUNT

I

DE.STINATION !l..l:"1l! two va r Lab Ie s of an, t:!,~e exc ep c Ii file bytt' of SOURCE is thE! be,giLllltug of i:hi? rauge of hytellJ whose va lues aT!:' copied. 1'hi!: flrs~ byt e ;:If Ill::5TnlATIflN 15, the bcgd uud.ng of t he ra,~ge of bye C!.S cha t t he 103 1 U e s are CDP :led iln:o. co U~'ris au Iu e ege r aLia ~r~cH Le!; the uumber M bytes 111:) "ed, SOIJRCE sud The first MOIJ El..£f'T ~ tart s f e om the. La f Lef t t n r Izh t , corytLlg byt es of the Di~STtNAT101l r aug e ,
MIlV ~EU r;wr
t

tow:! of

the

S DIIReE

Iut.e nESTINATIO~;

[" CL nge. staniiLg

It pr(lceerls ~t t he left

from elld
11 ,

from :~igh
Till.'

s t~ r t!'l f rOlil t; he r tr.h t eLld of t 11'" <; OURC E ralLge. 1 t pr oc eeds I"tf;hl: ro lere, e!1pyiLJr, byr es iLIUl m~5Tl~lATtON. sta.rtiLL" at the t ('LId of th~ D1":STtN,I,TIDN I:a,lge.

re'If.OLI !ClT hav"llig bot h of chee e i.5 that. the SOlJf\Cf. !'Iud DESTINATiON r auge s rna) overlap, If tiley Cl'/<?rJ",p, the o rde r in Io1hidl bytes {ire rroved

5,2

APPlE PASCAL LANGUAGE

BUIIJ-IN PROCEDURES AND FUNCTIONS

53

SUMMARY
STRING BUILr:·INS
Integer-Valued
LENGTIi.

1:-yped Fll,e

[/0:

Func t Lona e
of strinE' Indceli> of SIRG.

pas {

( STRG l 't'~tl!I"crH: length SURSTRG , S~ ) t'~turr1!:: occur'ence of SUnSTltG !tl thin F'UDC'tiOm,:

Urst

GET I: FILEI]) ) t'IHI.ds cur r ent, U Le t:eco1t:d into w1ndow b sdvanees fUe poiJ;ter. Default FlLt;lD 1s INPUT. I'm:: ( FlLElD )""ri'tU ""hdc"" mto eureenc f:lle re,,=o,rd !. advllrll"~s f He poi titer. Defaullt: FIL.EID is OUTPUT. !ORESll1:l' t'€[urnS an integer value whicb depl:m.ds on stat.u!! of lllost recent I/O operatiop. Value in ;!lero for O'K completion. READ ( [FILElll,] WLs 1 wiu!r<e llBLs means erne or :rnore Wi r'i ab l.es separated 'by comma!:!. Successive values are read hom fj Le
intQ V"Bchbles. Default FIL.ElD is INPUT. FlLUD mw::t be type TEXT (fiLE O'F CHAR) or INTERACUVE. R1!ADLN { [FILEID. i VBLs ) Like. REAl). but; sk Ip.s to beg:il nn i ng of Q.I!:I<;t lim~ af t(;1r re ad I ng va Lue fOl" Las t 11'1>1•• WRITE f [FILEW'.l (£XPRs I ) where EXE'Rs mean'!l eae or iWrll ex.p:teat.liol]~ sep aru t ed by OOWlll!lS. Ilar;:h EXPR mOllY also be follm.edby field wid.th and numher of dec1 mal placee .. E:xpress;iQTI va.iue.s are wrj t ten to :success1v,e file recorda. Default: ElILEUl is OUTPUT. FILEID IlIlJU be of type TEXT (FILE Of c:HM) or INT Eru..C:rr VE. IJii.1TELti [ ( [nUl!) ,,:I [EXJ.>Rs 1 ) I Lfke mU:.TE, but writes an end-of-l1ne afte. last EXPR V!llue.

of

S er ll:lg-'ii'aluecCI.

CONCA']' , STRGs ) returns concat eriat f.cn of stt'ir;gs. GOPi' ( STItG • INDEX • COtrNT ) rel:urns a suhst.ring
of S1'RG.

Procedures: DELETE f STRG • [ND~X • COUNT)
of

j3
delutus
II

Bubijtri~g

INSER'r , SU13STIl.G , StRe , lImEX ) inserts lJ subs t.r Lng 1nto STRG. STR ( LONG , STRG ) convar ts i~tegeJ' or long 1nt~g,er to
string of dcc Lna L di gi t s •

STRG.

I

!~
~

PAG! ( FILEI]) l .,;or.!: res I)~v:h:e I/O:

a.top-af-form

(ASCII 12).

TbeSB 'bu i 1t-:I nfi ar e des cd bed in UNITREAD ( Uf:U1'NlUMBER • ARRAY

de eai I in

the

text ..

INPUT AN D OUTPUT BLHLT-I S N
Opening
and

Closing Files:
FI.U:m

(UNIl'NIJl'mER ; ARRAY, t,.. r< a 'HI [., DNU.BIJ"S'I' ( UNI'Tt.lUMER ) : OOQLKAN U!ITTWAIT ( mHTNUm!ER ) UNITCI..£AB. ( UN !THUMB Ell. )

• L.EN!;TIi

t,

[BLOCKNUMJ'lllR) [BLOCKNUMBRR!

r,

MODEll

I

UNITWRITE

!. MODEI ) J

oj)etls e:ds t li1{; d1ske ece fUe. Dt' :reset:!! po Lut er s to beg.inl:liog if a.Lr eady open. REWRITE ( FILEID • TlTLE ) OpeG5 new diskette file. CLOSE ( Flu=:m I, ar:uml] I ciMel5 Eile. Of lION l!Jay be LOCK, NORl'tAL., FORGE, 0[' CRONCH. De.Eau'l t. i8HORMAL. RES ET TITLE

r

!,

1I

Untyped

File I/O; The.se built-ins
BLOCKREAD RLCCKWRITE rf'!LElLD,

are

deacr fbed
ARRAY. ARRAY"

in dot af I '[n 'the t"'xt.
[, RE.UUICK)) [,REUiLOCKI): mTRGRR lNTEGER.

BLOCKS BLOCKS

(F1LEm,

EOf

[C FlLE1D

) J bco l eBn,

t rue

if end or

file

has been

fl:'achED.

1_-

o~ file ts closed. Det~ult FILErD i5 INPUT. EOL.N [( FILEID ) l boolean, t:ru.e if end of line hall been
De f.au I [ FILF.W is lNPiJT. SEEK ( FILEID, INTEGeR I neves Teemrd.

reaebed-

ijll

EUe

pOllHer

to spedfti:'d

54

APPLE PASCAL LANGUAGE

BlllLHN PROCEDURES AND FUNCnONS

55,

MISCELLANEOUS au IllllNS
A'rAN ( NUMBER fUIlc.ti.GJO of INl'EG·ER.

1

:r,etUrTlIEI a REM. value.

St:amdard

Pascal.

This bl the NUMlIER!I!SY beREII1

JlRCTAN at

l.OG < NUMBERl' returns'

a HAL value,

the

log

base

HI of

rang~ QI •• ~7. ( IlEA'PP'U, ), where llEAPPTR is of type "'INTEGER. Iifu\PPIR if..s .:alle.d by name and ill aet ta l:urrenttop-of .. \l,elip. El:ELEA.S:E ( IlUP .. rR I where ~EAP'P"IR is of type. "INTEGER., The c::urr,."nt top-of-beap po.:i.Iltel: 1.s Set co ElEAPPTR. l:lALT callii@8 non-·fa tal run+tfme. errol::; hal U program. EXr:r eauaes orderly e:x.i t f:rum procedure, :funct.ion, or programMEMA:!lAI:1 ["e'~Ul:nEl an INTEGER value, the "timber of w{n:ds betr.1een t.op-of-stac:k and I:;0tl-o:f-b~ap. GOl'OXY ( l\COORIl , YCOOIlO ) 1I!JJ\!e.9 ElcreeIi curace 1:0 .specified c:ocn:dinat as. X:COOIW is an lNTRGEJl; 1.n 'tile 1'8.o,ge (11.,.,79 .md 'iCOORD h an INTEGER .in th cange (ii" 23. TREESEARCfl { ROOTPTR , NODIllE'TP. .' NAME l l3.ea:l:"c]),'e.sfor N.AME in a binary ~ree. See t.ext f o r det<!il:e" ~K

IWI,!IlER. NmlBER may be REJiL or INrEG~R. TRUNC ( NlIMBBR l rat urns lin ItlTEGER ve.lue. This is U.ke Stal'ldal:'d Pasc a l, exeept; that, N1M8ER may be LONG INTEGER ip!l'tead of REAL. NtJl<IBER mllY [lot axcaad MAXI NT. PWRClE"I'EN ( EX~ONE~'r ) to!tl.!it'nJii a REAL value whichie 1 ~ !:0 the nPONENTpower. EXiE'ONEN'l':is an INTEG:tR intne

BYrlE-ORIENTED BUILl;'INS
These built-ins lin;! d!?!;lI:ribed

in

detail

ia

the

t@xt.

SIZEDF ( VARIABLE OR TYPE IDEN1nFIER ) SCAN ( LII1I1 "PEXPR. • SOllK!;:E ) l'lOVELEIT ( SOURCE, DESTINATION , CQIjNl' MOVERIGHT ( SOURCE • DESTlNAl'ION • COUNT l FILLCHAR ( l:IES'l:TNATION • COUNT , CliARAC'i.'m

56

APPLE PASCAL LANGUAGE

IINlRODUCTION
of the Apple· I';;isc::al Cornpil'eT ts to t.rausLar e the tex:t of a l"IIBC8.L p:mgt"<lm in t,o the I:om.p:re.ssed P'-code vers1.on of the progra.rt.. This P~,~'ode is the "lIilIJcl:Line la.llguage" of til!:! ucsn Pascal int:el"preter or '"pseud.c~'rnal:hine," de~c.rll:led in rt::ne Apple Pasc,al Q.,E!'ra.ting System The purpose
MII.nulli. Comp 11'"e t Operlltf_ng

Filer'~ T jra.nsfe.r C01IlIIland to tranaf ar th<lt t ext file on Co Y01l11:' boot disket.tebeEore compili.ng.. If your ~:rog:nlm req'uires Linking to axt e rnn.L rout Lr Des. _~a. the A"'ple Pascal Operat Lng SyS!;~11! Hanuai. ~
8_&

Mulri-ddve

diskette

on CJjier<l.tion of the CCHlIp.:U~et' are ill the Paaca I Syste.m ",e£~rellce ~!anual: tile following c.wo sece i.cns Oil files needed and on using thl:! Comp!lerr;tr~ somewhat abl'.idged.
detail.s

SYSTEM. EDUrlR lind S'lSTEt].SYN.TAX are bnt.h on nurma I wlti-dJ:ive boot diskeUe., l"ne fHe SYSTEt>l.COMPIL.ER :i,s on diskette APPU'.2:. which is normall)' kJept 1n drive volume illS: in a~1t:1-ddve syst.em. W1th APPLin,; in the boot ''''UTE''',· in a non-boot dr Lve, your syste~ has all the .files , r: 'l!e and ........... d .L ,~eeijJJed to It (un or C(ornpl1El tll(l \i'o:rkfile.

diskeU;e

no!;el AFPLE1:,

ThE

files

which

is

the

DISKEnEPILES NIEEDED
'Iextf:Ue to be Cmrrpil,ed (Atny

dLske tte.

is

boot diskette' SYSTEM. WltK. TEXT"

any drive; def aul.t S I: e.xt. wo:rkfll@
any dr.!\n;!)

'j'lto!o-drive note: If you wish to R(un or C(ll'mpile a tex1::fUe. that i5 no'c lliready on APFLll.i: en· A1'Pt.E2:, ana your system haso~lytwD dr~v'Es, use the Filer's T (ransf e r command to t.rans Ee'l: thaI: tl!'l!;[fi~e cnee el. ther_ .II.PPLE1': Dr .Al:'PL!l::l.: befoJ!"e COlllpil:fi.mg. Another p05s.ibUity fur tQo-dri!.!"e ls . your • boot diskette (jus~ put llJ'PLE0; in d t.ne systems 1.. to Nke Al'rL.EIl: . . ..... boo~ drive and p resas the Apple s RESET key). This [!tees your s@~o" ddve to hold a sour ca or destinatiDn diske'tte fo~ [!ompl.la't1ons" saving yo,u. Er otn T(.ansferrb,g the source file oucc APPLEi: or APPLK2:. AEPLE(jil: does not contain SYSl'.~~. LINKER; if your p-r:ogrBDI(equ1rl:!s hi nk.Lng to e'xternal TOUtines" uae Al>I"t..E1: and APPI..t2;.

S Y:SUI1. COMPILER SYSTEM,. LIBRARY

(Any diskette,

any drive)

(Boor di$k.,tte" Bny drive.; required: only if am)! of the lThlITs in the system Hbrary .lme USBd by the program. See Cbapter 5., (Any dbkette, any !mIt's nat
aEI)'

USING 'THE COMIPILER
Ine
k Compiler is invo~ e d bv , ef Du:termoS[ I:;_'o~malld level "' shows t.he messa,l?;e COMI' 11. INC ••• I:y"i~'g C f~.··~ C(olllpil~ or R for ~.. ~. I;.h@Pas ca.l, sysl:i:'.!ll' The scraun R(un from the irnmedi<l.te..ly

O'tner

LibJraries

drive;. required iLf in the sysrem Hl;a:ary

a.r,~ USEd by the program being compiled. ~ee Chapte. 5.)

3

Ttn.e Compiler
Iil

SYSTEM. EDITOR

(Any dhke
to

1: te

I'

any d.:r1ve;
.round

Of,! tlonal;

f Ix erJ:'ors

by CQmp1.1eT)

SYSTEM. SYN'rAX

(!loot

d.iskette,
give.n

meSlsag@s

any drive; optional on Entering "!lite r)

automatically compiles the .TEXT 1'19.1:'1: of the wrkflle and the result ing code (.t'f cornpilai:iml is !luccesS full 115 tile .COD'I:: p.llJrt of tll@ .... :l:kfiie. o IE there 1s aW!l·rkf:U.e', but you do no t wish t o cO!llpil~ tl1l.at file, use the filer'll N (~W command to clear away the wOl'"kfil'~ b~fGre compiling. H flO"l w!)][kfile Ls ,SVRilable, you are p[Q~pted for oS. sour:ce filena!l!le;
~V~!3

COMPILE WHAT T~XT?
You shou Ld lOesjlol1.d by typing the name of the text file that you wish to have cOiIlp11ei:l. Do No.T type the 5l:Lffix .TEX':!' -that suffiX 18 a"ij.tomat1c:ally sup:ll11~d by the CompUE:!'r', .In addition to 11.[1)' suffix you
1I!aj'

In addition to the above fU,E's., the follo;.tillg files l!l.1y be needed it you !Ire invoking the Complier Iil.1toP!,Hically via the R(un command (Bee Apple P!;tscal Qper-s.ting Sys tern. Re ferenc@ ~!.:!nuB.l[or det~ib;):
SYSTEI'!. LINKER
SYSTI:M. PA.sCAL

sp@cify" you
t

S'{STEH.CHARSEl
One~ddv'e note:
SYSTEM. SYNTAX a r e al] on d rive. 'boot disk,et t,e. U ~di t oz, and 1I(pda t :Lng th.e needed to It ([1[1 or C (omplle C (ompill;! a I;extf He, t ha t

N@}!t. if rhe r e is no workfl1e. f LLe where you wisn to save

loIill

be

he comp lIed

version

.:;.skE!d [0 r the name of '~he of your pIogri9.I!J:

The f:li.l.es SYSTEM. COMPI L.m" SYSTEM. ED!TOR. and df ake t t.u A1'PLE~;:. !o"h Lch is the fiom,a] oneyou have been work:!. ng on a p.ogr'a.m in the work file , your boot diskl!it: te ha~aU th~ files t:he toTol.'kf:He... If you wish til R(un or is no t alre<l.dy on chI" boot disk .. t tl:!, us e the

TO WHAT CODEFILE?
If you s:!.lT1ply press

as you might expect;comp t Lad ver-siOI1 of

the RETURN key ,till! command ~ill pol: be tarmin~ted. Ins t!:!ad, the source file 100'111e compiled and the b your p r cgr'am Iil":lll be saved on the boo I: dbker t e "5

sa

APPLE PASCAL LANGUAGf

THE PASCAL COMPILER 59

workf He program.

SYSIQI ,.WRK. CODIE: •

ThiB :i.e handy

:I.f you

tben

wish

'tl)

R(un tile

po1nting follow~n~

to chI:! symbol ia

ill

t.he source

where the er ror

WIi.!!

dete't:ted.

Th~

an example:
URQR 18 ':

If you want the ,compiled veu10ll of yml'r prograill to have the :'HlmE nama as the. tel!:t vere.ion Cif your prog;l:'BIil(of ceurae, the BtI.ffb ...ill be .CODE ips tead o.E." TEXT) •. just type !lJ dolla r sign a nd preas the REIUIm k~y. Thh is !!!. "'andy feature, 8 ince you .... 1 usually U wOIll't 'to temembe r on.i.y one. name for boch versions of your ~t08:ralll. Ttl", dollot; sign repe~,l:s your e,ntfre source HIll lSpecifica.t1on, ll1r:ludli~'8 the yolullie ident1fl,er, so do N,OTspecify the vo Luae ideDt if ie-r bef o:r,e typing the dolla r a ign , Note tbal: this UBf". is d1f ferent from the use of t.he de l Ia r sign io the
JFllH.

I ««
UNE

s,

<sp:. (CONTImJE Jo.

<ESC> (TElIMINATE),

E{]lU

This show!! that the h£8ck.et:: i :!is 00. :Hleg,a.l eymhcl at this poillt 1m the pros;rall). 1'01.1 have ~btee. cp 1:;1 cnS "'ben .. you. see a message :u.k.e t.hi.~. Press1 u.S, the spaceba:r :instructs ehe 'Compi l.ei': to cont j nile the c,o'mp~lat1mh in CBSi'i YOl!!li'ant to H ndrnore of the erTorll dgh'~ noW. P:fess:lng the .l!SC key ce!u.S'i?!St:Erminat.:i.on of the comp:llat:l on and rl!'lnJro to the Command J.evd. Typing E se.nds you to the ~c:l tor, ~hlch automat:!:ca,l1y .eO!da in the r.1ork.f:lle.readyfol' ed1 t1 Dg. If you wel:e !'tot: CQIIlj:i,1 ling me lIorkf:lle.. the Ed:! tor requ,es:ts the wHile of the fi Ie you we.e comp:l.l:I ng. Yau shol.lld 1:'espo!ld by t:ypi~g the fUellame of. the fHe you were compiling, and that U ie will read lnta e.bcn be r{!'~Hi.l!.nto ~he Editor. When the corr'ect f:[ Le has beea ~he Edito,!;',l:he top UnE o.E the SC1'"eell displays the errQr ml!lllhlge: (or nUl!lber, if SYSTEM. SYNTAX ~as not a,\!a1labl~) and, the curecr i.s placed al: the symbol where the error was det@cte~. If S'lstEM.SYNT.AX ill not aVdlabb.,.
of .Appendix

£:t:I.em3jm,,'"

wan:!: YOUl[ progr!H!i stored under' anot.be]' filename, typeth .. des1:r€t\ Do NOT type tbe suff,Lx .CODE -~ ehae sufilx 1s autolI!BUcBlly supp Lf.ed by the CompUer, in add1t.1on to any suffb; YOu may specify.
j"Ol£

If

,Sy de EauLt , the

['Q1J!,pile. ~lae@6the r ('ode f1.1e at the 'beginning of the spa.ce O'D cite' dhket'te. To oven:lde t:h:ts, you can give ,a si2e ,specification 't.T1th the filenlmle. In t.llts case, you DO 'type the !iI·ufffx .CODE, followed by the number of hlocks 1n 5qu~t',e 1:1I::a~k.eCl" fo.Uowec by a period; large,st unused

I

l

a..

(You may wi a h

t,e delete

you call look up the erro1" in Table 6 the f:i.l.e SYSTEM. SYNTAX to obtai n

OIolfe d1.6ltette

space.)

Thi! pedod ae the end pn:evem:s the :syst~11I :h:am adding the. .CODE prefh a fit: er the dze spe cit 1c,01kin. t The size' s peci.Ut:Il. t10 D [Bl causes the cod~ fUe. to be pbced 1n the fits t .ilocatioQ on :the d.1sk,et te .... ilerE at 1eas,t II blor.ks ~:re avaHable. While the cOlllpller o.f th'E eQrnpiletioll is
!I~,

rt,]J~nlng. messages on the screen tn the fo.U.owing e:",lOlI1ple;

show tl1lElprollrB'3,g

THE COMPILE.R OPTIONS
COMPUJ::R .oPTION SYNTAX
COlllP1ler optjOflS (6 ee the follo'ldng ile,t.t 1on for det~j 111 ere plac.ed 1.1'1 1 U,e tex.t to be comp:U.ed.• and take effect when the Compiler arrives at t:e ,optiop during compiladon.

PASCAL COMPILER II.! [B,29] ,<' Ill>·•• ' •• ' •• TUNA-FISH 2334 WORDS] .( 6:;. .

r

U

LINES SPACE .." 23.%

SMALLRST AVAILABLE

W{lEtJl£

'Compi le'[' op t:l ens fol1ow1.ng fo!:m:

look

1.1ke a 8pecial

ld.nd of coament,

and take

the

The ldentifi'e1t"ll app~j).r-bg on the~creefl are the tdenHfier:!l of the program lind, its p:rn'cedLir~s. The 1den'ttlie·. for a prccedur e is di,s.ph.yed at the moment ~hellJ compile!: 10'n of the jjro~ed u.e body is at arr ad •
Th~

!lumbers ithin [ J indica.te [he number of (l6-bh) wor'lia .!ivaHable fOl!' sy~ol table s touge ,at that POillt in the compiL~itio!1' Ifthli.s n~mbe'r ever :falls below 5S~, the compiler will fail. You must th~(iL put the e,w~pI'1~g optioll (dlls,e:.rlbed !'lela!;") 1.oto your p r cgrsm and !:ecomplle. the cur rent line numbers., Eadl cl.;!'t
Ld.n e cOllIpiled.. ...1,11 show

The Compiler
~ ,cllarat. te:!': (*~G-c,lrl (*

erea

til

As ,ShOIombelow"

[here

materrio 1 ber ...ee~, ("$ and *) as a C'.olllP11er option. must be 1'10 :lipa,~e6 jn ("~ or ilDIled:l atl;!ly aft:er the Uus is a cOfl\pUer opl:ion. this :Is a COilliilent. This 15 a COMIIl!nr.

Th~ !llil1lbers encio:~e~ l>'iULin <: " arn o~ the se ",een. rep resent!! OnE source

<"$

$G-*)
G-*)

If the Comp11er dut ect s 0'10, error 10 your program, the screen th~ text prec~d ins the. e:r-rllt. an erro, numbe r , and O!marker

««

60

APPLE PASCAL LANGUAGE

THEPASCAl COMPtliER 61

SevIOil:alop

t.io!]s

separating

can be eornb:lnl!d In one set af (*$., •• "'l bca,[,'k,ets, ~he opt1ons wHh CO~II>l (dau't add ~·tril spaces); opU on*) [he

by

THE >IIGOTO STATEMENTS'; OPTION
Tells
S'tBU!1l1i'"nt

("'~QPt:[.on.

Ex~mllle: optHm9
~ha'~ Involve
rullllll!S

the Compile'!: wbe'~heT' to withs'n a program. value: Allows G-

allow

or forb:! d the

use oft-he

Pasua I COrD

You can't do th.is with c:han~c t:1!:rB. A !J;iv'~n option

or st rf nga

of

Default

at any po.:[n[, Jn the compIhU:on. The co'mpi La II: 1 On Ls aff.ec::ted Oflly fr-om the podnt whe rethe np i;:! 00 i,~ tUl:cu",d 00 until dIe po:hlt where the uption ss turned off :J8,a:!u. ThI.l.:S you can tu rn an op t f on on (or off) just ~U'!::I,fi,g the, compilat:i Oil .of a partj eutar tout1 ne in lIoU r ptogriillil.
00

may be tu med

ot' off

(*$G+*) ("$G-*)

t-he use o,f the GOTOstatement.

Some opti ens requ~, '!:e a f:L Lcna aa immedj ately fol1ow:l.ng tlI~ op [:I, on let cer i nst aa d of the usua.l, + 01:'-. In thi s case, al.l cha rac ten; be tlllE,en the 01' .100 L:! t ter . snd the d.os:l ng "')a.e taken as the f :llena,tlll!; axcapt that b Lanks pre~e~hng or follllw:!"n,g tl,~ ftlr.!nalll8 are ignored. The.'!:I!£ore" the filemlCll@ trust h@ the last item before 'the "'). If tbe i'i'r'9t chaeae eer of a f11e,n.ame :Ds +0 r -, lUU mmH pl.ace a bla:~k be t'We,~n rne op t Len 11" t er t and the filename. For eJI:<Jn11l1ea of specif)!] mg a f:i le[D.al1l@. aee the Slect.:! OIl dm'lcr:l bf.ng t,h@ r~~lude-f:! Le machanl sm.

T(!oche'ts !lIomed.mes use t'llP G- option to keep nov Lc.e programmers using th~ (',{lTO s tateme.nt ...'he re roote 9 t.T1.! ccur-ed approa~h,~s using ~<'HILE"or REPEATs ea tement s would be mo.e appropriate.

from

FOR,

!ill
I I

THE iiliO CHECK" OPTION
this option 'tells the comp:l.ler whether or not to ~:reate Err()r-che~kin8 code at teL each s eructu red filll! I/O 5 ta'~ emlln t (not the BLOCKo]!'UN It I/O s t a I:Ement.s) • Default value; 1+
5

~"

31
Pa8cal,
or

Ins truc:t

the

c:ompil.e

r

t,Q

ge.nel:atl:!

cnde

af ter

aach

In Apple
ee!llllleni:

<:.u];'1y br.3JtkUfl

and}

lire

equ:lv!lleTlt

to

the

Q,rrrnal

and "'I • Tni'" ell!:ly brackets cannot; be genez a ted by the Apple kayboard, ,So no COnE'IIS,:!on Exi,sts for programs written (}n the Apple comp~i:;er. How@v@r. other terlllhlah may h~ able to, genar at e til@ curly brackets, l" programs. These programs will be E!XecutEH'I con:ectly 01] che A:~p Ie. but the curly braclH~[s

i'i 11 be d i ~played on AppIE"S screen as square bt'ack~'t5 [ and 1 .'
o!~t,l On deLl mH:e r,S ('"

st,st,e.ment which performs any 110" Ln order to check ths t the '[/0 operation W<l.,s acc.ampl:lshed succe:olS fully. 1t'1 t.he case of ail, uns.uc cea s FuI I/O cpe r a t Iou, the prQ&'rarn will be [jHm:i.nated with <I, ruo-time e.r r o••
Lns t.ruc e s tn,(! Compile'! net co g@neratE': any r/oche ck Lng code. In the case of an 'unsuC ~ell5ful I/O ope ration. the 'p.ro~!l:am is not tero! Oil t ed I,Ii (11 a runtime, e'1:r01". Tl1e ("'$1-*)' op t Lon is IIseflll for programs .... here I/O che ekt ng Ls >lot des I r ab Le , or which do the Lr own cha d.ing v:fi.!lJ '[he Y.ORl;st1 LT f unrt 1.01:1 • The progr8m can then de t ect; and :rerHlI"t the 1/0, e1:"!O';us, "'itho~t 'be:il'[Ig ti'"Tm1.natiEd abno rtna l Ly with a ",un-time err01:",. However; the Ihs(ldvantage of setting the CiI$I-"') op t Lon is rhae 1/0 en:o["S, {aM possibly seve'!:e

THE "COMMENT" OF'TtlON
Th:l s np ~j 011 coned s ts tli rn!'! let ~er p Lace d , charae,ter ,f or character, 10'111 not. affect pr()g~alfi opecat EJ<;arnple: ("$C

and a li PIe of in Block I! 0 f the

c:

text Ie code.f,J!If! (wheel! :It
text. The

31

copyd.gbt

eo t dce or other
COPYRIGHT

t on), The j:I1Jr~Qs(! of this is to 011l')w a comaarrt co be emheddecl J~ the cod~jlg.
O. I"i!,NSOI'lE 1979;1)

pr og r,am buga ),'

may

go undet e e r ed •

ALLUVIAL

THE >ilINClUDE FlUE" OPHON
Th.e syn ~ax fer ins t rucr Ing im:o the cempLLa r ion :1.5 as
t heCoJ1pilf!

r

to

ill.C1.11 de

ano~her

source

file

follows:

r "'$1

f Lke.nane

ji")

All cha rae t e reb!! tW~f!n ("'$1 and *) II ire t aken <IS the :Hl ena1l!EC' of ,souTc::ef He to be tnc 1u~ed. Thus , the £:i l e name mus t be t hI! las

th!!
t

:it em

62

APPlE PlI,SCAL LANGUAGE

THE PASCAL COMPILER

63

before the *). i~nor~d,.

SFBces preceding

tbe (ilename

and following

it are

The following will c::.alllad UE~OLTEXT

caUSE'

On

the

the compil,~d listing [0 be sent diskette named MYDlSK:

to ,lIdhldile

Note

that if the fh,.,t cha,rBJct~r of a filename ts + or -; you MUSTpb~e ~ bb:k space bet .... een f*$I and the fllenalli@. Also. yoo may ,not: use the CH : !lot II ttpn in the ffJ-ename to ape c:i.fy the beet diske t te.
l:f

Tn'e sp.ecified filenam.e, which l!IuSt be t ha last itelll before the "'l'. is used e:!["actly as 'typed" No sU£fiJ!; is added. Note that a dish!tte listing file rna)' be edited just. like allY other text f:lLb. provided the filensme which is specified contains the: sulf1x .:tEXT.
I: he Compiler p,la,ces next. to eaeh aeurce line numbe!:" proc,edur,e £lumber, and the nU1riber of bytes Olr '<lords {bytes for code. words for data) required by t ha t procedure's dec1ar8CilYDS or code to that: point. The Compiler also ,:Ilndicates !.lhether [be line lies withir! the act.ua.I code to be axe euted 0]" ':1,,5 1;1 part of the decIar,lOtio,M for 'that pra~,ed.ut"e by printil'lf, !lJ liD" fo]" lIec la;[';:I. t:fl.on and an i.ntE!g€t' ~ •• 9 to des lina te che level of !! tal;ffi1le'ot t

I.n the compiled
11ile

lis

ing,

the initial attempt to open the file 1<Ihich 1s be Lug included (also calbd the "Lnclude fi.le") fails, the Campile:r concatenates the suffix .TEXT to the filename and ries again. If this second attempt fails or .if some I/O erifolt occurs wllile reading the include .fil!.e'; the' Compile; responds with a [e!!,tal error PlEssage end t e rmf net es its operation. H the include fUe option nc cur s within th@ body of a ;procedure or wi'thin the body of the IlIs10 program, t.he includ ftle must not eont.a t.n any USES, LABEL, CONST. TYPE, or VAR declarations_ Otherwise, the compiler mccepts include files whicb eont aLn .,uch ,cleclar-atioll!l even though the deocLa[.'ltLons of the: origin!!l progr&iJ have already be eu c:ompl1~d. The CompLl,e t cannot keep track of rt'l!.lI t;,!!d include opt Lous , 1. e. an include file must not cent atn an i.m:lude fil~ 0pC),OIl" This results fatal Compiler error. Ine i,nc'lude file op t Lon ma,kes :it easier to cOl:lplle Large programs w:itnOUI: having the. entire source in one vary Large HIE'. This is eSFt;!c1ally useful whee the combined Ule: 'would be too large to edit the. @.Xis Hog Editor's buffe r. .

the

n~!!Ibex,

aegmant;

'Illes ti'l!g "":[thin Here. ill
II

the. code pat[.

sample

listing,

to ~hich Lexical,

colulll.D hl!adlinga

have

been add,ed,:
Program

Source
H_'Ille 1 2

Pr ccedur e Segment number nUP1!!e:r 1 I:D
1 ;D 1 :D

le.vd

r,;rithi.n

Byte numb'er pt'oc.ed,ur,e
(lI.$L

text

SCRA:rCK: LIST 1.TEX'I*)

:to a

3 4 5 6
7

1 1
1 1 I:
[

1

1

PROGRAM DOCTOR~
VAR DAY,CURE;Un'EGER;

lID

3

1:0

2:D

5 1

in

Z:~
2:1 2:1 2:~ 2:" 3:D 3:"
3:1

G

PRO CEPURIE 'nOSE;
BEGIN

Itl

8 9'

I

1
1

26 43,

o
t

ti.1RITE('AN APPLE A DAY'):
WRITE(' ENDl AND .)

THE 'llSlltNGJ! OPTION
Controls whether the Compiler
L01'1

11

1

56

wi.ll!. generate

a program

l:i.ating .•

D'efault ('*$L+o!: )

value;

Ins t ruct.s the Comp He r to IU'lVg a compiled lis tillg boor diske t re unda r the filena.me 5YST~I. LST. TEXT. Tel Ls Compile r
I:Q

the

12 13 14 15 16 17 18

o o
11
11 11

PROCEDURE TREATMENTj,

BRGI:»
FO'R CURE: .. 1 TO 4 DO

1

1 I I
1

3:2 3:3
3;2 3:il .'l:~ l:~
];1

IIEGIN

211

19

34

13
~

nlD:

DOSE END

(*$L-"')

make no compiled to save

lis ring. 11'1the be aant; to

(*$L [:HellamE'''') For e.li:~TIIp Ie , the the prlllter:

Tells Compiler spec Lf Led file.

cOll1lliled llsI:11lg

2l 22 23 24

f ollo~lng

~Ti,11cau se the compiled lis ling

~(l

25 26

1 L 1 1 i 1 !

11
13 13 15 35

tt2

1:3 1::3 l:~

1:2
th.i!'

!tGIIl :FOR DAY:-Iil TO 25 DO BEGIN TREA:rMDlT : IIlRITEJ:.N(· ') .END

35

END.

(*$1. PRINTER.;*)

Th@ iuforcJatioD given in debugging a large prograllh segment ilumber. procedure

eompd.Lad lis'c.ing can be very va.l.uab le .for A run-time error m~s5a,ge will indit:ate the number, and the offset (byte nUIliber 'within the

64

APPlE PASCAL LANGUAGE

THE PASCAL COMPILER

65

cur r snt

procedure

l

lo.!nelfe the

,!"rrDr 0 t;'~l.Irred,

Def au 1 t .... aLuer

Qto suppr es s output
to

Causas the tmnpUe!: EXEC
TYPE

the

SR 1, pI 7, I' 56
<SPACE> TO CONT[NUE

ERR II 11'1

sc .een.,

1 "'$Q-'" 1
number ,alld occurred. Ii!- La
Til ill is []Iostly
1.]5e

Cause!! the Compiler to send lli ne numb!" r meaGages to the useful ...hen
t h e CONSOLE; dev:i.c~

procedure sc reel) • is nut che

name and

where' all Is th", J!legment numbe r, PO Is bile procedu.re the byt:e rnnabe.r in that proce.duce !.rheci! [;he error'

Apple· s TV

o r !!IOni tor

norme1

:.cree;; " for I"..xarnp l!.e if YOu are \.!sj ng;!I print w';i. th yml:r Apple. th ts opt ion is not need .. d. e

Lng t e rmillal '.

In

THE uNOLOAD" OpnON
co.de of a UNH' used by tile pro,~ra,tn (see Chapter 5) frQll] be Lng kepI: Ln meTruJJ:"Y whell t.he progrsCl 1s executed. Ins tead , the UNIT'!I code is inmErno ry Qruy wh e.n sCl':le port Ion of 1 C i!l!lJct lve • Def au Lt value:
N~

'This opria~

pr evane s the

THE 'IRANGE CHECK" OPTION
With the (*SR.+"'l opti(]TI, the Compil'~lf
Oil

""ill

:ptod.uce

code

w'iliC'.h che-cka

on

ar~r.1y and s [ring aub.scr.Lp ts aed a.nd s tri nil; types"
Defaultvalu!!!: RT

~s Signrnent a: to va r I ab les

of subrange

UNIT code will IlNII code will
b eg Lns
execloLt

be Loadad only be loaded
Lng , as

Wh~D, ac t iVe.,

(""$1'1.+*)

,~iJon as program
TUl"ns range the main prevent the du€ckirtg off. Note that programs compUed ,.,ith r he (*S:fI~1I) option 5e.le~'ced will nil, sligh tl)' fas t er. How~ve r if an inva],id index occurs a f 0.0 i nva 1 id as sd.gmeent Ls made, ttle p rogr am will not be te'rrninated .... t'll .a rUQ.-1:.l.llle i error. Since you. should never as sume r.hat s, program 16 abs:'Dlutdy correct, use {*SR-"'l cnl)! ..me., speed i5 crIt1csl.

Tile (*$N'oI') op't'ion should be placed at ~he beginTIing of program. I"ote thai; use of tile (II"SrH'~") option doe,s [Jot in! tia1izlH fop po:rt ion of a 1Jl'llT h:QJI. be in!1; exe cur ed •

THE '~PAGE" OPTION
If a lis I:iI'l3 i~, beLng produced, t.ho l' op t ion COIU ses on ec io!"rn-f~e<l (ASCI 1:. l Z] to be Lns e rt.ed in~o t he text of (ne lis~i<llg, jIJ5t be f o r e the line t.oQtain1ng the P option. For example, H your Ill"ogr'am contains the lin,!'!

THE "[RESIDENT" OPTION
Th1s ol'tiol'l fOl"cesc\le code of be Irep t in me mtn:y, fc .. as long
is a~tivlE:.It FMCEO'UftE or
,'3

",.5

("'SP'" l
that lin~ ?1"ogTBm's will appear at the compU ed 1:1,9 ring. top

~f a new pai~

when

you

print

the

THE "QUilEl COMPILE" OPTION
The Q Compiler op!tlon ts the "quiet compd Le " opt1o;'i suppr@ss the screen !l)(!Ssage5 that [ell the. pTocedu:re numbel''' !lind de t e.Ll, the pr ogr es.s of th'" c omp Ll a tiOll. which
nanes can be used and line to

ctI[l '~hI.lEl OVl'!rride P1JtlCTION (se f' Chap t c!' 5), and the ab,) toma:Hc '~wapping out of a UNIT CIH; sed 'by t~le ROL.OI'ID Dp i: Lo'n (5,!Hl <lb(,-.'e). FOT example. suppose ,thO!t~iOB

1s a 1<1 r:ge SEGMEN FI1:0C"1lll F. -Normally T Ull H is Ln llI£'l'l'Ctry only ,,",uen t t 16 ac t 1ve (t hl.lB allowing the melllory space to be usee! fa r 'some th ing elfle), But anet he r tl1"o~ed!J.]"e. RNI"S,. ~alls ~!OBY repeatooly. We don't want the di5~ d.r! VIE: to 'be whiz~ing !1DBYin <l rid (JUL of l~el!Jory each tdme RATS calls Lt , SO ",I" make NO~'t· a "r es Lde nt proceodure'" within RATS:

specified maT or SEGMENT pl:acedute to the p'[Dcellure t ha t: cunt.a.Lns the 01" t ion the an comat Ic sloIs01ping our. of a SEGME.I<lT

P'ElOC'ED(JltE RATS (HATS,. BATS, VAN FOON, ~1OQN: STRING;

CATS :INTE;GER)

;

BEGIN ("'SF.

MOBY*)

66

APPLE PASCAL LANGUAGE

THE PASCAl COMPlLER

67

THE IOllISE lIBRARY'i OPTION
This Tbe re,8id~lIt oj'l t ion is d.e.scribed above , also ~se:ful
iii connect.ion

wi th. 'thl!! nolo!'ld. 011 ion t

ccme:ists of rhe letter ij and II if lename. the !l!ulled file library U Ie illl I'Itdeh s1i.Ibs<l.qunt; U SEed UNITe lire! sought. ... 'Fbe ,erpecif:l.ed f:[ l.ena.!I!~. whicl1 must be rhe Las c Hem. 'bef ore the *). :I s iiJJsedi eA!'Il:'tl'y all· t.yped.. ~p suffix is added .•
bOl<!Om_es the

opti(l1!

THE uSWAPPING" OPTION
dei:eIlllines we.ther ot' not t he CompileJ!: ope r,ll t.!!B. h. mode. There a.re 'two main pa rt 6 of t ha Comp:11er: cue pro.c.esel!s d.ecla"lu:iona; the otheT' haud Laa B:t.atements. In the s+ Bwap p·ing mcde. only one of chesepa rt Iii isin~in Ulenwry at a i:iP1.e. 'il:h:la makell about; 391'i!l additional 'wo'l!ld!!l8vailable for aymbol-tabloe ..,tora&le a'C t ha COBt of ~lower compile t i.ol!.speed (li.pproxima.te:ly J~~ lines ,mil'lU I:e 11l. S- mode. verstJsabotlt lSI' line.!! lminut e 1;;1 S+ mode) 'tiecau!!e of the overhead of swapping the Compil",r se.gm.ent!!l In. from disk. TIl.is option !!mill: OCClIr bef·ore I:he COlllpile.r I""ncounters any Pascal .
opti?,D .BWIi.ppbl& symt:a,1l. _

?;hi.!!

The de.fau:n..t fHename forlbe l.jbrB.ry 19 SYSTEM.LIIiRARY. en the boot d 1skl!t ts. If any USEd UNI"Is are 10 the boot d:l8ket te'!I SYSTEM. LlllRARY J and you ~efl;lr '~o ehos,e UNITs fir!Ot. you do not 1!1eed thl1' [jse-librlir:y COIIlp11eT optiOll. for those UNITs" See Chapt·er :5 for O!Ot'!:! deud ls on UNIT!!Follman.!!: is <ill example GOlllP He:!: opU on; of a valJd USES clause emp:ioying the U Hll!nacne

lJSES mIT ~ ,UNU2, (ItFOUND IN *S·Y.S.'Iru.l:. LIBRARY"') (""$U M'nl is Ii: ;:0'\. CODE "') IJtl1T3 ,
(*~U APPLEl:1I •LIBRARY *)

UNlT4 • !J1U'I'5; Note:
][11,

II. tJ filename.

opthi'IlJ,

yOIl. may DOt use

rhe

*

OT

*,.

not!l,UO[l

to

spec..:i.fj' the

boot

diskette.

("'$S+"') ( "'$8-"')
<~$fH-I;""')

Puts

CompileI'

1n swapping

mode.

Cm!lp:!.ler .doles eVI!I1. mQre sW<I_pp1il8 than with th~ s+ op t 1011. The progr am C crmpiles !Hill toore. '" lowly. but still mere roC!!!l 16 left in lll-emcry !for symbol-table
stOlt'ag .. . e

Some jlrogra!ll8 require th.e Camp:! ler to access ano'rhe r dls1cette file for eX8.Wjl:le,at1 ,j1ilclud·e" .fileWhen th:ls ;I.~ done, 2K of memory hi r'equ1l1:ed for ~hl! diskette d1:rect;crry. U 'I::be progxam :tevery large, ads Ildd1t1.onal memory 1e not. avai labb!!lJnd the c:omp11a.~1on f.a~ la.. If t'[d.$ nappe!!;!;!: to yo·~. b,y the fQllQw1ngt:e,chn:ique; Use the Filer' ~o1llmand l1(ake to (;TIede: iEI. q-bl·o~k file named SYSTEM.• SilAPlnSK Oil. the same d16ketc~ that c<:l1'ltg:inll the CODl?l. li.er" Now, when tbe ,CQ!l!PUer re!l;(js !'i d1ake!:t,e fiLe dudng compile.tfoVi, it \lill write out 2:K of 1n1ormat.:ion hom. III.!!moryto S'{S'r.EH.:BWAPDISK, ChUB hee1ng .2It of memory for the d1llk·ette dire~~ory. Whan the diEikett,e~.l:reCl:ory is 110 longe.rneeded.,. ·the LK of 'lln.fonnO!lU(l£l is n:ead back~nto memory train SYSTEM. SWAFDISK.

THE "USER PROGRAM"
T.his o.p't ic·!1. comp:Uat.icn. D<l.fault (II:$U+I<)
(j'E!

OPTION
thi~ cClnrpila t iOI] is of a. sys [eJI].program. a useIr program

t M1!:rmines 'whecther U cO'mp11atio1!

or

value,

U+
t ake

Infotm8 the tompl1,er that thiB cllmpila.ticlQ is to 'place on '[he user progl:~111 lex lE.v.ll;:l..

TeJ..l.s t.he CO'tIlpile·r ec compUe t.he p"'ogram at the sys tern lex levd. This BiO.tt:inS of thE! (1 c01Ilpl1er option aho cau Bes the following cp e tons to be ae t: R-, CT, l~
[\lOT!: The U- option. w111 g@nerace N'ogra.P113 thllt do net tx!.have as expect E!d Net recommended for nD'n~sy5 tems work unl.es s :rD~ knllw it .. • mJ;! tho·dJ of ope t-at ion.

68

APPLE PASCAl L1\NGUAG:t;

TI1E PASCAL COMPILER

69

COMPILER OPTI'ON SUMMARY
ALi Comp tIer
>;·ommen:ts";

op t Lona

,are placed

1n tne aour'ce

I;ext In

"doll,l"r-sj

gn

E:o:ample8;

(1I$G-*)

'''.]1

WRTtE.TEXT

*}

l:o~ojJil~~-opl::lc)r1 sp BcH ieli ~f ons bracketB:
(*$op tlQU, oprJ.o(n,"') If a filename is speCified.

may be combined

in one Set

of

C"'S •• , .Jo')

Example:

(*$F-,S+,G+"')
t.ht!.

H. m~llt be the IIlJ.st item before

-It).

Foliololi nil, characte.rs G+
l;-

are

p.Iaced
(defa\.llt).

df !:'cc I:ly

im.to ~odcl He.

Allow-s ClOro suarament a , FOJrb1 da G01'O 9,[atolOents Generates VO~r:heck.ing [l"o I/O checking.
j

1+

I~
I

code

(default). eomp I latl
Oil .

f

lellll.mE

Inc

Ludes

named

90u[Ce

iI Le fn

L+
!,-

L f11ename N+

!lends Hakes Sends Pr evenr

C"HII,Il Hod lis t:1 ng to no compiled listing c{JmpU.od UBl:1ng to

SYST'EM.LSr. 'rJ:lXT. (d.Efault). named file.

on boo t df sk ,

N-

I.oads

murs
s s es

s lJlHTs

f.olC

be] ng

i=ecl:latel'.y

loaded klU1::J 1 <Iet:! vated , .... hen progtam runs Idefault).

U,,!+ -

Supp

r'e

Sc.(een

messages. and n~

Senas Ii race dl1:re Mines Geners

l.i ne numbers to CONSOL~; (di"f au Lr code (def au Lt.) •
cu erane one is a.c.tlve..

j

tes r~i1ge-dl.ocki ~~o range chedi.:lng.

Keeps !:lil!tIled proce dur a loade<J whlll:! $+ Put s tOIf1p11el' :in suapp f Jig mode. even !lloDTe swappi ng.

S,++ Campi let" does s- L,Qn-'swappj ng .mociE'.
IJ+ u~

Cotlt~lles
Cotlp.i les SpedHes

uaar
~ystelll
irna"lC

program of

{de.fauh program."

I.
for fJnd1ng
Ut>lITa.

U .Eilename

Lrbra1;y

file

10

APPLE PASCAL l..Ai'\lGUAGI:

PEas 71

Apple Pa.~clI,l suppa!!: ts the s;eparat ion af procedures ,and fuoct ioos, or group.s of t.h I;!ID , from the main pJt:ogram. Wh,en you are developing a large or complex program" tbis can be very u!leful aa 11: allows you to :reduc.e che size of code files, to eaduee ~he memory space used. by the pr 0 grill!! , lind to use a Bec of proc@!ci:uresand functions 1n IOOr,e chan cne program. can he achieved both a,e t:JH! P-,c:ode level .mc! at the. lIourc:eleVB1,. At the P-code level i a.ny' procedu'r@ or f'uncl:1on CAII be designated aa a SEGMENT. The result is that Us code .19 not loaded into lliem0tJr until it 18 called by sOlllle other part. of the 'program. As aeon as the SEGMENT procedure or function is no longer active. it i.!l "swappe.d 011][," t.hat is. its memQry spaee 1s mile =aileble for SOIl!e other use. sueh as dynamic memory !OU.ocatioll or swa,F']Jing in aneeher SEGMENT. This t echni.que iEl BO'IIlI! times, cal.l.ed "over lilY 1n 9; • " Separation
l.il.l1gl.lage A't

Filla.,lly. there is tlie EXTERNALmechaoism. 'l'h1.s allows a procedure or func.tiontc, be declared in a Pascal noat program. IO'itho[l[1:any Btat:e~ents el!(&ept, a head1.rLg and the word EXTERNAL. The procedure or function is implemented separate.ly i~ a:s5embly langus,le. I!;!lsemb l,ed. and tlle:~ llllked i'nto the host ptog~SIli with r::lle Uil.ker,. This call be advantageous, ,for 'proc,eoduree, (It' functicfiB whicb aLllI t run .very lEu, c-

the source-language level, a liiroup of on!! or IIIOre p,rocedure,6 or func'tions can be compiled separately ase. UNIT. The 't'esult of compiling a UNIT is a li'brary Hie: it can either be used directly or incorpora~l!d into !lome ot.he r Hborary file such as SYSTEH ..LlBRARY.

Sepi1.rars compU.ation has a~veral advantagE!8 in the deveio,pmE!J'!'lt of any l,use O~ comp,U.cated, progrS'[lh because t't allows you 'to approach the task as a group of smaller tasks ~ich are linked together in a simple and logical 'way. Several of the powe..ful features of Appl~ Pascal are implemented. aa UNIT's, as we will sae in Chapter 7. To USB <! !!,eparately compiled UNI.'I'. a program 1IMst contain II USES dacLar-a eLen wi th the Dallle of the UNIT; 'tile, program is t.hen taIled a host program" There' are two killds of UNITs: Regular tnI1T~ and Intt'insic UNITs. 'When a host program IJSES Ii Rli!gularUNIT, the UNIT"s code 1s Lnse.r t ed into the host pt'ogrl1lll's codeflleby the Linker. 'Th.i,s need only be done OI'lCB ullIn,a the UNIT is 1MdU1,ed, and, recompiled; then it l!I.I5,t be relinked iota the hesl: program. Whe;o a hns t program USES an Iutrinsic 'UNIT, t:.heUNIT·s code remains in Hs libra.ry .file and 1.e, ,iiiu.tomat1cally lOB-died into memory when the bost: program [s executed. This keeps the size of the host program's code.file deen, IJhich 1s part:l.cularly :l.:m,partant if tllB.nyprograms use the UNIT. It abo, aUow's fhe UNl'I 1:0 be' modified and re,compil,ed wi thout the uaed to T eli nk .. The. Co!!IPiler' a NOLOA!)I and REsmE.~ op t..ions (see Chap ter ")' allow funhe. control aver the handling of IutX'ins,ic UNITs and. SECMENT proc,edure.s and fuuctions. NOLOAD pn~ven,ts any UNIT from being automatically loaded until its code f.s act Lvat ed by the hoar program. The RESIDENT .option can !ll()d1fy the e.ffec't (],f NOWADor of .a S~GMENTprocedure or function; it forces a procedur a or func 1:1011 1:0 be kept in memory over !!I B,pecif Led :raoge of program execution -- sp~cifical1y, lIB long aa the p'rQcedure O. function c,o'ota.1Illing, the RESIDENII' op cion Is active. the procedur'e named

3

in the RESI~ENT option is kepI: in memory.

72

APPLE PASCAL LANGUAGE

PROGRAMS ~N PiECES 73

SEGMENT P'ROCEDURES A!ND' FUNCTION'S
D~clarat1olls
ordJ.n,ary Pascal procedures or f1lNCTION is preceded by

,LIBRARIES AND UNIITS
50 far. we hav,e seen Pascal progra.ms ""hich are compiled into code.filesl codef:Ue can be ll(u[I or eX (ecut ed • Now we will eons Ide r !INIts. which a'I'~ compiled Lnco libra.ries. Two or more libraeies can be. cO[llb1.ne:d into one file. A library is not R(un or eX(ecu'ted; instead. 1'1: 15 used by one '0'1' mrs p['ograms.
II

of SECMENT procedures: and :lUlilct:i,OtlS are identical to and functions exc ep r that the word I'ROCrnURE the ward SfCMENT. For exam:~le:
j:

S[(;~~,"I'IT PROCEDURE: INITIAL IZt: Sf-GIN (* Pascal staterJents *)

ENDj
SF1iI!OlT FUNC'I'10N FFT(nml}.tNlNPTF): Nl'TR;

BEGII'l

END;

C*

Pascal

statements

*}

c.onta1ns code for Ilrocedure.s and/or functions wbicl:J a;re to Bny Ilrogr.am that uses the tlbn!1:y, juat as if they wer,a defined iTl the progra11l itself. for exam'P,le, the l!pple Pa!'lcal S·yste.m comes wi till a HbTSr)" ca.Ll.ed SYSTEM.LIBRARYwhich contain.s code for several UNtTs; one of th~ UNITs is called TURTLEGRAPRICS. ~nd it prov1d,es a !let of procedur-es and fUllctions fo''r bigh-resol'lJJti,oQ graphics on the App~e. To use these procedures and fUDctions, a program need only have t.he line

A Ubrary .!l.vai.labJ.e

d'r:J~ not differ; ho;.rev€.J;, the code and data for. a SF-GHENTp r acedu r e or function are in mew],!:'y only whill! the pro~edurlO' tunccf on Ls ac tuaLl y running. This can be IIJOdified by use of the Compiler apti~n (*S~ na~e*) as explained In Chapter 4. lin}' procedure or function de.finiti(]n 1M.), have the word SEGMENT. This t nc Iudes FORWARDde f ini t ions ,:I nti nes t ed de f i 11:1. t ions ,
The 8dvantag~ pr ogr ams into

Pro~l"allI beh a'v ibr

USES TURtLEGRAfHICS;
01:

aft er [he procedure You

progu.1Il headingsuch aa TIlRNTO or

The progT1!m can tllen MOVE.

use

a TURTLEGRAI'IfICS

can creat.,e and comp.Ll,e yoirr own. UNITs, and either add them to' SYS1'EM. l.BRA1l.Y Q1' bud.Ld your own Ubrarieil L by Ulling the LlBRARY ut.;l.lit-y deseri be.d in the Apple Pascal Opera ring Sy5 tem Ileferenee Manual.

of using SECMENT procedures is th~ ability ~o fit large the Ilvai1able memo ry , To W'lrite such a progralll, divid~ it

into two or mPr~ main tasks which aLe lmplern~nt~d as SEGMENT procedures. To be- ef fe.ct Jva , each SEGMENTshould be substantial in siZe and the, program should be des1~ned so that SEGHRNTs are not 5wapp~d in and out too fr~qu~ntly.

If Ii. UNIT used by your program is contained 1n the. 5YST~.LlRRARY file. a R(UD cOIIIIIIiInd ill aU1:omat:1cally w invoke the LinkeI' to do the necessa.ry ~in.k.ing. OtheN:i5e, you 1!IJ5t explicitly invoke t.he l.inke.r. Note that i.E che UNIT is uo t contained 1n the SYST:EM.LlB!lARYfile, Y!l1J1III.l5't use tbe (*$IJ filename*) option of the compiler to tell t.he- compile.r which liL~rary HIe. con~8ins the. unit,. Tb.e (*$U fUenam.e*) 1s placed .anywhere' before the appe.ar,!l.n,~e of the UNIT naae 1n the USES deci.aratilln.

REQUIR'EMENTS AND UMITATIONS
The disk which holds the code file 'for the program must be on Una (and in the saIni! dr I VE' aj; when r.he pl"ogl"am ...as s taned) ""henever one of tile SEGMENT procedures is to be. called. O[;herY1se. tbe sys'tem will a.t t.erap t to r~t:rieve an.d execute whatever information now occupies that particular Loea r Icn on t he disk now in .ha~ drive., usually .... t h very L displ@<lsirlg results.
S!':CI'IENT

UNI1S AND IJSES
The source text. for a UNIT hall a f'O'Elll somewhat similla.r to a Pascll.~ 11 t'ogram, as exple..1ned in detail f1lll't'ther 011. 'Bri~.fly, it consiB,tll of fOUT parts:
- A heading. An INTERFaCE part carmmmic.ate.s with

code-gene

p ro cedur es muS!: be the rB r 'tnS s t a cement s ,

firs

t

p;rocedUI:e

declarations

t.ha t; cnnr ad n

which defines the procedures

the 'ila'l 'the host program and funct; i006 of the. IJNTf" "the procedlmr@s and

- An IMPLEMENTATION par-t which d~fine8 f~ction9 them.selves.

- An lfiifii[ializat:ion" which cOIlsists of a BEGIN and .a.n KNDw:ith any number of s t atemae t s be.tli'e.e.n [Item., Tb is 15 thee "1lI!!1.n program" of the UNlIT" an.d is a1Jtolll8,tica.lly axecut.ed ilt the hegioning of the nos t program. Not.a. that the in1.t:1alizlltion

74

APPLE PASCAL LANGUAGE

PROGRAMS IN PIECES 75

mlIy eons 1st of be.tween them.

jU!lt

the

BEG][1'!and END. 10'1 til

IliO

!I

t a tementa

There

a~e two d~ff@rent

flavors

of UNITs called

Regular

and lntr1nsic.

IRegullcr UNllTs
The heading, of a Regular UNIT baSi; the fom. UNIT name. The UNIT is linked 1n.l:o the hos t program just once af ter the prcgram is compiled. and. Uie enti:reUNII're c,ode 1s s['i:'ually imllHted ill t.he hoat program's codefil.e a.t that time.

E,ve:ry unit in J!J H_IH'8I:"y has a specd f Lc segment number associated ~1th :h. The aegment numbenl used by items a.l.r eady (n the Lfb r ary ,are :shown ill pSI:Ellltheses by ~1:1eLll!RMtY and 'LIB~1APut iIi 1:.)' programs (see Apple Pascal Operating Sys tern Reference l-lanual). In choosing segment numbers for an Intrim;dc UNI!. the eOIl8 t r a Lnr is that when the host program runs. i!:he seg-men t nUmbers used by the pc·ogr am mus t nOI: collf lie t " Observe ~he following: - "'Thile any progl'll.l!I is axe cut Lng, the system uses the main progr.arn !lody uses BiOtgwrmt 1. Therefore" these numbe ['9 fel r an In trine ic UN IT. - Segments :1 Urrotlgh III are reserved segment
never

III and
use

for use by the system. or functions, increasing number show numbers in the in

- If the progra.m declares any SEGMENTprocedures ~heaeprDce:dur~8 or funct Lons use sequent ially segment n~llmbers starting at 7.
Each UNIT uaed

Intrinsic UNlls
Intri~ic UNITs can onl~ b~ ~sed by installing them in the file. Th i6 is done at tel:" compil.a t iOn by us ing the LIB.RAB.'i utility progr am (s'l"e Apple Pascal Upe r.e.t tng Sys [em R",,:ferenee. Manuall·
SYSTD<l. L IBRAR'l

the - If

librJ;Lry

by '[he prog'ra~ listing.

'USES

t he

segment

pes sdb Ie , avod d any duplii.:at1c)fl

of segment

ltbrar-y.

An Intrinsic ONI1' [s "p;re-linke<l:, " and its eode 1.9 nev'er actually inserted into tRrte host pro,gram's c.odefile. Whe:n you R (un the hos t program, the L.tnker is not ca lled and does not have to be on line. The Intrinsic: WIT's code is loaded into memory when 'the host prog~ClII1 h to be executed. 'Thus an intrit:1.Bic: WIT can be used 1.Ml. many different programs, but ther,1!' 1.1;1 OQly one stored. 'C.opy of the. llN1T's t:ode. This can he especially useful ~hen !IInctug for does not have roOlll. for the Lf.nke r or for large sye tern d'i.s~,ettf'. !late ~hl!i: the SYSTEM.L:rn!RAR'l t:tme I:h@ ca.1ling prog.1:" am is execut ed. The heading UNlI of an Intrinsic name;
CODE caegnura CDAl'A dseglluml ; UNIT

Generally. it Ls a ge cd idea 'through 3L.

to use segment numbers

in the

range from i6

I~' '[DJ;

The compller'

s ~MAPPING op t 100.

a one-drive system wltich programs on the maif1 flie. must be on line 'each

s,hould alway's be usad beading of tbe UNIT.

'when

ell

UNIT

;is compiled"

It should

precede

che

has

the form

INTRINSIC

The INTERFACE Part of a UNIT
'I'b.e_

first

part

of

II

VNU is

[lie INT.E.!lFACE.

where (:sek,'D.um and dsegnum .IlIre t\lll; segment numbers to be associated wid] tile UNIT i.n when it is installed in the SYSTfl1.LlllRARY fHe. You clIo!}!!B these numbers, aru3 the syst@;tlluses t.hem to identify 'che UN!T .at run time" Segment 1il!.Imbe:rs j[angf' from" to 31" but 'certa.in uuebe rs bet.ween 0 and 15 till.Ist not btl! used (see below). 'The UNIT wUl generate <II dat.!!< segment if it: decl1are.s B.ny ver.tables not c.onl:.dned i.n p!"oc:edures 01: funct Lons ,
Th.e

The' llNTEIU'ACEpert im-m!<d! ateI)! f ol l ows ch .. UNIT'!l head Lng line. It dec lares constants, types. va.rLab Las , proDedures and Eunct ions char are public -- that is, t1ne host program can acces s them just as if they had been dac Is r ec in the host progrBr.'1. The INTERFACE Ilot"tipn is the oniy part of 'th€ UNIT that is "viaible" from the outside; it spec tf Les hew 1'1 hoe t program ca D cDmmunica te ""i th the UNIT. Procedures ani! Euac t Ions declared t n the INTERFACEare l!lbbrwiate.d nothing but the proccdur a or f unct ion name and [he pl:Il"betel' Gped fica tione, as SI'lOIom in t ha example b",Iow. to

code segment will be associated with segllIent csegnum !legment (if ther@ is one) ;;!ill be ",sBodated with segment

BDd

itl> data dse&ll.um.

76

AAPlE PASCAL LANGUAGE

PROGRAMS IN PIECES 77

The' IMPLEMENTATION Part of
The rni'L~"N'!'A'IIONpart
lNURJI'ACE. ImlliedlllCely

0

lJNllT
declilration .ili'L the UNIT fROG. INTRINSIC CODE: 2S lJATA 25; (* Tbb '" l~; (* Will ; need Data liH"811lent "') stuf:i' rs pubHi: "'l INTER.FACE (;OMS1' FLYStZE

foUIJW1I t.he Last

'['h'e lM1'L&1I>.NTA'IION beg.1fis by declaring those 1abe19. l:::oust:antB, types, ·v<l.'!:itanle.s, procedureB and fYficn:1.ons chat a1:e pr1v<I te -- that is. !lot acceflstble to the hos.t; program.. Then the publ:l.c procedures and ftlnctiQ[ls t.ni! twere derc;lared 1n tile INTERFACE .are: defined. .As showl;l in thE' e~ mp Le belo\l. they ar@. daf !nl!g 'wi thou t pilrameten; or func ti·on ""E'BuH types., s I nce thel'j.@. !lave already been defined in the INTERFACE.

TYPE 1iIA.Ury:l'~" (GRel:;~,BROWN); '
VAR FROGNlMtE.:STRItIG 12.~J i PROCEDURE J'[J}iP (IHST; IN1:~ER) rUNCfHHl WARTS: INTEGER;

IM I'L EM f.:NTAT ION CONST PI = 3.14l59;

(" This

sl:u..E£ is

pr Ivat.e

ill)

The lnltlollzotion
AI: ·theend

POlrt of

01

UNIT

T'fi'E .ETC = ~ •• 13:
VARFROCLOC

:1IJiTEG ER ; {'" No te; DIS!
(lD

the DlPLetrE:I'iTA'l'I.ON par'[ ,. fo l.Lovf.ng the last funcUon OlE th,ere J:s the "'init.ialization" par t , This is 01 .sequence of !l t a te.nen ts p·[E'.cE.ded by BEGIN .<l~d t@.rmi,nat@dl'l'ith END. The result: ing code runs caut.oma.r Lca Lky when th,!" hast p1Cog'l'"aJm eX@.C!1t!:!d, be! ore ·the is 11 eae p rograa is run. t t I::anbe uaed to make any p~""para t ions that [lEY be raeeded before the procedu.lr"s. and. fu.ncot::ions of the IINIT cam be uaed , For E)(stllf.lle, rbe 1.!lHfa.l1Mr:ion psn of .he TRANSCENfl UNIT Iu SYSTEM·. LIBRARY SE!1erateG a !:a.ble of ~rigaflCfOleu:lc va lu.es to be IISElii by the '~ransc:endenta lfuflcc 10ns. If you don' C \olll.n any fn1 t is Uza t 10n to t t ake place, you. 1lDJst stHI have tb<; END followed by a [:l1U''iod..

procedure,

or

PROCEDUllJiJUMP; BEGIN FROOLOC -_ FROGLOC+ END;

lHLra.ii1fl'ters he r e :1:)

rnNf:TION

BEGIN

1-IARTS;
definitien

('" Fllnetion

he.e *) hare
11)

END;
(11 More proE@du:res

and fun ctio.nfl

AN IEXAMIPLEUNIT
Let '9 sketch out an llm.aginary Intrinsic UNIT !: 0 deIllO!UIt r.a [;'1" the info:r!nat ion gl "e.n above. that !!E@.ils a DATA acgmerrt ,

BEGIN END.
('" In1t.iaUz~tHm code, 1 f ".flY, goaa

here

"'l-

Variables of type FtLl mua L be dec Ia red in IlNIT. A FILE dec1a.red in the IMPLEMENTATION e'~IOr upon cntnpd.Lar ion.

th£!. INTERFACE part: of II pan wi 11 cause a synr ax

USING THE EXAMPLE UNIT

3

The

UNIT

abOVE,

properly

completed,

would

theu

be

compiled.

The'Ul

the

IlNIt' Would be instaUed in S'iSTEM. LIBRARY. ua Lng the LtBRARY ut nit),' (lnce in the li1;,..«1"Y, the UNIT 1::·01.1.10. (hen be used by any Pascal hos t prC~I'al!lo A ssmpl .. program 1:0 uBe" CUI' UNIT is sker ched aut below:

78

APPLE PASCAL lANGUAGE

I~

PROGRAMS IN PIECES 79

CHANGING A UNIT OR ITS HOSllPROGRAM
USES :raOC;
CONST VAll •••. ••• ;
•• "

:

TYPE •• " .i
li'ROCElWRE

For' t,est purposes. you 'may define a l.e~ular iJNIT :rigbt in t he ho s t program, aft'er the hea~.ing of the he,s t ~rograIll,. 10 [il1s ease, you Ifill cOinp:lLle both the' GNIT and the ho,s,tpT,ogram togetheJ;', Ar,y eubsequent ch.engea .ill. the LlN or bO!;lprogratmrequi:rc [T t that you recompile bOI:h. I~o:rIM11y. you rl.ll def Lne and CDnip.lle. <Iii. Regular llNI't sep.s r!I~el, and. use it ,as a library Ule (0 r store 11: tn anrrt he 1: library by using the 'LIBRARY tit U.ity) • I!.he:r compiling a ho,s t program th;n U!H'~sstlJ'~b .a [JNIT 'you must Ihlk that UNIT into the host :~,t'OgI"IJI'S codB.filO!: by ,exl!.cu.t:fi:og the Linker. Try1ng to IHun an unUnkedc.ode fUe ""ill cauae r;.be Linke. to eun ,aucOllia ticall.y. look 1nE fo';:, the IJNl!l.~ th.e aya tern. Ubr,al1" Tryin;g to X(ec.u'te alii. unlinked file causes th,e sys tern Co remind YOiJ, to link che f:fiJ!.e • Cha~e.6 program. in the hoat pl:Qgr= r equd r e that YOlJrecO'mpile the hos t You must also link in the UNIT ,Ilga,in, 1f it ~B nat Intr·.:Lnsic.

FUNCTION

••• ' l

BEGIN

I'

END. .11program
parI: iudic.!lt€ t;he UN:I'I'a that 11:: mms befo~e the de~:l.ar:at;lO[l prugram;procedure:El ami fWictioos may not contain tn@ir OWn USE clecla:ral:;(oLls. At t he OI:I'J.I1::rence of (j USES de cLar a ti au , the. Compile!: I:efe.re.nc,es the INTERFACE pa et; of the UNIT 8.8 though it: ware. part of the
!!iuS!

(lft.he

l . I

heat text H:~e1f " Tbel'l!"to're a,i 1 conat aut s , tyPf!s. variables, fUl:!cl: iOLlS .. and procedures publicly defined t[l the UNIT are global. N,W!l@ r.:o~lfllct$ m.ay ari!l'e if the usar clef :Illes a~ idellt1f1er that has already been puhUdy declared hy the UNIT. If the UNIT iB not in the S·YSTEl'1.LIBRARY, the USES deda ration mUBt be pJrllceded by ~ "use library" option to teUthe compHer ..,hat library file eontaaus tile UIHT.

I

Chan8:e5 ;tIl a 'R'E<g~lar mHr :rEquire you 1:0 re,compile the UN·IT., ,and t.U:lell to :re.cOJPpi1@!llld relink a.ll host: plrograms for other UlHTs.l wh:Lcb use that
UNIT.,

INTRINSIC 'UNITs and I;heiI' hos t programs can be c:.ha.nged above, bu t they do not have to be :celt nked.

IlS

de:s,cribecl

NESllNG IJNHS
A UNIT may al so USE a~other UNIT. in wbtel,'\ case ehe USES deeIa:tatIon must: ,1IJl]le.arat th@ begilli11iU.& of the INTERFACEpart,. t-ot' example., c:nJI' UNIT FROG might use the graphics [UUT TIJRTL£GRAPIHCS; (*$.\,,1-* )
UNIT FlOO: INTRINSiC CODE 25 'DATA 26;

E

INl'E"RFACE USES TIJRTLEG1RA¥HIC S; ()OI'lST FLYSIZE - 10;

llhe.u

you la tElt" use such ,1lJ UNIT. yon rhos USES the d;eepest L1I~S te.d lINIT f i1;:1'1 I: ;
PROORAH JUMP ER;
'['[I RTL £GRAPm:

t

program mus I: de!:la re

thin

it

US ES

e S •FROG; UN cannot IT USE a !lEgul.ar
HI'll';.
[

The.re ,is Q,i:1e11mi I:: a tiDL1:: jHl lin 1:ins1c

I_
T

so

APPlE PASCAl LANGUAGE

I_
PROGRAMS IN PIECES 61

EXTERINAL P,ROCEDURES AND FUNCTIONS
tXTKRNAL

hnguage
require

file.

procedures (. PROC':91) ar a sapa rll_tel y as semb led asse~lbly·procedures, of t en S to red f.n a HbT'a ry EllE!. Hoa ~ progrWlLB EXTE~AL procedure" must nave them linlted ili1to the compiled

tb.1lt
code

A host program declares that a procedure (or muen the slime f;.7:;ry as 11 pr o cedur e is dec La red heading is ~rovjded, followed by the keywQrd PROCEIlUR.E E.X'!' ERN A1. : FRAMNIS (WIDGET,

function) is EXTEIiNAL if1 FORWAIID. A s ttl ruia rd EXT~RNAL:

CIDIBIHON:INTFliER);

The r e is one special rule f urrct f.on a lit VAll. lJararuecer Calls to the

for can

thl!!: headiDf be declared use standard

of an EXTERN.AI. proc,edure without a.ny type. Pascal syntax., and the

or

EXTERNAL procedure

Compiler checks that: calls to the EXTf:RNAI... agree il'l type and number of parameters with the EXTERNAL de e La ra r.Lcn , It is the user's responsibility to ensure that the .:l.ssemllJ,·-.ianguage procedure respects t he Pa.8 cal EXTEllNAL de c bra t ion. 'The Id nker che.cks only that, the number of wards of ps rame t.ers agree b~tw,een be Pas ca L and ILBs@mbly-language declarations. Ven:: more Lnf orraat Ion sec tl1!! Apple Pascal Operating SystEm Reference )ol'al'lusl. The conventions of the surrounding system concerning register lise and

calling sequeTIc'es rout 1nes • On the

must be res pe ct ed by writers of assernbly-laTIguag'E fI.pple. all regis ee rs are availab Ie. and ae ro-pl1&~

hexadecimal hH:atl:ons 0 t hr ough 35 are. available as t erspo r a ry variables. ~Qweve1:'" the Apple Pascal syst;;om also uses these Lo ca t Lons as temporaries. so YOll should not expect da to 1 f t there to be Lh~re when you e-xecute thE! rouc tne the next t Ime , 'You can save variables ill nan-zero page memory by lJEi!1& the •BYTE or ,T.lORD directives in your program to reos@rIle space., For the assembly laaguage aane , except that; functions <.FU~C's) che sequenCE is essentially

- Two .10 rd s of zeros parameters ore put. ._ hfter rhe ex Lt, rime, stack the.

are pl;lsne.d by the on the stack •

Compiler

at tel'

any

has be.!;!n cempleteiy PUNC must push the

c Le aned function

up at the routine result on t~'H:

stack.
For en exalliple of all EXTE.RNAL asslHllb Iy-I .. nguage procedure and an EXTERNAL as aetnb ly-1a [Jgua~E funct to n , called fr om a Paa ca.I pr cg r am, SIH~ t he examp 11" Ln the Ap'ple Pa.sea lOpe fa [ln~ svs tem ReI'E renee Manual. The EXTEl"cN/lL routine in thll t example is mauaa.Ll.y LinkEfd Lntc ~!1~ ca Ll.Lug
~lrogTam"

82

APPLE PASCAL LANGUAGE

I
(

IDENTIFIERS
Tbl!: undenc:ore cha:raeter 18 allo~e,d tn identifiers; !;.omp:Uer iguore.s it. Thlllre!ClI-re the idelJ,tifie.l"s howE:ve.r. the

!I
[

r
[
!

aero
Apple P!lIscal hu Il. IlIcrre 11m t~d pucal. The des t:Lna. tioliL of the procedure as the GOTO !! tatement fa m of GO'JO 6 tate:men;u,t than St.lmda rd OOTO II tal:ement mUll t be :in t:he ",UiliJiIl :L tae.H (CDns ide ring the !I18.in program unle,e,e the to

r

fIG_:LBA'F

FIGLEAF

1
[The Apple keyboErd doea n,ol: have 'the UiI!iet'lIcore Scme!! ,external teDiinala .del.)
i

be a proceduEe).
The cO-!!ql:Ller cOll!lid~n a COT!) atatem.ent to beUlega1 ~Qtllpiler option (*$G+*) h !JIBed; Bee Chapter 4.

are ,equivalent. d:t&rac'ter i but

I
i

I
I

PROGRAM HEADINGS
Although tlle ,ApplePus.:a.1 Compill!r will permit; a lis t of file pa rB.mf"tera to be present :!',ollcwiI:t8 the program identifier (M in Sta.n:ti,e.rcl Pasca l j , thes!! pa :rameterll, ,a.re i,ge ot,~d l:Iy the compiler .and. have ItO af feet on t.he program heiDi compiled.

bStande:rd Paecal, Hthere is no ClllS,e labe1 equal to i:hewll.le of 'the C,IlJBeseiee.to!!'. the Teesl.!JLt:of the eaSe statement is un,defined. In Apple P.a5cIl.I. if theE!! is 'IJ!) caee label lJ:IB.tcbilLnlthe value of the EIlJSe .seLect.or. thell thellext !I'ta:teilleilC I!lI:llctl;ted i.e U'[~ :et.a.lemene foU.O'oi'i.ng the ca~e statement.

I I
I

L~

r
I I

l

SIZE UMITS
'nLe' fo.llloW"lng h a. Ibt of I!U!.xl.mum she l1'mitac1.0.118 :illllfolled upon t1se r b)' the cu r'ren I: h:J;p 1!le'[I tilt 10 11 e,f IIIIpIe 1',.. 5 I:a1 : Ie
Haxil!lUllI nwtibe 1" ofbyt es of obj eel: code 1n .JlJ PROCEDURE or F(]I1'CTION is 1200"Local variables in 11 PROCEDURE or FUNCTION ,~an Qceu~y a Il!Bximum of sboll't 18~k'l!1l words of memory.

COM,MIEN1S
The Appl~ Pucel compiler recol!:n.izee any text ~ppear1.n!! between etthel" cheaym1.lo.[.e (~ M.d ~} or the symbols < !Inti. } M ,1lJ COIilliiE!L1,f_,. Text llI'ppead.ng 'ee'tween chelle ,symbols ia ignored: by the CompHer unhOls9 the firBt chs:ra.cter of the comme.n't i.B 8. l'ioll.!!:rsfgn, in which ease th,!'! eommenl: ill 1nterpreted ,115; a c.ompiler opt::fi.on {see Chapter 4)" If of the 'be.ginning of the comment ia delimit.red by the ('" symbol, the en.d t.he OQ!!l!Il.E!.n't !!!Us!::be delimite.d by the !!lII,tehing 10) symbol. E&ther than the )- symbol.. Wht!:lI!the ().omment beg;1.na with th@ { a ymb 01 , t.he CO!!l!!leot continues until the Etching } a.ymbol IIppea.1'6. This feature B.llcw.~ you to !'CQmm,ent out U 11 gect~on of a j'll'ogr a m wb:h:h itself e;,orl:tainll comment!h Tbh a,ppl1es t'o ex:~erna.l I:erminalle ooly, since the only CQ!!l!!lJ!!nt elbrl:ter a:vaHll!ble on the. Apple h the p!!ir d foli and *l. An I!Jrample of how the two kinde of commen.t delimiter!> .lIre used 00 an ell;tel'mtl c,enainal:
{

~~
I

the

,- i'laxi!IIU!I! I1axinrum

number

of

cb.,!!l:"sctel'B .1n element
sin
II.

II

ST'RING va I!:i ab Ie

Ls 25.S,.

n.ullihe 1" of

SET is 3.2 .. 16 .. 512.,

~ Haxil1llJm Ilurnhe r of eegme'ot s a program!;:; n ruse :lIS: 16 • This i'lll:luli.es one segment for thoe lIlBlim pr o.g·ram, enc for ea.::h SEGMENT PROCEDURE amcl 6EGMEN1' PUNCTION declared in the
prQgram,
&xlmUI1l

and

one

for

ea~h

R@li!ull1.Y UNIT
or

t hac

the

~rog)!;lIm

USES.

m.lIliber

of

PlIDCEiJllREs

F1mCTIONs en~ ed is

wU:h:i'n

'" segmem:

EP

I'" XCP + 1 if'"

ADJUS T POR SPECIAL CASE...

"')

}

is 149.
MaxlllW.m i tl'teger

that

can berepre.s

32767;

m1.n:t.mum

The CQlIlpil,er ,does n.ot keep CI'adil of mOlsted cOmmeutS. When a comment aymbol 1& em:.ou.ntel'ed, the text, i.e IIcanned for c.he. III1l.tch:1.ng comment: symboh 'll"l'e foIJlo"11n8 text. wi.l1 re.sult in II syntal': error!
(II' THIS

1s ,-32768.

IS A COMMflNT

(* NE'STED COMMENT tII;)

END OF Ft.II.ST COMMENT it) "'e.tor here.

EXTENDED COMPARISONS
,ApplE! .Pascal ,,llo1011l .. ana, <:) type 2nd of rE,cord at.ructu res
c0m;P0l.'f.i,8ons

of aJ:":I:!!.Y" e:-;actly of of ,exact ly the same t:;y:pe. This

thll
cam

sa.~e he

64

APPLE PASCAL LANGUAGE

OTHER DIFFERENCES

85

done
(j

without:
,COlSf!

subae r Lpt;in,g

('tn

the

case

n the

of

reCOl'd

s) •

For example.
OF mTEGER; INTEGER;

of err!!,),!! lJ or fj,eld. identifier:'! gj VlOtl the declarat Ions

Whe.n.

11M Al B:,

AR.RA'i[G, •• AItRAY[\Ii ••

,l~J !Ill

the OED function :!t.s a1veJl a .BOOUlAN val.u,e as lUI ac'tual pat',a:lIleter, the rellult b not: al\OP8.ysJ or 1. It i.roOOBt un.HkeJ.y that a. lO'oridng ! progratl! 'will ever encounter I;,hjs, sltuat:1on, I!,inoe there' is little re8.c!lOfi to take the OED of a OOQLEM!value.

or

then 'the fol1awlog
IF A"B l'HE.N •••

sr.atemen!: is le!!:l!l:

and the st.a t.ement; folllJ.yJ:ng the A .1s equal to the c.or1"e!3ponding

THEN will be execut ed e.le.m.ent of ]).

if each

element

gf

AS PARAMEtERS
PUNCTION.

PROCEDURES AND FUNCTIONS
AppleP~scal dces not allow a PROCEIlUREor FllNCTION to be dedared formal parameter 1.:n the parameter H:!:!t of .mother PROCEDURE or
,lIS

a

:RECORJD TYPES
Theu: a,~e two te,:!:!td'ctjoos
fr'Dm S':.andard

on rOl:ord
P'aaca I syntax

type, declarat;ions
e

which are

d,Hfenmt

- A null

Ueld

lisl:

ill

HIe!!al;

in other

.... erda

'the

C(;lfl5tn.lL!ti,on

RECORIlEND; wt11
C.IlU.BC 1I.!l

en::,or.
is

- A n,u11 field wl.t:nill. the ~Brenthe5es of II va.j,!lJilt field Ust: I.:Ui!gal; in other wo.d:!:! 01. :ocm:!colon just before the dosing
pe.r ent.hesd s ~i 11 caUBe: an e.iI:'or"

THE ORO FUNCTION
The ORr) func:clo[l wUl accelJl: a parallleter numerical value' of Lhe pointer. of typ'c .POINTER, a.nd reto:nrQ
dIe

86

APPLE PASCAL LANGUAGI:

OTHER DIFFERENCES

87

88

APPLE PASCAL LANGUAGE

APPLE GRAPHICS:

THE GRAFMODE

PROCEDURE

THE lURTLEGRAP'HICS UNIT'
Tl:ri.. graphics package is call .. d ''Iurtlegrapl"!ice'' since it :La ba,,lle.d on tb~ "'tul::l:leB!t devised by S•. Papext and his cOIVo!rkersi at. t.he Mas·:sachu.IH!tts Institute of Technology. To maka I1lrBph:n.~B ea~y fot' childre.nWhom:!,ght have dUH.culty unders tanding COl. rt:es !tau coordinates. Pape.r t ii!t al. invented tile :i.dea of a "tur tIe" who could walk a giV~TI d.Iat ance and tU!r"n th'l:ou1!;11 apec.If.Lad angle. wb:{1e dragging <l. a pen along. Ve.'I"j' simple a.lgaril:hms iIi t hLs eyst,e.m (which could be called "r,elal:ive polar coordinates It) can gf 'lfE' more interes·t1ng image» I:han. an 1l1,g.ori t:hm of the .same lengt.b in Carte.llian coo1;.dinates. Before any graphiCll can be uaed , they must be enabled declarat:f,on ilI'!ll!.ed1atel.y af t er the program headi'ng:
USES TtJRTLEGRAPHICS j,

This procedu.re I'lIlS 110 pal7l1me t e rs • It swi tches tb@. monito r or TV to show t he gJ:'a;pbics ~cre~m. without the ot he r initialization th<J,t nnTmRTLE dOM. It il3 usually USE'd to show graphics in a program tnat ~wi~ches be;twee~ gra'phics, Bnd t ex t display.

THE TEXTMODE PROCEDIJRE
This

by plilcillg

thi:!l

p1"ocedw:e has no pa Cobt.ained by HlIT'I'lIR'l'11'; to text IIlClde. the image 5 tll1be l:.!Ielre when you (un.l.es a you deB.berate!}, th.,t uses g1:~Phies. the

ral!le t.e rs • "It 8wi t ch es from itT aph ic:smod"" or GRAFMODE) to showing text. r..!hen you 6W1~Cfl that you saw in GRAFHODE cot 1,0at. but w;Lll 1s use GRilFNDDEto go i lito graphics ailJde IIsal!! ~hBng.ed it .. Upon termlnation ) ~f .any program sys t em eu t oma c:lc<llly go,ea back 1nt:o t ext mode.

liE t.his dec lara tim; appears, tile graph Lea pt',o~edlLt'es and fun~.tiQn6 deacr fbed in thas .sect ion can be used.. TId~ declara tion tell.s thi! P.a!!c!!.! .system to ,get 'the gr.>I!phi.c:.s p:rog1!'ll.msfrom the libr,~ry. The SYSTEM.LIBRARY fUe rouat: he 0'1] line whefi tl'ie progJram is R (1.!1l or eX(e~uted.

THE VIEWPORT PROCIEDURE

THE APPLE SCRIEEN
Ttle Apple !lcreen is a rec.tangh, w1!:l!l the odgin (X"'~, Y"'O') at; the LOlllER tEFT CO~er. The upper righl: corner il,!l.5. t.h~ cocrdllla.tea <X=279, Y"191). Since point~. ma]' oilly be pIa esd a t. integral coord.ill<l.t.eS; all argmni3'n!:~ to the graphics funct.ions a:te INTEGERs. (You can supply a REM arg.ulllent: .it will be roun.ded to an IN'I'E.GER.). Th~llf12alt'·e !:WOdi'fferent screen images s·tored in thQ! Apple'·.s marnory. One of them holds tl!1Je text thai: YOu S~.e ~he.n '~he coeiput ur 1s Ur>Elt tm:uec 01'\·, The other hlI)lds a STaph1c :Una.ge. There m::~ three pt:Dc,edllre6 [hat
switch between the
IruJdeB.

(I

w1n e re
have.

want
There

the. fOI.l.I pa If:ll.llJe t.e.:a g'1 ve th ... bounda rd es you 1-Ism the VIEWPORT to t If you dor!,'t use this proceduTe, Apple PBSC":n. as~um~s 'that YO[l to !Jse due whole sc reen for your graphics. are
sOlhq~ a'rdd.ng .. u

10Ihile
sqY<l:n~ .. L

c:u::caslonswhcn it is fuandy to uaa only part of th~ screel'l" t:h~ res,t from accidental j].ele. i'OI: e;i;1i.~ple, II small near the mj_d,ci_le of tht! ae r aan might be selel:'tl:!d as a viewpc:rrt by 150. 86" lil6l
'WhOSE'

the

sta.ement:
VIEI-lPORT 03~,

'They

are

[NIITURTLE.

TE:lITMODE and

GRAJ'MODF..

X-coOrrl1ol1

Th h example 'would :allow the si::re.~n-ploi: ting o-r all pOints tes are from 13###BOT_TEXT###amp; t hr ou gh 150 and w'~o§",- Y-coordina B6 throu~h Uti.

tes

erc

from

THE INIITIILIRTLE PRQCEDUR,E
Trn is procE'dur.e !las no param@t@·rs. It s '"Teen to be used for graphics [8 eher
u~,e. this rourdne befor·e sta.rting
c.l,co,m::s the

rhan text: ' any graptlic.s.

screen. and ;Jllo~5 the II: i~la good Ldea to

tNITTURTLE: iEoea a few other things as' well; the !t:url:l.e {more. about it later J isplar:-ed in th", cen·te:rof the screeD facing rigln, the pe:Cl! Io'r co is set to NONE (more about th1s late!' too) and the vtewpol"t is s.·et to full lH::rel'!n ('[end OIl).

When II l111·e :is drawn using .~ny of the graphi~ comlfl6.nd~ "it is automatlcally clipped so t:hat rlniy the porl::fi.o[1which liel';! W'ith:r.n the CuU'e.nt. viewport:: is displ.syed.Po:!.rits whose. COOTdinates are not: in the cun:ertt vieWport, even tho.se points that woul~ not be on the ac r e en at: all, ar e iegal. \:lut are ignored.

90

APpt[

PASCAL LANGUAGE

SPECIAL UNITS 9'1

This

&11,0'0119

S t,~@(HI ,Il:ll da.y • and never cannot b~ disabled.

some dr.amat1.c affect:!>. It also allows YOu t.o plot. off.S2£! a thing ot:' &e t I1li f!rrnl: :Il!e.lll>age. Clipping

The r,em!lJ!Ln:l.ng colors uBe.tul: screen. line,. It is

are

not

Tf~ally

co:n.ors at

all

but

are

equally

NONE: Draw:l.!rng with

tills "co Ioe ' produce s no change on che useful for moving the ti.l1:'tl.e w1.tnout dr.'!.w;l,pg.

a

USING COLOR: PENOOLO:R
The PENCOLiOR pr ceedura sets the pen 'co],orr., It hall title fom

_ REVERSE: Dr.BIol'ini!, wirl1

REVERSB changes

BLAC~ to WHItE aoifl WliITE

PENCOUlIl. (COLOR)

to !lLACK.. It aho c:han!l,es Io.lHITE to BLACKl, WRITE2 to IlLACK2. I GREEN to VIOLET and ,IlRANCEeo B1.UEand vice versa. lR:: is 'rllther a w.agiCBl "color"" It ·mllm'B you ee draw, say, a Li.ne ac roaa .8. c.=pl,ex baCkground amI have it sl::ill show up. RADAR: This •'<:0 lor" pp 11C~ t:iona •
hBS

WHITE
mlITIU WITE:l
IH ..Ar:K (two clots w,td~,
(1:0

bee.n left

WlUSEd

for

future

,11

for

urse w:U:h 8!:',een caJnd viole.:)
:(In,.::! blue)

dot s 'wide,

far use with ora!lge.

MORE COLOR: FIILLSCREEN
The FILLSCRKENpi'oce.dure

h..a: the

fOTID

3LA.CKl BLACK2
GREEN

(two (two

don

wide,

fill"

use with

gn"'en and violet)
orang@:. and blue]

FILLSCREEN
FILI.SCREEN
e]l;l.llllpl!:!

(COLQR)
the m"lt:ir,e vie.li;Pjlort with the spae.Lf Led color.

dots wide,

for

use

with

fills

For

VIOLET

FILLSCREEN (BLAC¥.)
c Lear s the vi ewp11 rt .' Th e sta t ement;

BtUE
If you'd like the drawing
t.O

E
be in GREEN, use the

FILLSGREEN

(REVERSE)
of

makes
statemEnt;'

a "nega.tive"

the

CQllt£!ntS

of

the viewport.

PENCOLOR

<GREE~l

It may seem st.range tl'iat aside fr01ll 'WHIT.lF., BLACK. GREEN. VIOLET, ORANGE., and BLUE, there are wo additional flavon, or I4IHTe and BLACK" 1"111";803. e. re due to ttl"" in t ric:ate (not to !ley 'btza{"Tf'} 'WIly t:h~t co 101: televisions produce their: co Lor , btera~t::i.ng with the. techD;l~ul! tnoll;t Apple use.!;! 1;0 se't a lot o.f a::olor very economically. Rathe. thlill e~pla.ining how ttL!a all works, su:ff ice it to say hl!!!'1! that WHITE and IlLACK gi VI! the fines t linea pOBs;lbll-,e. and the c,oloJ::a sive .a w-lde.r line :1'0 order to make the colora ahow. [.E you Wi!!!] to make ,8 'Olhite or black line t.hat c01:'tl:!sponds ell;aCUy in posit t100 and'. wid tit wi t.h II green or violet lille then yol.l should use Wl:lI.TEl orRLACKl. If you llish [0 make a wh jj te o:r black line that: cort:esp~nda ~a('Uy 1:11 position .and width vich an [l,ange or bllle U.ne. then you should 1!lSe WHITE2 ,or Bn.ACK2.

When you invoke is Aul:omari,cally
5CREi':i'lC010R

TURTLEGRAFlIICS, a ne.W v<l,riab l.e typo! call'Ed C'Tetat~n. it is defined as follqw5:
=

SCR.EE;NCOUl:il.

(NONE; W['TE" VIOLET.

SUlCK, REVERSE, RAllAR, rmITE L, IH.ACK2, OltMlG!;',

BLACU. GREEN" BLUE" rnlILE2);

SCREENCI)LOR has all 'the us!.>"l characce:rist:ks userlJ,], When you declare .. var Lab Ie that 'Will

of a Pascal be 1.':5ed t o

l:),tJe.
6[0'1::",
.!l

It La co l oz ,

'1)2 APPLE PASCAL LANGUAGE

SPiECIAL UNITS 93

TUiRTLE GRAPHlIC PROCEDURES:

TURNTO, TURN. AND MOVE
.At at

TURTLE GRAPHIC fUNCTIONS:
TURTLEX, TURTlJEV,TURTLEANG, AND SCREENBIT
Theile !;unctioI:l8. ,allaw you to ill.te][][ogatE state of the turtle and I:h~ screen.
rhe comput er about

las!: we're back co the imagin.ary turtle. In:lLtlally, the tUl."tle sttll the center of the scr'een, fa.Cine '[1ght. Th e turtle can only do two things: it can turn or it can walk ill the direction it is facing. As it walks. 11: leaves beh Lnd i! trail of ink (!) in tb.e cur rent pen color.

the cur renr giving

The T'URNTO procedure
1'I1Il.NTO rDEGREES

has the fotm

Tbe TURTLE:X,and TURTLEY iunc:t:i.oJ:1's (no par,acmet'et"s) re'turn the cu.r eeut; X ,and Y coordi:nat.es of the 't.urt:le.
The

integers

I

where DEGREES is an in~eger which is treated modulo 36Q; thus its effective value is in the range -359 t:hrough 359. When invoked, this procedure causes the eur t Le to turn from its present angle to the indicated angle. II is exactly to the right" and couut ar cIockwt.s a rotation represents increaJ;ling angles. 1'b.:is command never causes any change to the l.nl8ge on the screen. The TORNprocedure T lJRN (DEGREES)
,",her'", DEGIl.EES 1<; aga:ln an Lnt eger 'IlItdch is ·treiiL ted IIDdulo 36~; ~hU5 its ,effec.tive value is ill the range -359 ·through ::159. Thb procedure causes the tU1:tle to rotate counterclockwise ,from its Cllur,ent d1tecI:loo thnmg,h tne spec1f1ed angle. It causes no change to the 1ma,ge on t.ha Bcr·BeT\.

TURTLEANGfunction (no paramete:t's) 't~tu.r"s an integc~ giving the ·turtle angl!! as a posic.ivc. number of degrees. !'>late '[bat if you u.se tlIRNTO and then TTIRTL&ANG, the value returned by TIJRTLEANG may no 'be t:he same valu!! you gave with TlJRNTO'. For example, after

current:

TUlUlTO (-,91;1) TlJRTLEANC will return

2. 7ij!. noi; -9\il. has the fo~

has the form

Tna SCREENBIT fu~ctton SCREE~IT
... ere h value

(X,I)

X and Yare screen, coo:rciinat@s. This function retUJ;ns rhe BOOLEAN TRUE if the specified location on the screen f.s not b l ack , and FALSE if it 15 black. It doesn't tell you what color h lilt that point, but only whether there ss aomethin,g non-b lack there or no e.

The MOVE procedure

has 'the form

MOVE (DISTANCE)
where DISTANCE is
IN THE DIRECTION DISTANCE. It <Ill integer. This procedure mkc5 thetu'rtle move IN 15 POINTING a d:fi.~.ra.n~e given by til!! tIl teger leaves a t rB,il ill the current pen color. The sequ(!nC,E;! of

CARTESIAN GRAPHICS: THE MOVETO PROCEDURE
Earlier w'e said that in tIlr·t:Ie graphics, the turtle can only wa1k in rhe diri!'ction it is facing,. But in Cart",sian graphics., tbe n:urtle can move to a specified point on th.e sc-reen wH:ho:mt tl.lTn1l1g. The MOVETO pl:ocedure has the 'form

WHIC'H IT

SU!'temell[S;
MOVE C5ti). TURN {12~)i MOVE (5Q) j

PENCOLOR

(IlliITElj

MOVt;TO (X. Y)
whe.re X and Y St'l~ screen coord!inates. NO'VETO moves the t.ur t Le to the point ex, 't ),,, This c.reates a: line in the cur r ent pen. colo.::: from the t),!rtle's lasl: position to the point (X.'ll· The d~rection of the tur Ie is not changed by MOVETO.

TURN
dre~s

(129);
triangle, for instance.

HOVE (5~)

an equllateral

94

APPlE PASCAL LANGUAGE

SPECIAL UNITS

95

GRAPHIC ARRAVS: THE DRAWBLOCK PROCEDURE
The I)RAWl1LOCi{ procedm:e DRAWBLQCK (SOURCE, has the form KSKIl", HODE) YSKIP. 'WIDTH, HEIGII!, ROt.lSIZE,

_ MODE ranges

XSGREIlN, YSCREENI,

where the' SOliRCEpara.mert: e r is thE n.ame. (wi thou t subgc.r·i.pts) of a vnr Lab Le which should be a I:wo-d:l.mensl0nal PACKED ARRAY OF BOOLF.!U'l: {g~e note beta,.,). All the other p:H:am~t'Er's an~ integ!:!l's. DIUM1ioLQCKtreats each llOOLii:AN e Lemen t of SOURCE as a "dot" --, r rue [or whit e or faJse for black. It copie.ll the array of "dots" (or a portiolll of .it) from memory onto the screen to form a screen image" the first dimerlsion of thE ~rray is rhe number of rows in the array; the saccnd dimension is the numbe.r: of el(;!l'IIent<l in aach rffi.!" You may choose t.o copy the entire SOURCE array, or yO!! may choose copy I'm)' ape cf f :fi.ed !'window" from th,e arIa)" us Lng only thos e dots !l.['['ay from X::aU.P to XSKll'+WI.D'TII and from YSKIP to 'lSKll'itlEIGHT. Furthermore,. YOt] can speciEy the starting S!:TEen pOSition for th~ ~t (XSCREEN , YS CRE EN) • SOURCE ,is the BOOLEAN 1:.0 be name of 'the. tWD-d,imensiolllil PACKED AKItA'," OF

from II th.rougb 15. The. MODE de'termines -what appean"9 on the portiM of' the scree" sJlecHied by the ot:.be.f' paramete~s,. I,t is quite ,a, powerful option, ~ich call _Simply send 1;J'hlt~ or blac:k to the SCI"e.en, irrespective ofwhot:. is in 'the array, copy the B.rray literally, or combine the cont ent.a of tll.e a1'Tay a.nd the screen and ,s,e.nd the result ~O' the sc!:',een. The followloli!, table. sped.fieswhat op'e:rat.i.oD is ped,o-rme,d, on the data in the. array and OQ the screan , and t.hiJ.9 ~hll.t appear's OIl the ~c:[een. (The logical Ii()t:~tll)fi 1lli5e;' A fm: the arnl.y, and S for the Hcreen. The ,symbol mean:!!, NOiT,,)
M.ODE

II
1

to
in t.he copy,

2 J 4 :5
f,

Eff~ct Fills area on s~reen with black. NOR of array with SCl:'e.etl" (A NOR S) AND of array with cump.Lement; of s"n.,em.

8
9

7

1(11
11 12

copied

(s ee not eo below). (not
the

,- SIZE is the
'lou can 2.t(

flUHlbel'" c,f by te5
this OIV 16 from

dots)
fOl:D1ula

per

['ow in

t:l1e anay,.

cal!:ulat,e (1<+15)

13 14, 1:5

(A AND -5) Complements OIFIHI on sc::ree.tl,.( ~S} ANTI of complemeun:: of ar ray w1'th 6cree'!h (-I\. AND S) Cqmplemellts t.he er ray- < -A) NORoferray wi tl:l screen. (A Knit S) NAND of a.reay with 5Cre!!Il' (A NAlID S) WD 0'[ ar ray with sr;nen. (A AND S) EQ1UVJ!.LENCEof ar]:ay with sc:reem.. (A '= SJ Copi,es array eo seTE'en, (11.1 'OR of array with complement of Sere.en. (A OR ~S) Be.reeo '[~pl,ac:eB Br:reen., (S> OR of E.omple.me.nt: of ,aJn·ay wi.th scree-t .. (-A OR 5) OR of array vith screen. (A OR 5) F11111 <U'B:} rill. screen liith fo!h ite..

where
-

X 1s the numbe:r

of do!:.s in each rowto skip over

xsnI> t e l Is now IIlaJly hod:zom~-l doc!:! in the~rray b'~f()Te th~ copying, P1l:'OC()S~ is '6·t;!1l:ted,

l!l

Til e !lemons t r a'~ i Oil ~'['t) g:r am. GRAFDEMO• TEXT i on A.P 1:'1:1:; 3;. con,!; 11.1 B rna. ny n e:K:Bmpleso:f how to i;].se the tU'I: cle,graphic.!l rou tines. In pal!'t Leu11:1, I:' proc,EHlures BUTTER!, etc .•,. give a!: rings to procedure SruFF, which c.onv,erts I:llem too. PACKEDARRAYOF BOOLEAN named BlJIl'TER; end. proced~.!l:·e YLU1"I'ER oseathe. DMWBLOCK Tou~ine to display the array I!tJTT£"R 01'1 rbe IIcreen.

,(SKI!' t e Ll.s bow many ve.rtica1 dots in the ,an::ay to akd.p over b,ehuTe ~egfJ:,n1[;[g the copying process, Note thBtcop:ies are !!!ade s t ar t.Lng from the bo tt.om up i. e, the firs t rolf cop led from the array Ls th e be t!:em row of 'the sc ['Een copy., WIDTH t e LLs how many dots'

widttJ

of t.he array. array.

srartin.g

at

XSKIF'. will
HEI.GRT tells

bl! u5ed.
ho .... many ba used·

dots'

heiS'l1 t of

the

,st.arting

at

ISKIl', trlll

Actually" the SOURCEparameter ,,-an be. of ,e.ny· type excep t !'I FILE type: DiVlW8LOCK really deals wH:b ,il:Ji]1 auay ofbHs in memory 'Which begd.na at: 'tb'll! addri"!sll of SOIJRCE and ~ose '~i.ze and orga~:fl.zaticm depend OIlL the other parameters .~or examp Ie , the. following pl:'OCedUT~ uses a single BOOLEAN variable :instead of all §rray. The pr'ocedu.rB plo I:s a single. dol: On t.lie. IBcre!!nat. specified .r:oordlna,tea (X .•Y) :

XS.CRE.EN and YSCR:EEN arB
corner of d,eterm1.ne the the

[be coordinates area HI be cop ted wto" 'si.ge of the rec tangle.

of the lo .... r e The WlLDTH and

lef!: UEIGIIl'

I'ROCEDUREPLOTIJOT rx, 'ii'AR i>Ol':&OOLIAN,
:BEGIN
DRAWlILOCK(OOT,l,l!.

'1:

INTEGER);

!il.I,l"X,

Y, 3)

END:

96

APPLE PASCAL LANGUAGE

SPEOAl UNITS 91

Bowever,

:for most

~rog,ralD.S t.he .most. c.onvemient

way

1:0

handle the
des~l!'fbed

array

is t.o use a. No-di~nsional prEi'iliously"

PACKED ARRAY OF BOOLEAN as

III'

II

The WErRING procedure:

has

the

form

whi:!f'e

TEXTASGRAPHI'CS: WCHAR, WSIR'ING, AND CHAR1fYPE
Th.ree procedures, allLoW' you to put charact~rs 01'1 the Il'raph1cs sc~(!,en. a th,e turtle is at eX, 'f) :you can use these pr ocadur-as 1;:0 put a. cbarae:ter or ·~e'l:i.n,g oll~he scr ean with il:s lower _left crrrne r 2t eX, Y). Each ch.er<M!te.· cccup i.es a rectanguI,a,r area 7 dots 'wide and 8 dots higb an the
'lOcreeI1..

S is an expres sian of t)' PI" STRING. An en;ti:l:e string of characeeue is 'placedot! che screen with the 1.ower left CQ]:[J~1:: of the firs [ characcer at. the current tU1:ti(!' poa Lr Lnn , The eurt Le is shifted 7 dots to the right f,or aach character ill the str:ing. This procedlJre ca Ll.s WCHARfor aach ~llara~l;:{!r in the s,trin,!!.

Thue p,rocedures use an array stored in the file S'iS'tEM.GItARSKT on di.e:ke.t t<l: APPLE 1:" This aHay ccmtains all tt::he ch.eracters usud, and 15 reBa in byth E! :hLi tializa t ion routine ""hen yoor program USES TUiU'LEGRA:E'HICS,. If )10U mtlke up Sin array containi"" yo,ur own character set , you should -re"allle the old SYSTEM.CRARSET and thenoame your new arra.y SYSTEM." GHlIRSiBT (see note ,at the end of t:his chap ted.
I\lS1'RI.NU and WGHMI.use the procedure IJR.AW'IlLOCK e.e cop)" each charec te( frOiD the array mite, fhl!: sc!:~elh T~e MODE pa ... m!!~er t:ha:t they lise i.s set

T~e chars.cUrs io the STRING value pa~sed the first 128 characters of the ASCII set Appendix ll.
The GHAR1'YI'f. procedure
CHAATYPE (MO'DE)

to WSTRIt4Gare restdcted as sbc ... tTl Tab Le 7 of n

to

nas

the

form

I

by tne

CKAR.l'YPE procE!dul({!.
has

.
form

The WCHAR peoce.dure WCHAR (eli)

the

-I,
[

r~
,3
r
J r_

i~

wherE MUDE 1s an integer se Lect Lng one of t.he 15 MODEs described a.bove for DRAWI:I'LOCK. MODE defines the way c'hllracters g@.[ ~ltt!lll Oll. the a c r ee n i it works to l"WCHAR and II'STR;INGj us t, es: it work:'! for !JAA\.J~L[lCK.

The. de.iault .MOD.E 1Q, whie:h places each cnaral::ter OIl the ::lcree!1in is 'whi te, slrrrounded TIY8 black r@ctaflg,le" MODE 5 La the Lnverse of !'IODE' l'~: each chalract·e_'(' is in black su'rroundecl by a white rec:t:angle.
of the. most IlsMul ocher MODEs is 6, ..mlch does, an exclusivl! DR of the I:charact@T With the current. contents Clit:he flcr<!:en. If you use MODE 6tod:raw a charac.'.eror lltl:'ingaml then redraw it at. the same Lacat.Len ~il:\; HODE. 6, the effec:!: Ls 1:0 e r aae the character or st.ring, Leaving the' tlrig1.nal image mi.a.ffec.ed. This i~ (!specblly useful fer!: usaz IDessag@$ i.oe graphl.c.s-l1lI'iE1il.ted p.l:ogum. One

where

CH is a fin exp r eas Ion of type GHAR,. Thisproc(l'du.:re places the charac rer On the Screen with i rs lCiW!!.r le.ft cornel: <lit the CUt' rent location, of the turtle. 1-Ihen ttlts pl:Cicedure is used, the. 'tu:r t Le is, s·hilted to 'the r.i.ght 1 dots, f rom i[s old position. For exampLe , thIs puts an, x: in the ceneer of the scr eau:
p~Ncm.OR (NONE); MOVE:ro (13 i ,9(1) ;

!J

~CltAR

C"')n

In this example., ~ote that it ~1I6 no't necas sary to !l.pectiy a ne'iO' pen colo'[ before ca;lli.ng I<lCHAR. The character is not plotted wit.h the current pEn color; r ache I: it depend.s on I:he Cl.[rr"'~t MODK, just 013 D!RAWIIL(JCK does. For details. 'Bee C~IAltrYPB bel,~~.

If you wish to 'I1':r(!at~ yOll:!: IJWp cha rae roer se't file WSnUNG. it. IlIllS t be Btructm:ed aa fo 11o...s :

fot' use ~ th WCllAR and

.- St.,ar l:i.il,1r;wi'th the charal:tlH'

the set

t byte in the f He. each character is 't'epresl,Hll;cd by 8 cout.Lguous bytes.

firs

111.

The CHARvalue passed co t-ICIAA,R 'restricted :1s to the: first of the ASCn set as shovro iil Table "I of Appemd.:llx~,

128c:harac1:ers

- E"ch byte re.p.resen!:s, one't'OH" of 8 docs in the ~ha1['aCl:er imagE. Th~ first: bllte of @ach char!i!:ter represaL'ltatimu 19 the bottom H1W of the image.

98

APPLE

PASCAL LANGUAGE

SPECIAL UNn-S99

- The least the row.

s1gn.1f1cantbf.tof

~<!ch by!:e Ls the

leftmost.

dot

in

- The iliOst ei.guifiC:Clnt bit of each by·tE only SevEn dots ee.c:h.

is

ignQred;

ebB. rows ate

'OTHER $,PECIAL APPLE FEATURES: THE APPLESTUFF UNIT
-'

.

~uch a file COil be createdi eithel: in CI!isemhly languag~ o. in Pascal.. In Pas'C:1l1. you. can build the CIHl.l.'actel: l:epresentati.on9 :in me.mory ;as packed nnrl:lYs of the type '1•• 255 S illce each elemen t of such an ':UJ:.e.y .is tn effect a byte. For example., you might uaa tn.ea:leclarail::ions InE ClIAFiD1A.GE-PACKED Ji.R.RA'Y 1r;J 7] OF ~ •• 2.5.5 : •• CHAJU,E,T-PACKED ARMY ~(!•• ,127] OF CIWllKAGI::; CHAAFILE .. rILE 'OF CHARSET:,
c:ftARA1':'fER S : EIAltSET ; OUTFlLE: CIiARFlLE;

'fhi!! sec:r: ion 'teLLs you how to genera te random numbers. how to UBI" the g,ame paddle and button inputs, how to read the C81lSette audio input, hoW' to switch the game-control"s TIL output.s and how 1:0 generate sotlClda, on eha Ap'ple,'9 speak!!.·r. 1'0 use these .special Apple feat~res from Peaca l , YOu f1r;s·t have to pla~e. the dac.Lara t.Lon

iDLme.dia tely al tel." tlul prlJ.gram headd.ng , If :fDU wish graphics and the Apple fe'8 eur as you would say '[lSES TlJRTLECRAP!UC5 • APilhESTUFF; stnel'! there
C<lO

ell

cs e bo th rue tLe

VA

a

c

only

be one IJSfS 1.n apro,g;ram.

THE RANDOM FUNCTION
IUINtlOM is an in I:ege.r f~.m~t 10.0 wi th no parameters.., It re tuens a value £l'om ~. I:hroush 32767. If JRMmOI-lI.e: called l:epeat~dly .• the resu.lt i8 a psuedo-rando~l sequence of integers. Ttl!:! stat",me,ll't WRITEtN (RANDOM) an il1.1t.eger be tWe~n cite indie!lJCed
l.illlirs.

-3

w:111 d.isplay

A l;yp:1.o::a1 app
s,ay.

l1CIl't1.0fi

ber.lo1een LOW and

of thl,s, Func r 101] is [0 get a pseudo-ran.c:lom [luillber. rUGH inCll.l51ve.. The e.:qn:e5s1on

~
I~

LOW + RANDOM MOD (lllCF[-LOIiI+ll i~ Bomet1.mes used wheEe Te.s~lI::S ,... e net; c:ri t;ical, but the vs Iues formed b:t chis expreSSion .Il:e ~ evenly dis ~:r1bu ted eve. the nmge LOW

I

.. I. I I
I
I

I

I~--

I

I
100 APPLE PASCAL LANGUAGE

S~ECIAi UNITS 101

~

t.hruugh l'lIWl'L. If you wa,,·t pseudo-random int(l·ge.n OVer a Fang!!, you can use the follol<f1ng !unec:lon:

evenly

dht·r.lbuted

read the rnsl!:ac:t er I/O. The 8tat~ent

£rOUl

CONSOW; or tn'OOARD

OI"

have

IIny other

ef fe HOn

FUNCTION RAND (LOIoI, HIGD: INTlGi!:II.: VAR ERROR:ROOLEAN): VAR HX, G, D:, INTEGER; lJEGIN RAND :'" @I; EfU:!OR ;'" TRUE; IF tOW:;. HIGIl THEN EXl'J:' (lV\.mlj i (*1"["["0[" edt"') If LQI-i .;'" II: THEIi IF HlG H ;:. MAX1.N'I'

INTEGER;

IF KEYPRESS, THEN READ(KlYBOARD,
chanll;te:r character fru;t,ance,

CH)

(where CD is

the effect of lI'eadb,g the Laat tIJ CHARvadab le) ~af! This cou.l.d be u~lI"dto retriev~ a. typed an. the key ball.ltd. typed whH.e the program wpS, do:1o:ll aometlting e.ls,e .-- for displaying, gra.ph:1c!S. be cnaes
the

+

LOW TIl. Jr'.N EXIT (RAND);

< "'~rrol"

exit

*I

OnceKEYFRtSS
!J,c,cesst;!,S eUhe!:

true

it 'teDI8.ins
f Ll.e or the

tTUf!

until

a GET, READ. or READLN
0'[ until a lJInTRIJJ)

INPUT

KEYBOARD file,

ERROR :- FA.LSE; (*no eHors1i') IF LOll '" utcu TIlEN MND :'" LOW ELSE: BEGIN C :- RIGH - LOW 4- 1; NX :"' (r1AXlNT - RIG.i:! + LOW) DIV C -+ 1: HX :- HI: '" (RIl>H - LOW) + {MX - 1) i R.EPEA'I n ;= RANDOl>! UNTIL D <- MX.i RANJ) ::'" LOW + 010101) C E.ND E.NtJ ; .If HIGH ~,s not greater t:b.an LO!.J, or the dHEer@VLce between AlGI! .e.ndLOW I"'ould ex.ceed !-lAXINT, RAND ret Ll rtis \! and sat.s the ERI!.OR pa ramat ar to tr,u,e. Othe""tse, RAND r e r.urus evfil<nly distributed pseudo-·random :l1'Iteger values be!;W"een LD!.o1 and lUGE! (:I!I~ lusi ve) •

acces ses

thekeyboa

rd device.

~I

1<EYPRESS ~om;; not.. work \I.ith an external te:rm.inal eonnect cd via a serial ipterhce card. It ..nIl always re-turn F.ALSE with s.uch a ~e.1"IEinal.

PADDLE BUlTON, AND TILOUT
t

The PADDLE funC't ion
PADlilLE (S ELECT)

haa

the

forn

'THEIRANDOMIZE PROCEDURE
RANllO~ilZI: is a pUle,edwce \/1 Ell DO parameters. Each U:!l'ie you TUn a given p !:o!l,ram using RANDOM, youw-J IJ ge,t_ the S9.lPe random jsequeuce un Leaa you u s.e RAN[)omZE. RAtllJOHIZ!:':, uaas a t1 me-depende]'l[ Leee tion co gene zar e a. star t.:lnspo;in
L

IiIhere SELECT is au inte8~r treated modulo .q to s'~V~c:'r CJlile of the four paddle inpu t s 'Dulfi'be '!'M Ill. 1, 2, and 3 " l'ADDLg~e zurns an i t'lt egeT in the range II to 25 j whiC'l1 re.presentB the pos i tIon of the se.Le ct ell pa d d l.e, A. lS'~Kvariable. :res:!.st.u;C!! ca n be connected in place of any of t.he .fou.:r
padd Ie s,

If

you try

to

read

t .... o

!laddl",g

too

quickly

in succession.

!;l.g.

for l /0,

the

random numbE!Jf generator.

The starting

PQin.t

)! 011 do

any inpcl t or oucpu r o,p.~.rill.ti on in )'01.1rprogram. the sCartili.!; poi nt, for the random sequence does

changes ea,ch !::1me If you use no 'not change!.

WRlTELN 'W]UTEl.N

(PA!lPLr:: (I'!); (,PADDLE {I)

tt1e hardwBTI! will tl1e loop
FOR I :'"

nat

be able. to keep up'.

A 81,11 tab:Le delay

1s gi ven by

THE: KEYPR'ESS F:UNCIION
Tl:uh funce t on, Which. has nopara,me.~e:rs. returns true j[f a key has been pressed. en '.he. key boa :rd s1m:e the J:lrogram s t:~rte'd or si nee the las t ~iQl~ t ne keyhoa.r-d was read. (wh_h:h~vO!r Is mcs t. recent). KID"PItESS dClE',g Dot

~ TO 3 DO:

The ~[JT'EONfunct ion has ~tr'i.',[ON (:SD..EC,[,)

the

form

'Whe:re SELEct i.s an int eger tt:eat.ed modulo It to se.l.e ct one 0.£ the three but ron iDP'Dt6 nuwb.: red 121, 1, and :1:, or che audio cas se t 1:-11 input ulilllbe:ied j. The BUTTOt!function returns a BOOLEANvalue of 1RUE Lf the sdect.ed,

game-control

but tan :1spres sad,

and FALSE otherwise.

102

APPLE PASCAl. LANGUAGE

SPECIAL UNITS ~03

li'he!.1l

liU1'TON(3) ie used to rMd the audio c.aSSE'tt:e Lnput; , it 8ample.~ the CI!5sette i'nputwhicll cll.angelltrom TRUE to FALSE. :!I!nd vice versa at aaeh zero c't:oseing of the input s1goa:l. along to turn

TRANSCENDENTAL FUNCTIO'NS:

are four TTL lev.,1 cueput s aV'sila:b1e on thE' game connector wi tl:i the but ton and padd 11" iop!.lt: s. The T'rLOOTprol:ed ur a is US!!4 these: outputs on or off" 'l'TLOOT has the for-m
TEOOT (SELlt:CT. DATA)

There

'THE TRANSCEND UNI1
In Apple Pasl;:,lOl. the I:ranB,c.elldental function!> are .!lot built, i~to .tlle language" To use. this set of futu.c.tiolls you !illS!: place the declarat1.oD. IJSES TRANSCEND;,

where

SELECT is

'f'IL eurp uts

numbered

an :!.r!l:eg,er treated ~. .I., 2, and

!JI(ldlJla 4 to select one of ·ttl.. four :3. DATA is:c! BOOLEAN 'E'!!:x;press ion. is ttl 't"D Bid to FJ,LSE.

iD!Illed:tat€!iy liner the. PROGRAM he'IIIiTig. If you !rlsh to use, SOlY. AJ.lllL.ESTUFF wi.th the transcemlencal futiLctiollB. you would wri~e

If DATAis TRUE .,~heo tbE ,eelec.t ed output until TTLOOTie inVOkEd with the DATAset

USES TRANSCEND, APPLESTUFi,
11.1.1.!i,NGLE and NUMl!&R. arguments aT'e tilAl, rad.ia.ns. Ail of these Eum;:tiQIlB re'turn and the ANGLEa.guments are.hl real values. and ·v<!lm'!j.s returned The Eo 1101>'1-1]8 functions are

MAKING MUSIC: THE NOl'E PROCEDURE
NOTE (PITCH, DURATION)
where' PlICA is fr am, " thrQugh
A PIreH time.

Ilythe AT.AN fUfic'tion ~rovided:

B.re in

railiaM.,

SIN

(ANG1.E:)
(AllGLE)

cos
~ through SI'! !'loll DURATION an :lrn:eger iii
ATAN

an integer
25.5.

from

of ~ irs used for .8, reB t, a nd ~ thr ough 48 yi,e.id a. trullpe re.i! (approxim!l.tely) c!:rJ;"omatiC aca La , DURATION i!l in atbitr aryuoHB of
tN

(NUM!ER)
(NUMBER)

(Noee: rh Ls is the same Eunc tio1'l :!isStandard PascalL's ARCTAN)

NOTE (1,1)
A chrQlllatic

gtves

a click. played by the
follow.ing

E
program:

LOG (WMBER)

aca.l e h

SQRT (NllMll ED. )

USES APPI.ESro~F: VAR PITCH. [lURATlO~:

INTOOER;

3

BEGIN DURATIO~ := l~~:
FOR PITCR :'''- 1.2 TO HDO
DURATlOW) NOTE (PITCH.

10A APPLE PASCAL LANGUAGE

SP.ECIAL UNITS

105

106, APPLE PASCAl LANGUAGE

INTRODUCTION
ThIS appendix p:rCGentsB graphIcs p:rOgt:Dm ""ldctn is fullyanl;l.otated. both by a nan:a!:1 ve exp lana e ion and by ccpd ous C01!!!!lell.tsIn the sou rc:€ te'l!:t. This progl."BllI ill, foliolOf:d by COIIimI'llULtD.r'hs on the demonstraUon suppU ed w:th Apille F'aGcal. progrllmli A ward ,of caution .ils 'in order .eg.a:rd.ing a11 of these p'rogiC'ams,. They are p re s,eilted, :110 as to ~:I, VI" you eXilIIIples that you can run Without lilly rnodif1c:acioQ." a:tJ,'~ also study t:he source text Co see how it: works. They arc not 1~tended t.o 1Il~ models of 1:.11.1" best possib!@ j)rogramm.1ng techojque. that. lolOuld be enr I rely beYmJdthe scope of th Ls manusl. They do work, and Itl1.ey ~o. d,emonstrat,.Ej ways of doing cert".i" useful things .iQ AppI~ Pascal. "With chis ceut Jen 1.n mind, Me the programs as learning tools. One of the. bestw'ays tQ lea.:nu might be to t.y h1noducin,g modificatiolls into one DiE Ul,I!I'"

Ihis 111 a f.a1rl]l complicated program, Bec.lions. Firs t ve call wr1 ce a sketchy 'BEGIN
R.EP€A'r

60

We ""iIi deve Lcp it 1.n outline of the program:

the t r Iang Le, using the angle mETA") i ("Draw me rotated rriangle on che !;Ic:re~Q*) UtiTll. (ilComplet I" pa.t t efil has been erased "') UNT U. .KEYI'RE 5S (~R.otat~
'E.RIl.

(.Cree te a I'andolll l:t:i,llmgular pac tern"') ; !llllTA: - ("tandom number from 3 to 1s* J RE.PUT

t

'1'0 Ull

1

declalral:j skeleton

in th:l~, outline, \ole begin w1th a progralO hell.ding, a US.ES on, !lome use rul cons cants. 1;"'0 V'H::i:able. dec Lar'e t:l ems, and a. oE the inner REPEAT ,ij,ta:teiIien.t:

A FULLYANINOTAIED GRAPHICS PROGRAM
Tlte following !!flDle helpf~l ~rog1ram". PATTIilltlS. :J.s intended. to :illl!str.fLh~ pO:l.ntsabout Apple Pascal. The progralli creat.es pleasant g,ra.ph.iC!l by drawin,g .3. ~1:ia.o.gle on ehe IID:.:reen and t.hen ~ei?eatedly TOUting it by II few degreea.and redrawing 1c. The points of the triangle <I.re alway.l!i on the edge of an invisible drc:.le of 'rad1u6 95 (-which lEills the he:!tgnt of the screen) but apart :tr,om that it is a [,Ilndolll trta.ng,le. 'rile aogle. by 'whi~h it i.1! :rotated each time it is d:raw:n 19 also ran.dern, though U_ is alwaYll, between 3 and 15 degr@es. The color used to draw the tri,aJngli.e i9 REVERSE. 'wtddl. baa il1td guing ,effects when one ~ma&e is drc!lWIlover anothe_r "1'1<1 the: lil"les inters@ct at .13_11 angl es , Also, aa the I:rjangle is repe.OIJt,ed.ly rotated and r@d;ra~, a ca rcu Lar pat tern .its built tip; but 'tW~ntual1)' the triangle gets. rot at ed bac.k to ita nrigl.ila.l position. When 'chii'! happens, <Mch new im~g~ Is exact 1)' f!iuper-i.mposed on an oJ!.d one. Becaus,e of the REVERS.E color. this eraSes the oldlmaa,e! When all the old illlase~, have beellera;~,e.cl!. the IIrogram clears t.he sueaan, ,g,en@:ra.tes <I. Qi!'Ol tdangle wltha di:fferent shape. and star'ta a.ll over. Thill :rep€titiotl continues. 1llriLtil the U$er signal.s il: til halt by pressing any key. The KEYPRESSfunction" in the APPLE.STIJJ!'IIl' unit,. can be. used to Undo!.!!: Whether till" us,eI' has pleased a k."'Y' (KEYPRESS is described in Chapte[l: ].) The progni,m ill g1ven in full, wi th ccuanent s , at thf! end ~)'f this appendi'X. ~at follows is a. descr1.ption of how a program like. fhd.s be developed. Of course, in real life thf!l'e ou"emistakes and false starts. H<l!1:'e.lEer t.he sake of le,arn:hlg ,Bome prlm:iples ..... u prl:!telld tb.e development of t.he progrsm, proceedClO ",1ehoue aIU rch . dernonst.car;iflLl

!!I
~

USES

PIi,OGRAH PA1'FERNSi TURTI.EGRAPtUCS

,Al'l'LES'1'UrF;
{*&I.dmum

CONST ~!AXX 2SIil'; MAXY.. J91; ..

x.

and Y coordinates"'}

!!I !!I
[

RADIIJS ..'Ij'5: ("'!'ta dIus

of pattern'"

l

liARcrCLES:~ ••l;
TltETA;J •• J5;

BEGIN
REPEAT

CYCLES; "'ill
REP &AT

(*Cre'll ce a. random t:[1angular pattern"'); TaE'U.'A:" (*randolIlllllmber' from 3 1:.0 15*).

("'Rotate tDe triangle, lUI:!,n!,!: theaflglc TRE'rA"'): PENCOI...OR lREVERSE) ; (*Dr~w the. J!'ot;_,at,~d t1:ia.ng,le on th.i! ::H:t"een""); IF ("'the [ot·ateri triangle. matches th€ crI gi na L il:rf.iillgle"') THEN CYCLES: "CYGL.E5+ 1

END.

UNTIL CYCl..Es-2 ITNtIL KfUIlESS

fbe variable CYCLESts a. councer for the number of ti tiles the ni.a.l'Igh has b@ft(l :rotated back to its cr Lgf na I ,Position. WhellJCYCLES" , the 1 c!l:c'ular pa'~tern begins to be ",raBed becau.B~ each ];I!!.W t'r i angLe :is draWll in the REVERS~ coloI' nn top of a pr,,,,vious r r i a ng.l e , wt:t(HI CYGLI':S=2, 'the entire par cern has; been eraa ed, W", can now bef!;1n r,eplacing eomment6 '!il1.th.ac tuel sea t.ernel1.ts • fOll: example" "Ie already have a var t ab Le , THETA, whh:h is 1:11:", number of degrees to ~tate tbe pattern" So it as nat.u'ra I. to replace the first Comment in the inner REPEAT with a Mil 1:0 8. procedu,e named R,OTA.![ which ·takes an INIEGKR parameter., The val ce usedfot' 11;1,~p<l'[alll€.t:(;!r

C.!l.[J

rnll.t

~08 APPLE PASCAL LANGUAGE

DEMONSTRATlON PROGRAMS

109

will ~e the have

va"dable

THETA.

ROTATE will

need

t.o be declared;

now we

of the thil. t'd coroer are, :saved, :in a variable only I:es; t. all, f 0 11.ows ;

m!Pled CORNER.

PROCEDURE

ru'lIIITE

(ANGLE:

INTEGER)

i

lIE' TRGI. [3I-CORNE.R

TIlI::N CYCUS:

"'CYCLES+i

("'To be C-orupleted ..•• 1!J) BEGIN
REPEA"r

At this pattern"');

point,

the pt"Og,HI.ID Is

as !Colll.oW,":

TKETA:=(*randnro number from 3 to 15*);
C'l'CLES:"'~

(1I;Ci(<!,ate a r andom triangular

PROGRAM

USES 1'UJ:tTLEGRAPU(CS.A1'PLiESTllfF;
GONST MAJCt=2 80.i 11l!Jl.Y"B~l. RADIUS""95; (ioRadiuli TYPE POIN'f"'RECORD ("'MadmulIL X and of pattern"') Y cooit"dinat,es*)

PAI~ERNS;

REPEAl
ROTA1'E (THETA) :

To dl:aWf the triangle 011 the Bc.:r:een. we IlIt1st fi t"&t COliS Lde r ho'.ol the t r Lang l,e 15 t'epresen ted rn ·merom:)'. We can t.h1nkol the triangle as three po1.nts; bow I;i,hall we t"epreseOii: II point~ '" PQint: ean be repre,Benl:ed by cwo l1LrrnllE:t"s ~ an X ,end a Y coord:Lnate. Th~l:efoJr,e we Ci>!:I define a type. POINT. as shown he 10"" • Then we can repre,sen ~ the triJ:l'Ilgle as an array named TRGL. 0:1' type POINT. We ".i11 abo decl.a re a v.arblile C to
U9!!

K: ~ •• MAD: :

Y:I1 •• ~Y
1/AR CYCLES:0 •• ,2: [1 •• 31, OF'

THETA;3 ••!5~
TRGL ;ARUY

as an ind~

'for

the

arl:"ay T,RGL.

'<'onn;

C:1..3:
COR.NIER: POllITT; .PROCEiDURE ROIA'I' I'.: (AtlGLl:; : INTEGER);
llIUS'~

TYPE POHlT-RECO!l.D

l\; 0 •• ,MAX}{: '1':0 •• MAX"

("'To be ,"cmpleteoii :Ill TRGL and leave BEGIN

Laave

[I~W

corner

coord:lnate.lO

tU'I:"~ Le at

third

EClrn.el:.

"'1

Vi\R CYCLES;iiI••2;
'['HUll:' 3 •• 15;
TRGl.:ARRl\,'i[I •• 3l OF PCIN'X;

REPEAt

C: I •• 3.

(*Cr,eate a "ando~ t.rLangu Lar pact.et"n*). THETA;s<*[andom nu~het" from 3 to 15*).
CYCLES;-~

RE_PEAT
Assuming that tbe ROTATEprocedure Leavus the rc t at ed cQol:dinates in 1'lt':l:oy TRCL and that it leaves [he tllrtle at the th i rd corner of the t:riangl,,.,, we, can use CII,r~es ian !ll"8phil:s. to draw the fie". t:da.ngle:

the

END.
fENCOLOR(REVERSE);
FOR C: -] "00 :l DO IItOVE1'O C1RCI.. [C! ,. X. TRGL

ROTATE (ntETA) ; PENCOLOR(REVERSE) .~ lOR C;"l TO :J DO MDVE·lO,(TltGL.[C) IF TRGL (J. l-CORN EE. THE~ C'lCLE5; lllITIL CYC:L.ES.. .2. 1.JNU1 KEn',R.ESS

-cr CLES +l

.x,

TRGLIC]

.'OJ

Ie I • 'I)

;

The remaining c.(l·mment in the wbethel:" the ro t ar ed t:riangle aBsum€!that whe.n the t["iangle

:!.Imet" REPEAT Stat.ement

I:H_Hs

for

m;;c ches the odginal one. To Bchf eve :Is U rst crea.t:ecl the eooxdIna tea

I:esting th! s ,

I 1:. , I

Thl'! inner REPEAT s taJt;!!'II!ent wi 11 repea t.e'l:ily rc t at a the tria.ngle and d.1."I1'" ile. using the REVERSE colol:. bu:i Iding up e ct rcu.lae pa tt@1:1'1 on the screen and t.li](m eirasing it by itra.~ing aver it. When the pat ~e'rn has been e~aaed.. the inner REPEAT t.e-r-mina tell"

ml

APPLE PASCAL LANGUAGE

DEMONSTRATION PROGRAMS

111

N(lWIli!.

the

can bEgiQ tilling out e.r REPEAT t:eqtilre

in

the

outeI'

REPEAt.

The

st&tellifmtl3

added

to

JIJ!.B:l.TRAR'i.

II'no .-.... .."er

". "'''''''11.'''' ])l:'oce d UJ:e .• """"-"'~ "''''.

And a ftml!t.ion,

TIl,e mail], prog1:llJIi. tiEl n.early cornplet,e.. Itr,em;!iml {mIl' to add oue lILew variable named CEN1RK (of l:J"pe FOINT). and a fe ... .itl.it.ial1zing stateTilentll befo't"f1 the, (lUl;erll:EPI!:AT:

FUNCTlOI-lAR.llTTRAR'l (UlW , III G~ : mT:ElGSR) ; INTEGER: (ioTa be c.ompleted; 'm'p.st. rerum an in Leger value range LOW •• I:UGH.~)

VAl!: CYCLES:~ •• 2; In the

THE'rA:3 •• 15;
TRGL:ARRA'l [1 •• J1

OF POltlT';

~ROCEDURE MAKETRGL:
("'To be c.olllpleted,; must lea,vlE! eo rne r c{lord.1Ilatios and a.Lae initialize CORlll,e;R with clwr-di.l'I<ltes of cOfiler.*)
BEGIN UPEAl' MAl!:E"FRGL ;

C: 1 •• 3: itn TRCL third
CoRNER: p(J!NT • CENTER :POINT:

:aEGUl RANDONIZE. I Nl!.TW RILE
j

("'To

TRETA: =ARBITRARY (3, CYCUS; ""i
REPEAT

l5);

iJattemlo) (jOChoos~ Bogle for rol:ating (*Clear the cyde counter*l

(ioMake l:.dal1(gl.llal:

C~NTE.R",X ;"TIlRTI.U tri~mgle*)

CENTER.Y:=111R1U'f~

get a dlffenmt sequeu ce each time program is exe;:ut-edit) ("'Always do this 1:0 use 'VD RTtE.GRAPIHCS* 1 (*The turtle is at th!l: c.e.~1:I'!:r ecause b DU.T11lRTLE leaves it there. Save
Lt.s
coo rdd 1111' t es

111 CENTEll:. 11)

I '.X, taG!. Ie) H nOL [3] =CORNER 1'H.EN CYC'L.I::S:=CYCL.E~Hl UNTIL CYGLES...2
UNTIL KEiP.R.ESS

ROT ATE (THE TA) ; P£NCOLOR(REVERS£) ; .FOR G ;0,,1 '00 3 DO MOVETO (TRGL [C

..Y > ;
I:JlITIL CYCLES"'2 UNTIL KEYPR.ESS J:lND. The mliil'iL progrllm and 1.s comp Ie r e , and
1'Im.!

END. The oUJter REPKAT f1 rB t ca Ll.s MAI{E'rRGL. T'hb procedll:re. sti~l [0 be d.efined. chOOSf1,Sth!b~(>_ ra ..dolll pOin't!l en D. d rc!.e ,of radius 95 and stOI:I'!S their coordi:patl'!13 in t~u:: array TR.GL. It al.so stores the coor!linates ~f the third ce rme r ill the 'Variable mRNER.
Ne:xt., !:be hmc:.l:iol'l ARlHTRARY is

we mu,s!:. define AmH 1" RAR'r •

the

two

pr ccedur es

MllKETIiGL

ROTATE !'Imj tbe

f un ct ion

the oumber of degree,s

to rotate

used to, aS5.ign c.he [.T::!.angl~.

a nndQm varue

co mETA"

'The AlmIl'RILRY funl1'.tiol1 is shown in the! complete program at: che this appemlh;. It b <! simpUfied ve cs Io n of che RJl,NDfunction ClJ.~pt e r .,. in the d[sclls~d.Dn of 'the buil t -d.n Eun ct ion Rl!NDOM. RAND 'handles
BOOLEAN.

end

0'[

given

in

unac cep teb Ie pa r amet

e'ra

by setting

a VAR p.arameter

of

rype'

ARBITR/UlY Iloes n01: need this el::rOIl:-handl.ing capability Gince it wiIl always be called wi t~ COM Cants <IS p~ r amet e rs. Slmile:r 1),. RAND hae a spe,c:1..1lI1provision for the case To1oeTIl the HI,GE[ and LOW parameters are eqW11.; .ARBITRARY do es not harve this p'l:ovi.siQn, ·:llJd HIGH mU!H be stric.l:.ly sreatem: than LOW. l'.n other resJi@c[s" ARBITRARY is the same as RAND. Inddent~il.ly. "[lie cOtlplexity of the calculatioon in both vera f.ons is due to the fact that two uUmhe1".51 cannot be added O!b aubt.eaet ed if the result would eN.ce~ 'the value KAXII'lT'027,61). The funct 1o'n has to get arcund th.1s H.mi t8.ticm by l.iJ!a,i.rlg the inl:emeciia'tl! 'ValUE' m. .

112

APPlE PASCAL LANGUAGE

DEMONSTRATION PROGRAMS

113

I

The MAICE:,[H:GL procedun" nIHil; choose r:b.ree rundcje points on a circle of r.!li.dil.ls !f5, wah its center Il.I: CENTER. To select. I:hre;e random pOints,

the

following

method is used:

!JAR I: I. .,3;

I • I
1

FOR I: -I TO 3, 00 BEGIN ("'Move t.h e ru n le.~o the CKNTE.R polin; MOVETO (CEN,!,ER • X • CENTER .,y ) : (~Select a r,afldom d:h:~ction ce JCoyethe

i~
I!I
II

3

The ROTATE!l rOQ:edure works very IIIJ.lc.hlib, the !iAKETIlGL procedure. but i!lB I: eed of 'Os1ng ra~om aug Les it uses thl;! an,gle:a found ill. I: he DlRECTllONI array ~~ af ter ,lIddillg ANGLE to eacll of them and takilli! ehe result MOl) l6,J'j. It &oorer; the re!'lulting jloirl,'ts in, the T&GL array" but does not change CORNER. Th£' effect is to replace each POi-Tit i~ TRGL wieh B n.ew ~oil"i.t czea teclby rota ticn through I'lNGl.E degreEs,. The ~omple ili:e ROTATE pro eedure is
PEl.OC&D!IR.E ROTATE(ANGLE: VAIl. I: 1.,.3: INTEGER) ;

~)

turtle

<I'IoTay

f.rom tnl.s

CRlftER" a~ray

and sto're cbi:ls a:ngle .in an array lIeed t.o be dec Lar ed ; :II ), !nRECTION [I J:=A'Rl:U.TRAR 'i (il. 359) ;

named. IlIREI::T'l.ON;

"'fl.l.

[ii!I
,~
'I ,II

i!i
:::::.

..

BEGIN

PENCOLOR (NONE) ;

FOR 1·; "'I :1'0 J DO BKGH4
MOVETO(CENTER. X, CENTER. Y) ; [HRECl']ON [II : '" (D iUtECTION [1]+ANGLI;) TURNtO {DIRECTION[ll}; MOVE(UDIUS) ; TRGL (:n:j .X:~ruRTLEX: MOD

J6~.

("'Turn

the. tu n lee :lathe FIIRNTO(DlREC·nON lIJ ); edga of

se Lec ted

dj .ection;

:II)

L~
Nove

TRGL Ill.

Y ="TU RILE'!

END
END,

("'Move 01.11:tD th~ MOVE{RADIUS} •

the

e;irrle:

*)

1
in the TRGL array; *)

tu ["·tl,",':8 l'.oordiJ1.lll:es TIl;GL [IlI.X; =TURT1EX: J.RCL [li.]; •

: -TU RILEY END

(*s toret:he

I

the DIRECTIOtl' a;;r:ay will be used by tlle ROTATE procedure.~o re vill need to be dec.Laee d ·at the beeinning of rhe prQgira.m - 11.0't li'Bhin the
MAK~TRGL?~ocedu~e.

I~
I

t.he t :the MOD 361 ope :ration is ueceBllary be cau SI:! if the prog!ram fo r a 10ilg t !me., the res ult of DIRECTION [I I+ANGLE cou.Ld eventu.aU.y
eJl:ce.~d MAXIN'r and cause a :n,m-time er-ror.

r an

I
1

I

The G:cmplete

prograe

begins

on the

following

page ,

any th i ng at t;hi!:! po:! nt, We set the color to FOR at a tem~mt • Mtert.h["e~ tim!:!!! through '~h,e fOR at a t.etnenr , thO! met le. :is at che ttl:! r'd t.[J:HU~ r !I]f' dl'~ ~[I.an.gle., so we save H.s pos_[ ~ Len in tbe CORNERvsri ablE' fOr uae in ttl,,,, maiD pt:ogram.
S1 [Ice we doll.' t Wllnt to dra!,'

l,3
I

l'IOI'lEbel ore

sea r r.i.ng the

The

t.owplct,e

procedure

ts

PRO GEDURE MAl( B1'RGL ; !fAR I: L. 3. BEG[N i'Et4C:OLOR(NONE) ; FOR [: .. 1 To 3 !Xl ~ECIN MOVEl'O{CEtlTER. , C!lNIEF;. 1); tHREe'nON m : "'ARBITRARY {~, 359) TU!(lI!IOUHRECTION (IJ : MO'II"EUJl.Dlll S) : TRGL II].Y!,"T"URTLE'l RND; CORN"_p".X; -Til an, EX ;

,;

TRGL.[I).X:=TURT"LEX.;

t;OIWEP;:. Y ; -TURTLEY
Elfl.l ;

114 APPLE PASCAL LANGUAGE

DEMONSTRATION PROGRAMS

H5

PItOGRlIM lI'ATTERNS;

US ES TUlIT'l.EGR.APlLl CS •M'Pl.ESTI1F.F;

(1!"'oit.***"'*"'*"'''''''ot*",,,,******,,,,,,,,,,t.t.!;.t.tH***********'''***''''''':I<:I<"''''****:I<****''''~*'II'**}
PROCEDURE, MA&ETRGL:
II! '" II!'ittt· ..

CONS!

( II'#!'. '" '" '"

*...,... 10 '" * It '" '*.rII* '"#I '" 11'. '" '" '" '" * lII:*ir1t .. '" II! Ii'"'""''''** *

* * oil *"'*'" "',;,II'"* .il-jIo'lI ), ••

("'Maximum X an.!"! 'I coordinates"')
MAXX"'2,Sr;!';, HAXY-l ~'l ; ["'Radius o,f pat:tertli;lt)

lAD [,IJ S"9 S j,

mE

( II: '.111'"It'" ",ell'.#! '" '" '" '" '" ",''' •••

'."'Iii.'"'"'"*

(*Make ll. tria.llgle, defi ned by 'tbr.lO!erandomly chos eu vped n'tS ar a di s cance lUJlUJS frGwthl'! poi I'l't CENTER. C~OOOl~each ~Qlrn: hy starting at I:ENT~!I" cunr:!n,!J'j to a random sngke , and IlIClvi.ng the d.1stance R.t.\IlIUS. St ar e (he angl~ b. DIRECTION. the pOint coordlna'tl!s 10 'TRGi, and the" third point (for f~ture refer~lu::e)in. COIUIER. Notic.e how co:verde]lltly eh I s is don>!: by l!!!Ovtng tlite turtle around w:l1:h the color NONE. )

II! '" '" II! *1t1111

* oil "''''

'" '" '" '" '"

",.:it .... ,

* '""''''''''''''''II'"* * it ",it",,,, *,)

VAR 1;1.,3:
BEGIN PeNCQ'LOR {NONE} ;
fOR I : .. 1 TO 3 00 BEGIN KOVE'OO (CEN1'ER.X. CENua.

(fiT-his,

type, store\!! ()fie se I: 0.£ III::re,en. co(Io!'dlnete:s:*) POIN.I"RECORn Xl"., .MUZi
Y:'i\l, •• MAXY

END.
('" 1I:;Ii iii ilrih."

'0 ;

VAll. fWCO'llDter f()~ bow many time.!! t:r:l:a.n8,le hasbeelll rGtated b!lCK tQ its in:! t:J!.al pc's1t1on*) CYCLES: iii •• 2; (''''AngJlefo!; I:oi:a't:inlil, b'iansle*) tHETA: 3 • '"15; 'l"Array to 9t:or'e t:.oQl!'d:lnllt,e;!l,of cc['ut;!U of trbtl,gie*)' TRGL tI\RRAY ~1 •• OF POI.Ni: ("'Index h~ corners Q·f U'fang:!Leii) C; 1 ,,. 3.i (,*Point to IItore coordinates of one. corner ef triangle, be:fore allY r'ota,t1onsil) COaHER:, POINT ~ (*P!;'in,( to store. cOfJrd:i.ml'tes Qf center of~cteen*) CEIi'l:ER:PQWT; (*A:rtll), to lIt.ore dir'ect'l:oo angle!:! used to ,tl;enetate triAngl.!!*) DIRECTION:AltRAY [1 •• 3~ OF INTEGER;.

*'"'"'"

* "'**'"'"'"*"'' ' '"'""'' '

01:11: "'''''iI''Ii'll '" '" oil *"'11* '"'"'""''''.... '''* * * oil iul'"'"11.1:.1:

.'.it.."' ' "'"'"

DlRECTl'ON[I) ;-AR.fHTRARY{0, J59};
TlJRNTO (DIRECTIO~ [I] ) ; llOVE (RADIUS TRCL tI] •.X.' =IURTLEX; TIi..CL (I l'" : -TURTLI>Y Y END: CORNEl!. "X: =:ruRTLEX, CI}RNEI!..Y:=TURTLi!:'i .imD;

II)

>:

n

(11 '" '" '" ***11'11* "':I: "'*11'" '" oil '" *** 1111'" '" '" '" '" it ..*1,.,""'" ' I'ROCEl}UaE ROTATE (ANGLE: INTEGER) ;

*'"'"

*.... '"'"* "'",,""':II '" '" '" "'''' *'" *"'*

I< '" '" I< "' ..

***,;, '"}
in

("'Il:.Qtate chc triallg11:' definf!tI by point mmrdin:lJt£'B in TRGI. anti angles DIREC'rI.OIi .• by adding ANGLE CO the angles lIt .DIREC1'lON, t ak Ing 'tile ir!!.sul t MOil :O6!!. and using 'theae angles ttl determim! the neW' corner

coord1nate~.
VAF. 1,;1 ••

Again the

tl,l'[tle

is

moved ar ound us1ngl:he

color

NONE,"')

3;

BEGIN

("'*****"'*"' ••• *·**"'*****ll".'it •••• ",************",*******"",;r,"'*iht'fU,*"'*"'*"'**"'***) FONCTIONARBl'rRARt ~l.OW. mGH.: INTEGER} : lNl'IEGru!.; (i'lRet:uros II paeudo""'rs.ndolii .integer in the t'ange LOti Ch.l'ough. HIGH. 'l:bi!J func:.lI:1oo 9'ho,.!l.d only be 'oolled Wit1'l ComHant:s as p&'I"A!IIet!.n:s., HIGH mU9't be strictly grellterthan LOW; 1t lI:iU~t. nut be equal to LOW. Also the d.U~erence be,t"'eeo HIGEl and l.O'W tlll!5t not IliKCl'!ed MAJUNT.'")

PENCO!"ORU~ONB 1 j

PUR I: "'1 TO 3,00 BEGIN HOVtTO (CENl'ER •.X. CENTER. "i) : D [RECTl ON [1] : = (D lREeT ION (1.l +A1lGl. E I ~IOD

.3 M~•

TU&NTO(DIRECTION [I] ) ;~
MOVE (RADIUS) •

TRGL[lJ .X.=TIlRTLEX;
TRGL {I] •