Tải bản đầy đủ

Pitman publishing fundamentals of data structures oct 1984 ISBN 0273020722


APPENDIXA:SPARKS
Thissectionismeantforpeoplewhodomostoftheirprogrammingin
FORTRAN.FORTRANhasthedistinctionofbeingessentiallytheearliest
higherlevelprogramminglanguage,developedabout1957byagroupatIBM.
Sincethenitanditsderivativeshavebecomeestablishedastheprimary
languageforscientificandengineeringcomputation.But,withourgreater
understandingoftheprocessofcreatingprogramshascomearealizationofthe
deficienciesofFORTRAN.Creatingaprogramisproperlythoughtofastakinga
realworldproblemandtranslatingitintoacomputersolution.Conceptsinthe
realworldsuchasageneologytreeoraqueueofairplanesmustbetranslated
intocomputerconcepts.Alanguageisgoodifitenablesonetodescribethese
abstractionsoftherealworldinanaturalway.Perhapsbecauseofitsveryearly
development,FORTRANlacksmanysuchfeatures.Inthisappendixweexplore
theideaofwritingapreprocessorforFORTRANwhichinexpensivelyadds
someofthesemissingfeatures.
ApreprocessorisaprogramwhichtranslatesstatementswritteninalanguageX
intoFORTRAN.InourcaseXiscalledSPARKS.Suchaprogramisnormally
calledacompilersowhygiveitthespecialnamepreprocessor?Apreprocessor
isdistinguishedfromacompilerinthefollowingway:thesourceandtarget
languagehavemanystatementsincommon.

Suchatranslatorhasmanyadvantages.Mostimportantlyitpreservesaclose
connectionwithFORTRAN.DespiteFORTRAN'smanynegativeattributes,it
hasseveralpracticalpluses:1)itisalmostalwaysavailableandcompilersare
oftengood,2)thereisalanguagestandardwhichallowsadegreeofportability
notobtainablewithotherlanguages,3)thereareextensivesubroutinelibraries,
and4)thereisalargelaborforcefamiliarwithit.ThesereasonsgiveFORTRAN
astrongholdintheindustrialmarketplace.AstructuredFORTRANtranslator
preservesthesevirtueswhileitaugmentsthelanguagewithimprovedsyntactical
constructsandotherusefulfeatures.
Anotherconsiderationisthatatmanyinstallationsanicelystructuredlanguage
isunavailable.Inthiseventatranslatorprovidesasimplemeansfor
supplementinganexistingFORTRANcapability.Thetranslatortobedescribed
herecanbeobtainedbywritingtotheaddressgivenattheendofthisappendix.


InordertoseethedifferencebetweenFORTRANandSPARKSconsiderwriting
aprogramwhichsearchesforXinthesortedarrayofintegersA(N),N 100.
TheoutputistheintegerJwhichiseitherzeroifXisnotfoundorA(J)=X,1
J N.Themethodusedhereisthewellknownbinarysearchalgorithm.The
FORTRANversionlookssomethinglikethis:
SUBROUTINEBINS(A,N,X,J)
IMPLICITINTEGER(A-Z)
DIMENSIONA(100)
BOT=1
TOP=N
J=0
100IF(BOT.GT.TOP)RETURN
MID=(BOT+TOP)/2
IF(X.GE.A(MID))GOTO101
TOP=MID-1
GOTO100
101IF(X.EQ.A(MID))GOTO102
BOT=MID+1
GOTO100
102J=MID
RETURN
END

Thismaynotbethe"best"waytowritethisprogram,butitisareasonable
attempt.NowwewritethisalgorithminSPARKS.


SUBROUTINEBINS(A,N,X,J)


IMPLICITINTEGER(A-Z)
DIMENSIONA(100)
BOT=1;TOP=N;J=0
WHILEBOT.LE.TOPDO
MID=(BOT+TOP)/2
CASE
:X.LT.A(MID):TOP=MID-1
:X.GT.A(MID):BOT=MID+1
:ELSE:J=MID;RETURN
ENDCASE
REPEAT
RETURN
END

Thedifferencebetweenthesetwoalgorithmsmaynotbedramatic,butitis
significant.TheWHILEandCASEstatementsallowthealgorithmtobe
describedinamorenaturalway.Theprogramcanbereadfromtoptobottom
withoutyoureyesconstantlyjumpingupanddownthepage.Whensuch
improvementsareconsistentlyadoptedinalargesoftwareproject,theresulting
codeisboundtobeeasiertocomprehend.
WebeginbydefiningpreciselytheSPARKSlanguage.Adistinctionismade
betweenFORTRANstatementsandSPARKSstatements.Thelatterare
recognizedbycertainkeywordsand/ordelimiters.Allotherstatementsare
regardedasFORTRANandarepasseddirectlytotheFORTRANcompiler
withoutalteration.Thus,SPARKSiscompatiblewithFORTRANanda
FORTRANprogramisaSPARKSprogram.SPARKSstatementscausethe
translatortoproduceANSIFORTRANstatementswhichaccomplishthe
equivalentcomputation.Hence,thelocalcompilerultimatelydefinesthe
semanticsofallSPARKSstatements.


Thereservedwordsandspecialsymbolsare:
BYCASECYCLEDOELSEENDCASE
ENDIFEOJEXITFORIFLOOP
REPEATUNTILWHILETOTHEN:
;//

Reservedwordsmustalwaysbesurroundedbyblanks.Reservedmeansthey
cannotbeusedbytheprogrammerasvariables.
WenowdefinetheSPARKSstatementsbygivingtheirFORTRANequivalents.
Inthefollowinganyreferencetotheterm"statements"ismeanttoincludeboth
SPARKSandFORTRANstatements.TherearesixbasicSPARKSstatements,
twowhichimprovethetestingofcasesandfourwhichimprovethedescription
oflooping.
IFcondTHENIF(.NOT.(cond))GOTO100
S1S1
ELSEGOTO101
S2100S2
ENDIF101CONTINUE

S1andS2arearbitrarysizegroupsofstatements.Condmustbealegal
FORTRANconditional.TheELSEclauseisoptionalbuttheENDIFisrequired
anditalwaysterminatestheinnermostIF.

S1,S2,...,Sn+1arearbitrarysizegroupsofstatements.Cond1,cond2,...,condn
arelegalFORTRANconditionals.ThesymbolELSEsurroundedbycolons
designatesthatSn+lwillbeautomaticallyexecutedifallpreviousconditionsare
false.Thispartofthecasestatementisoptional.
Thefourloopingstatementsare:


WHILEcondDO100IF(.NOT.(cond))GOTO101
SS
REPEATGOTO100
101CONTINUE

SisanarbitrarygroupofstatementsandcondalegalFORTRANconditional.
LOOP100CONTINUE
SS
UNTILcondREPEATIF(.NOT.(cond))GOTO100

Sandcondarethesameasforthewhilestatementimmediatelypreceding.
LOOP100CONTINUE
SS
REPEATGOTO100
101CONTINUE

Sisanarbitrarysizegroupofstatements.
FORvble=explTOexp2BYexp3DO
S
REPEAT

Thishasatranslationof:
vble=expl
GOTO100
102vble=vble+exp3
100IF((vble-(exp2))*(exp3).GT.0)GOTO101
S


GOTO102
101CONTINUE

Thethreeexpressionsexp1,exp2,exp3areallowedtobearbitraryFORTRAN
arithmeticexpressionsofanytype.Similarlyvblemaybeofanytype.However,
thecomparisontestismadeagainstintegerzero.Sinceexp2andexp3arereevaluatedeachtimethroughtheloop,caremustbetakeninitsuse.
EXITisaSPARKSstatementwhichcausesatransferofcontroltothefirst
statementoutsideoftheinnermostLOOP-REPEATstatementwhichcontainsit.
Oneexampleofitsuseis:
LOOP100CONTINUE
S1S1
IFcondTHENEXITIF(.NOT.(cond))GOTO102
ENDIFGOTO101
S2102CONTINUE
REPEATS2
GOTO100
101CONTINUE

AgeneralizationofthisstatementallowsEXITtobeusedwithinanyofthefour
SPARKSloopingstatements:WHILE,LOOP,LOOP-UNTILandFOR.When
executed,EXITbranchestothestatementimmediatelyfollowingtheinnermost
loopingstatementwhichcontainsit.
ThestatementCYCLEisalsousedwithinanySPARKSloopingstatement.Its
executioncausesabranchtotheendoftheinnermostloopwhichcontainsit.A
testmaybemadeandifpassedthenextiterationistaken.Anexampleoftheuse
ofEXITandCYCLEfollow.
LOOP100CONTINUE
S1S1


CASEIF(.NOT.(cond1)GOTO103
:cond1:EXITGOTO102
:cond2:CYCLEIF(.NOT.(cond2))GOTO104
ENDCASE103GOTO101
S2CONTINUE
REPEAT104S2
GOTO100
101CONTINUE
102

EOJorendofjobmustappearattheendoftheentireSPARKSprogram.Asa
statement,itmustappearsomewhereincolumns7through72andsurrounded
byblanks.
ENDIFisusedtoterminatetheIFandENDCASEtoterminatetheCASE
statement.REPEATterminatestheloopingstatementsWHILE,LOOPandFOR.
LabelsfollowtheFORTRANconventionofbeingnumericandincolumnsone
tofive.
Theuseofdoubleslashisasadelimiterforcomments.Thusonecanwrite
//Thisisacomment//
andallcharacterswithinthedoubleslasheswillbeignored.Commentsare
restrictedtoonelineandFORTRANcommentsareallowed.
Thesemi-coloncanbeusedtoincludemorethanonestatementonasingleline
Forexample,beginningincolumnonethestatement
99999A=B+C;C=D+E;X=A
wouldbelegalinSPARKS.Toincludeasemicoloninahollerithfielditshould
befollowedbyasecondsemicolon.Thiswillbedeletedintheresulting
FORTRAN.


Wearenowreadytodescribetheoperationofthetranslator.Twodesign
approachesarefeasible.Thefirstisatable-drivenmethodwhichscansa
programandrecognizeskeywords.Thisapproachisessentiallythewaya
compilerworksinthatitrequiresascanner,asymboltable(thoughlimited),
verylimitedparsingandthegenerationofobject(FORTRAN)code.Asecond
approachistowriteageneralmacropreprocessorandthentodefineeach
SPARKSstatementasanewmacro.Suchaprocessorisusuallysmalland
allowstheusertoeasilydefinenewconstructs.However,theseprocessorstend
tobeslowerthantheapproachofdirecttranslation.Moreover,itishardtobuild
intheappropriateerrordetectionandrecoveryfacilitieswhicharesorelyneeded
ifSPARKSistobeusedseriously.Therefore,wehavechosenthefirstapproach.
FigureA.1containsaflowdescriptionofthetranslator.

FigureA.1:OverviewofSPARKSTranslator
Themainprocessingloopconsistsofdeterminingthenextstatementand
branchingwithinalargeCASE.ThisdoeswhatevertranslationintoFORTRAN
isnecessary.WhenEOJisfoundtheloopisbrokenandtheprogramis
concluded.
TheSPARKStranslatorwasfirstwritteninSPARKS.Theoriginalversionwas
handtranslatedintoFORTRANtoproduceourfirstrunningsystem.Sincethat
timeithasbeenusedbyavarietyofpeopleandclasses.Thusitisrunningfar
betterthantheoriginalversion.Nevertheless,thetranslatorhasnotbeenproved
correctandsoitmustbeusedwithcaution.


Extensions
BelowisalistofpossibleextensionsforSPARKS.Somearerelativelyeasyto
implement,whileothersrequireagreatdealofeffort.
E.1SpecialcasesoftheCASEstatement
CASESGN:exp:CASE:integervariable:
:.EQ.0:S1:1:S1
:.LT.0:S2and:2:S2
:.GT.0:S3
ENDCASE:n:Sn
ENDCASE

ThefirstgetstranslatedintotheFORTRANarithmeticIFstatement.Thesecond
formistranslatedintoaFORTRANcomputedgoto.
E.2AsimpleformoftheFORstatementwouldlooklike
LOOPexpTIMES
S
REPEAT

whereexpisanexpressionwhichevaluatestoanon-negativeinteger.The
statementsmeaningcanbedescribedbytheSPARKSforstatement:
FORITEMP=1TOexpDO
S
REPEAT

AninternalintegervariableITEMPmustbecreated.


E.3IfFappearsincolumnonethenallsubsequentcardsareassumedtobepure
FORTRAN.TheyarepasseddirectlytotheoutputuntilanFisencounteredin
columnone.
E.4Addthecapabilityofprofilingaprogrambydeterminingthenumberof
executionsofeachloopduringasingleexecutionandthevalueofconditional
expressions.
HINT:Foreachsubroutinedeclareasetofvariableswhichcanbeinsertedafter
encounteringaWHILE,LOOP,REPEAT,FOR,THENorELSEstatement.At
theendofeachsubroutineawritestatementprintsthevaluesofthesecounters.
E.5Addthemultiplereplacementstatementsothat
A=B=C=D+E
istranslatedinto
C=D+E;B=C;A=B
E.6Addthevectorreplacementstatementsothat
(A,B,C)=(X+Y,10,2*E)
producesA=X+Y:B=10;C=2*E
E.7Addanarray"fill"statementsothat
NAME(*)

exp1,exp2,exp3

getstranslatedinto
NAME(1)=exp1;NAME(2)=exp2;NAME(3)=exp3
E.8IntroduceappropriatesyntaxandreasonableconventionssothatSPARKs
programscanberecursive.
HINT:Mutuallyrecursiveprogramsaregatheredtogetherinamodule,
MODULE(X(A,B,C)(100))whosenameisX,whoseparametersareA,B,Cand
whosestacksizeshouldbe100.


E.9AddacharacterstringcapabilitytoSPARKS.
E.10Addaninternalprocedurecapabilitytoaidtheprogrammerindoingtopdownprogramrefinement.
E.11AttachsequencenumberstotheresultingFORTRANoutputwhichrelates
eachstatementbacktotheoriginalSPARKSstatementwhichgeneratedit.This
isparticularlyhelpfulfordebugging.
E.12AlongwiththeindentedSPARKSsourceprintanumberwhichrepresents
thelevelofnestingofeachstatement.
E.13GeneralizetheEXITstatementsothatuponitsexecutionitcanbeassigned
avalue,e.g.,
LOOP
S1
IFcondlTHENEXIT:exp1:ENDIF
S2
IFcond2THENEXIT:exp2:ENDIF
S3
REPEAT

willassigneitherexplorexp2asthevalueofthevariableEXIT.
E.14Supplyasimplifiedreadandwritestatement.Forexample,allowfor
hollerithstringstobeincludedwithinquotesandtranslatedtothenHx1...xn
format.
AllfurtherquestionsaboutthedefinitionofSPARKSshouldbeaddressedto:
Chairman,SPARKSUsersGroup
ComputerScience,PowellHall
UniversityofSouthernCalifornia


LosAngeles,California9007
ToreceiveacompleteANSIFORTRANversionofSPARKSsend$20.00(for
postageandhandling)toDr.EllisHorowitzattheaboveaddress.
GotoAppendixBBacktoTableofContents



APPENDIXB:ETHICALCODEIN
INFORMATIONPROCESSING


ACMCODEOFPROFESSIONAL
CONDUCT


PREAMBLE
Recognitionofprofessionalstatusbythepublicdependsnotonlyonskilland
dedicationbutalsoonadherencetoarecognizedcodeofProfessionalConduct.
ThefollowingCodesetsforththegeneralprinciples(Canons),professional
ideals(EthicalConsiderations),andmandatoryrules(DisciplinaryRules)
applicabletoeachACMMember.
Theverbs"shall"(imperative)and"should"(encouragement)areused
purposefullyintheCode.TheCanonsandEthicalConsiderationsarenot,
however,bindingrules.EachDisciplinaryRuleisbindingoneachindividual
MemberofACM.FailuretoobservetheDisciplinaryRulessubjectstheMember
toadmonition,suspension,orexpulsionfromtheAssociationasprovidedbythe
ConstitutionandBylaws.Theterm"member(s)"isusedintheCode.The
DisciplinaryRulesoftheCodeapply,however,onlytotheclassesof
membershipspecifiedinArticle3,Section4,oftheConstitutionoftheACM.


CANON1
AnACMmembershallactatalltimeswithintegrity.
EthicalConsiderations
EC1.1.AnACMmembershallproperlyqualifyhimselfwhenexpressingan
opinionoutsidehisareasofcompetence.Amemberisencouragedtoexpresshis
opiniononsubjectswithinhisareasofcompetence.
EC1.2.AnACMmembershallprefaceanpartisanstatementsaboutinformation
processingbyindicatingclearlyonwhosebehalftheyaremade.
EC1.3.AnACMmembershallactfaithfullyonbehalfofhisemployersor
clients.
DisciplinaryRules
DR1.1.1.AnACMmembershallnotintentionallymisrepresenthis
qualificationsorcredentialstopresentorprospectiveemployersorclients.
DR1.1.2.AnACMmembershallnotmakedeliberatelyfalseordeceptive
statementsastothepresentorexpectedstateofaffairsinanyaspectofthe
capability,delivery,oruseofinformationprocessingsystems.
DR1.2.1.AnACMmembershallnotintentionallyconcealormisrepresenton
whosebehalfanypartisanstatementsaremade.
DR1.3.1.AnACMmemberactingoremployedasaconsultantshall,priorto
acceptinginformationfromaprospectiveclient,informtheclientofallfactors
ofwhichthememberisawarewhichmayaffecttheproperperformanceofthe
task.
DR1.3.2.AnACMmembershalldiscloseanyinterestofwhichheisaware
whichdoesormayconflictwithhisdutytoapresentorprospectiveemployeror
client.
DR1.3.3.AnACMmembershallnotuseanyconfidentialinformationfromany
employerorclient,pastorpresent,withoutpriorpermission.


CANON2
AnACMmembershouldstrivetoincreasehiscompetenceandthecompetence
andprestigeoftheprofession.
EthicalConsiderations
EC2.1.AnACMmemberisencouragedtoextendpublicknowledge,
understanding,andappreciationofinformationprocessing,andtoopposeany
falseordeceptivestatementsrelatingtoinformationprocessingofwhichheis
aware.
EC2.2AnACMmembershallnotusehisprofessionalcredentialsto
misrepresenthiscompetence.
EC2.3.AnACMmembershallundertakeonlythoseprofessionalassignments
andcommitmentsforwhichheisqualified.
EC2.4.AnACMmembershallstrivetodesignanddevelopsystemsthat
adequatelyperformtheintendedfunctionsandthatsatisfyhisemployer'sor
client'soperationalneeds.
EC2.5.AnACMmembershouldmaintainandincreasehiscompetencethrough
aprogramofcontinuingeducationencompassingthetechniques,technical
standards,andpracticesinhisfieldsofprofessionalactivity.
EC2.6.AnACMmembershouldprovideopportunityandencouragementfor
professionaldevelopmentandadvancementofbothprofessionalsandthose
aspiringtobecomeprofessionals.
DisciplinaryRules
DR2.2.1.AnACMmembershallnotusehisprofessionalcredentialsto
misrepresenthiscompetence.
DR2.3.1.AnACMmembershallnotundertakeprofessionalassignments
withoutadequatepreparationinthecircumstances.
DR2.3.2.AnACMmembershallnotundertakeprofessionalassignmentsfor


whichheknowsorshouldknowheisnotcompetentorcannotbecome
adequatelycompetentwithoutacquiringtheassistanceofaprofessionalwhois
competenttoperformtheassignment.
DR2.4.1.AnACMmembershallnotrepresentthataproductofhisworkwill
performitsfunctionadequatelyandwillmeetthereceiver'soperationalneeds
whenheknowsorshouldknowthattheproductisdeficient.


CANON3
AnACMmembershallacceptresponsibilityforhiswork.
EthicalConsiderations
EC3.1.AnACMmembershallacceptonlythoseassignmentsforwhichthereis
reasonableexpectancyofmeetingrequirementsorspecifications,andshall
performhisassignmentsinaprofessionalmanner.
DisciplinaryRules
DR3.1.1.AnACMmembershallnotneglectanyprofessionalassignmentwhich
hasbeenaccepted.
DR3.1.2.AnACMmembershallkeephisemployerorclientproperlyinformed
ontheprogressofhisassignments.
DR3.1.3.AnACMmembershallnotattempttoexoneratehimselffrom,orto
limit,hisliabilitytohisclientsforhispersonalmalpractice.
DR3.1.4.AnACMmembershallindicatetohisemployerorclientthe
consequencestobeexpectedifhisprofessionaljudgementisoverruled.


CANON4
AnACMmembershallactwithprofessionalresponsibility.
EthicalConsiderations
EC4.1AnACMmembershallnotusehismembershipinACMimproperlyfor
professionaladvantageortomisrepresenttheauthorityofhisstatements.
EC4.2.AnACMmembershallconductprofessionalactivitiesonahighplane.
EC4.3.AnACMmemberisencouragedtoupholdandimprovetheprofessional
standardsoftheAssociationthroughparticipationintheirformulation,
establishment,andenforcement.
DisciplinaryRules
DR4.1.1.AnACMmembershallnotspeakonbehalfoftheAssociationorany
ofitssubgroupswithoutproperauthority.
DR4.1.2.AnACMmembershallnotknowinglymisrepresentthepoliciesand
viewsoftheAssociationoranyofitssubgroups.
DR4.1.3.AnACMmembershallprefacepartisanstatementsaboutinformation
processingbyindicatingclearlyonwhosebehalftheyaremade.
DR4.2.1.AnACMmembershallnotmaliciouslyinjuretheprofessional
reputationofanyotherperson.
DR4.2.2.AnACMmembershallnotusetheservicesoforhismembershipin
theAssociationtogainunfairadvantage.
DR4.2.3.AnACMmembershalltakecarethatcreditforworkisgiventowhom
creditisproperlydue.


CANON5
AnACMmembershouldusehisspecialknowledgeandskillsforthe
advancementofhumanwelfare.
EthicalConsiderations
EC5.1.AnACMmembershouldconsiderthehealth,privacy,andgeneral
welfareofthepublicintheperformanceofhiswork.
EC5.2.AnACMmember,wheneverdealingwithdataconcerningindividuals,
shallalwaysconsidertheprincipleoftheindividual'sprivacyandseekthe
following:
--Tominimizethedatacollected.
--Tolimitauthorizedaccesstothedata.
--Toprovidepropersecurityforthedata.
--Todeterminetherequiredretentionperiodofthedata.
--Toensureproperdisposalofthedata.
Disciplinaryrules
DR5.2.1.AnACMmembershallexpresshisprofessionalopiniontohis
employersorclientsregardinganyadverseconsequencestothepublicwhich
mightresultfromworkproposedtohim.
GotoAppendixCBacktoTableofContents



APPENDIXC:ALGORITHM
INDEXBYCHAPTER
CHAPTER1--INTRODUCTION
Exchangesorting--SORT1.3
Binarysearch--BINSRCH1.3
FIBONACCI1.4
Fillingamagicsquare--MAGIC1.4
CHAPTER2--ARRAYS
Polynomialaddition--PADD2.2
Fibonaccipolynomials--MAIN2.2
Sparsematrixtranspose--TRANSPOSE2.3
Sparsematrixtranspose--FAST-TRANSPOSE2.3
Sparsematrixmultiplication--MMULT2.3
CHAPTER3--STACKSANDQUEUES
Sequentialstacks--ADD,DELETE3.1
Sequentialqueues--ADDQ,DELETEQ3.1
Circularsequentialqueues--ADDQ,DELETEQ3.1
Paththroughamaze--PATH3.2
Evaluationofapostfixexpression--EVAL3.3


Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay

×