ebook img

Programming in Prolog: Using the ISO Standard PDF

308 Pages·2003·4.509 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Programming in Prolog: Using the ISO Standard

Programming in Prolog Springer-Verlag Berlin Heidelberg GmbH W.F.Clocksin · C.S.Mellish Programming in Prolog Fifth Edition 123 Prof.William F.Clocksin OxfordBrookesUniversity Department ofComputing Wheatley Campus Oxford OX33 1HX,United Kingdom Dr.Christopher S.Mellish University ofEdinburgh Department ofArtificial Intelligence 80 South Bridge Edinburgh EH1 1HN,United Kingdom ISBN 978-3-540-00678-7 ISBN 978-3-642-55481-0 (eBook) DOI 10.1007/978-3-642-55481-0 Cataloging-in-Publication Data applied for Clocksin, W.F. (William F.), 1955- Programming in Prolog: using the ISO standard/W.F. Clocksin, C.S. Mellish.--5th ed. p.cm. Includes bibliographical references and index. ISBN 978-3-540-00678-7 (alk.paper) 1.Prolog (Computer program language) I.Mellish, C.S. (Christopher S.), 1954-II. Title. QA76.73.P76C57 2003 005.13´3--dc21 2003044177 This work issubject to copyright. All rights are reserved, whether thewhole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilm or in any other way, and storage in data banks. Duplication of this publication or parts thereof is permitted only under the provisions of the German Copyright Law of September 9, 1965, in its current version, and permission for use must always be obtained from Springer-Verlag. Violations are liable for prosecution under the German Copyright Law. http://www.springer.de © Springer-Verlag Berlin Heidelberg 2003 Originally published by Springer-Verlag Berlin Heidelberg New York in 2003 The use of general descriptive names, registered names, trademarks, etc. in this publication does not imply, even in the absence of a specific statement, that such names are exempt from the relevant protective laws and regulations and therefore free for general use. Printed on acid-free paper 41/3111XO – 5 4 3 2 1 Preface to the Fifth Edition SincethepreviouseditionofProgramminginProlog,theProloglanguagehas been standardised by the InternationalOrganizationfor Standardization(ISO). Al- thoughnotallPrologsystemsconformtothenewstandard,wefeltitwasnecessary totaketheopportunitytoupdatethisbookinaccordancewiththestandard.Wehave alsointroducedsomenewmaterial,clarifiedsomeexplanations,correctedanumber ofminorerrors,andremovedappendicesaboutPrologsystemsthatarenowobsolete. Thisbookcanserveseveralpurposes.Theaimofthisbookisnottoteachthe artofprogrammingassuch.Wefeelthatprogrammingcannotbelearnedsimplyby readingabookorbylisteningtoalecturer.You’vegottodoprogrammingtolearnit. We hopethatbeginnerswithouta mathematicalbackgroundcan learnPrologfrom thisbook,althoughinthiscasewewouldrecommendthatthebeginneristaughtby a programmerwhoknowsProlog,aspartofacoursethatintroducesthestudentto programmingassuch.Itisassumedthatbeginnerscanobtaintheuseofacomputer that has a Prologsystem installed, and thatthey have been instructed in the use of thecomputer.Experiencedprogrammersshouldnotrequireextraassistance,butwe hopetheywillnotbedismayedatourintentiontorestrainmathematicalelaboration. In our experience, novice programmersfind that Prolog programsseem to be morecomprehensiblethanequivalentprogramsinconventionallanguages.However, the same people tend not to appreciate the limitations that conventionallanguages placeontheiruseofcomputingresources.Ontheotherhand,programmersexperi- enced in conventionallanguagesare better preparedto deal with abstract concepts such as variables and controlflow. But, in spite of this prior experience,they may findPrologdifficultto adaptto,andtheymayneeda lotofconvincingbeforethey considerPrologausefulprogrammingtool.Ofcourse,weknowofmanyhighlyex- periencedprogrammerswhohavetakenupPrologwithmuchenthusiasm.However, theaimofthisbookisnottoconvert,buttoteach. Programming in Prolog can be a useful companion to two other books. The beginner might use Programming in Prolog as a tutorial preliminary to the more VI PrefacetotheFifthEdition concise and advanced text Clause and Effect. The more experienced programmer mightstartwithClauseandEffectandbewritingusefulprogramswithinafewhours, returningtoProgramminginPrologtofillinanygapsinunderstanding.Clauseand Effect also conforms to ISO Standard Prolog, and it may be beneficial to use the reference manual Prolog: The Standard in conjunction with this book. Details of thesebooksare: ClauseandEffect,byW.F.Clocksin. Springer-Verlag,1997.ISBN3-540-62971-8. Prolog:TheStandard,byP.Deransart,A.Ed-Dbali,andL.Cervoni. Springer-Verlag,1996.ISBN3-540-59304-7. ProvidedthatthereaderisequippedwithaPrologimplementationthatconformsto the ISO standard, the book Prolog: The Standard almost obviates the need for an implementation-specific reference manual, although the latter would be useful for documentingimplementation-definedparametersandlimits. Like most other programminglanguages, Prolog exists in a numberof differ- entimplementations,eachwithitsownsemanticandsyntacticpeculiarities.Inthis book we have adopted a core Prolog based on ISO Standard Prolog. Previousedi- tionsconformedtoadefactostandardthatbecameknownasEdinburghProlog.In turn,EdinburghPrologwasthemaininfluenceonthespecificationofISOStandard Prolog.Thetable shownbelowsummarisesthemainchangesthathavebeenmade in the use of particularsyntactic forms, special atomsand built-in predicatessince earlierversionsofthisbookinordertoconformtotheStandardorotherwisereflect morerecentpractice.Mostofthe differencesbetweenthe EdinburghandISO core versions are of a purely cosmetic nature, though ISO Standard Prolog has gone in newdirectionsinthewaythatinput/outputishandled. Thisbookwasdesignedtobereadsequentially,althoughitwillprovehelpful toreadChap.8whenthereaderbeginstowritePrologprogramsconsistingofmore thanabouttenclauses.Itshouldn’thurttobrowsethroughthebook,butdotakecare nottoskipovertheearlierchapters. Each chapter is divided into several sections, and we advise the reader to at- tempt the exercises that are at the end of many sections. The solutions to some of theexercisesappearattheendofthebook.Chapter1isatutorialintroductionthat is intendedtogivethe readera feelforwhatis requiredto programin Prolog.The fundamentalideasofPrologareintroduced,andthereaderisadvisedtostudythem carefully. Chapter 2 presents a more complete discussion of points that are intro- duced in Chapter 1. Chapter 3 deals with data structures and derives some small exampleprograms.Chapter4treatsthesubjectofbacktrackingin moredetail,and introducesthe cut symbol, which is used to controlbacktracking.Chapter 5 intro- PrefacetotheFifthEdition VII EdinburghEditions ISOEdition "..."(string)notation Notused(canmeandifferentthings) ASCIIcodesforcharacters Singleelementatomsascharacters get,get0,put get_char,put_char see,seeing,seen open,set_input,current_input tell,telling,told open,set_output,current_output user user_inputanduser_output integer number(floating-pointnumbersarehandled) reconsult consult(thoughnotintheStandard) not \+ tab,skip notused display write_canonical assert asserta,assertz /arithmeticoperator /and//operators name atom_chars,number_chars @<,@=<etc.introduced =:=and=\=introduced Table of differences between previous editions, which used theEdinburgh Prolog standard, andthepresentedition,whichusestheISOstandard. ducesthefacilitiesthatareavailableforinputandoutput.Chapter6describeseach built-inpredicateinthestandardcoreofProlog.Chapter7isapotpourriofexample programs collected from many sources, together with an explanation of how they are written. Chapter 8 offerssome advice on debuggingProlog programs.Chapter 9introducestheGrammarRulesyntax,andexaminesthedesigndecisionsforsome aspectsofanalysingnaturallanguagebyusingGrammarRules.Chapter10describes therelationofPrologtoitsoriginsinmathematicaltheoremprovingandlogicpro- gramming. Chapter 11 specifies a number of projects on which interested readers maywishtopractisetheirprogrammingability. During the past twenty years that previouseditions of this book have been in use, individuals too numerous to list by name have given us help, support, encourage- ment, suggestions, and comments about this book. We are grateful to our readers, students,teachers,colleagues,correspondents,editors,friendsandfamilywhohave contributedinvariousandmanifoldways.Ofcourse,responsibilityfortheerrorsand omissionsthatremaininthiseditionrestsentirelywithus. OxfordandEdinburgh WilliamClocksin June2003 ChrisMellish Table of Contents 1 TutorialIntroduction........................................... 1 GivesthestudentafeelforwhatitisliketoprograminProlog. Introducesobjects,relationships,facts,rules,variables 1.1 Prolog.................................................... 1 1.2 ObjectsandRelationships ................................... 2 1.3 Programming.............................................. 3 1.4 Facts ..................................................... 4 1.5 Questions ................................................. 6 1.6 Variables.................................................. 8 1.7 Conjunctions .............................................. 10 1.8 Rules..................................................... 16 1.9 SummaryandExercises ..................................... 22 2 ACloserLook ................................................. 25 MoredetailedpresentationofPrologsyntaxanddatastructures 2.1 Syntax.................................................... 25 2.1.1 Constants........................................... 26 2.1.2 Variables ........................................... 27 2.1.3 Structures .......................................... 27 2.2 Characters ................................................ 29 2.3 Operators ................................................. 30 2.4 EqualityandUnification..................................... 32 2.5 Arithmetic ................................................ 34 2.6 SummaryofSatisfyingGoals ................................ 37 2.6.1 Successfulsatisfactionofaconjunctionofgoals .......... 38 X TableofContents 2.6.2 Considerationofgoalsinbacktracking .................. 42 2.6.3 Unification.......................................... 43 3 UsingDataStructures .......................................... 47 Representingobjectsandrelationshipsbyusingtreesandlists. DevelopingseveralstandardPrologprogrammingtechniques 3.1 StructuresandTrees ........................................ 47 3.2 Lists ..................................................... 50 3.3 RecursiveSearch........................................... 53 3.4 Mapping.................................................. 57 3.5 RecursiveComparison ...................................... 60 3.6 JoiningStructuresTogether .................................. 63 3.7 Accumulators.............................................. 67 3.8 DifferenceStructures ....................................... 70 4 Backtrackingandthe“Cut”..................................... 73 Howasetofclausesgeneratesasetofsolutions.Using“cut”tomodify thecontrolsequenceofrunningPrologprograms 4.1 GeneratingMultipleSolutions................................ 74 4.2 The“Cut”................................................. 80 4.3 CommonUsesoftheCut .................................... 85 4.3.1 ConfirmingtheChoiceofaRule ....................... 85 4.3.2 The“cut-fail”Combination............................ 90 4.3.3 Terminatinga“generateandtest”....................... 92 4.4 ProblemswiththeCut ...................................... 96 5 InputandOutput .............................................. 99 Facilitiesavailablefortheinputandoutputofcharactersandstructures. Developingaprogramtoreadsentencesfromtheuserandrepresent thestructureasalistofwords,whichcanbeusedwiththeGrammarRules ofChapter9 5.1 ReadingandWritingTerms .................................. 100 5.1.1 ReadingTerms ...................................... 100 5.1.2 WritingTerms....................................... 101 5.2 ReadingandWritingCharacters .............................. 104 5.2.1 ReadingCharacters .................................. 105 5.2.2 WritingCharacters................................... 106

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.