The Go Programming Language

Total Page:16

File Type:pdf, Size:1020Kb

The Go Programming Language ptg16091132 www.it-ebooks.info The Go Programming Language ptg16091132 www.it-ebooks.info This page intentionally left blank ptg16091132 www.it-ebooks.info The Go Programming Language Alan A. A. Donovan Google Inc. Brian W. Kernighan ptg16091132 Princeton University New York • Boston • Indianapolis • San Francisco Toronto • Montreal • London • Munich • Paris • Madrid Capetown • Sydney • Tokyo • Singapore • Mexico City www.it-ebooks.info Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and the publisher was aware of a trade- mark claim, the designations have been printed with initial capital letters or in all capitals. T e authors and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein. For information about buying this title in bulk quantities, or for special sales opportunities (which may include electronic versions; custom cover designs; and content particular to your business, train- ing goals, marketing focus, or branding interests), please contact our corporate sales department at [email protected] or (800) 382-3419. For government sales inquiries, please contact [email protected]. For questions about sales outside the United States, please contact [email protected]. ptg16091132 Visit us on the Web: informit.com/aw Library of Congress Control Number: 2015950709 Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan All rights reserved. Printed in the United States of America. T is publication is protected by copyright, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. To obtain permission to use material from this work, please submit a written request to Pearson Education, Inc., Permissions Department, 200 Old Tappan Road, Old Tappan, New Jersey 07675, or you may fax your request to (201) 236-3290. Front cover: Millau Viaduct, Tarn valley, southern France. A paragon of simplicity in modern engi- neering design, the viaduct replaced a convoluted path from capital to coast with a direct route over the clouds. © Jean-Pierre Lescourret/Corbis. Back cover: the original Go gopher. © 2009 Renée French. Used under Creative Commons Attribu- tions 3.0 license. Typeset by the authors in Minion Pro, Lato, and Consolas, using Go, grof , ghostscript, and a host of other open-source Unix tools. Figures were created in Google Drawings. ISBN-13: 978-0-13-419044-0 ISBN-10: 0-13-419044-0 Text printed in the United States on recycled paper at RR Donnelley in Crawfordsville, Indiana. First printing, October 2015 www.it-ebooks.info The Go Programming Language © 2016 Alan A. A. Donovan & Brian W. Kernighan revision 3b600c, date 29 Sep 2015 Fo r Leil a an d Me g ptg16091132 www.it-ebooks.info This page intentionally left blank ptg16091132 www.it-ebooks.info The Go Programming Language © 2016 Alan A. A. Donovan & Brian W. Kernighan revision 3b600c, date 29 Sep 2015 Cont ents Pr eface xi TheOrigins ofGoxii TheGoPro jec t xiii Organizat ionofthe Bookxv ptg16091132 Wh ere toFindMoreInfor mat ionxvi Ac knowledgments xvii 1. Tutorial1 1.1. Hel lo, Wor ld1 1.2. Command-L ineArguments 4 1.3. FindingDup lic ateLines 8 1.4. Animated GIFs 13 1.5. FetchingaURL 15 1.6. FetchingURLs Con cur rently17 1.7. A We b Server 19 1.8. Loose End s 23 2. Pro gramStr ucture27 2.1. Names 27 2.2. Declarat ions 28 2.3. Var iables 30 2.4. Assig nments 36 2.5. Typ e Decl arat ions 39 2.6. Packages andFiles 41 2.7. Scope 45 vii www.it-ebooks.info The Go Programming Language © 2016 Alan A. A. Donovan & Brian W. Kernighan revision 3b600c, date 29 Sep 2015 viii CONTENTS 3. Basic Data Typ es51 3.1. Int egers 51 3.2. Float ing-Point Numbers 56 3.3. Complex Numbers 61 3.4. Boole ans63 3.5. Str ings64 3.6. Con stants75 4. Com positeTyp es81 4.1. Arrays 81 4.2. Slices 84 4.3. Maps 93 4.4. Str ucts99 4.5. JSON107 4.6. Text andHTMLTempl ates113 5. Func tions 119 5.1. FunctionDeclarat ions 119 5.2. Rec ursion121 5.3. MultipleRetur n Values 124 5.4. Erro rs127 5.5. FunctionValues 132 ptg16091132 5.6. Anony mou s Func tions 135 5.7. Var iadic Functions 142 5.8. Defer red FunctionCal ls143 5.9. Panic 148 5.10. Recov er151 6. Metho ds 155 6.1. Met hod Declarat ions 155 6.2. Met hodswit h aPoint erReceiver158 6.3. ComposingTyp es by Str uct Emb edding161 6.4. Met hod Values andExpressions 164 6.5. Example: Bit Vec tor Typ e 165 6.6. Encapsulat ion168 7. Interfaces171 7.1. Int erfaces as Contrac ts 171 7.2. Int erface Typ es 174 7.3. Int erface Satisfac tion175 7.4. ParsingFlags wit h flag.Value 179 7.5. Int erface Values 181 www.it-ebooks.info The Go Programming Language © 2016 Alan A. A. Donovan & Brian W. Kernighan revision 3b600c, date 29 Sep 2015 CONTENTSix 7.6. Sor tingwit h sort.Interface 186 7.7. The http.Handler Interface 191 7.8. The error Interface 196 7.9. Example: ExpressionEvaluator197 7.10. Typ e As ser tions 205 7.11. Discriminat ingError s with Typ e As ser tions 206 7.12. Quer yingBeh avior s with Int erface Typ e As ser tions 208 7.13. Typ e Sw itch es210 7.14. Example: Token-B ased XML Decoding213 7.15. A Fe w Wo rds ofAdv ice 216 8. Gor o utines and Channels 217 8.1. Goroutines217 8.2. Example: Con cur rentClo ckSer ver 219 8.3. Example: Con cur rentEch o Server 222 8.4. Channel s 225 8.5. Looping inParal lel234 8.6. Example: Con cur rentWeb Craw ler 239 8.7. Multiplexingwit h select 244 8.8. Example: Con cur rentDirec tor y Traversal247 8.9. Cancellat ion251 8.10. Example: ChatSer ver 253 ptg16091132 9. Concurrency withShared Vari ables257 9.1. Race Con dit ion s 257 9.2. Mut ual Exc lusion: sync.Mutex 262 9.3. Read/Write Mut exes: sync.RWMutex 266 9.4. Memor y Sy nchro nizat ion267 9.5. Lazy Initializat ion: sync.Once 268 9.6. TheRace Detec tor 271 9.7. Example: Con cur rentNon-Blo cking Cache 272 9.8. Goroutinesand Threads 280 10. Pack ages and the GoTool283 10.1. Int roduc tion283 10.2. Imp ort Pat hs284 10.3. ThePackageDeclarat ion285 10.4. Imp ort Declarat ions 285 10.5. Blank Imp orts286 10.6. Packages andNaming289 10.7. TheGoTool290 www.it-ebooks.info The Go Programming Language © 2016 Alan A. A. Donovan & Brian W. Kernighan revision 3b600c, date 29 Sep 2015 xCONTENTS 11. Testing 301 11.1. The go test To ol302 11.2. Test Func tions 302 11.3. Cov erage318 11.4. Benchmark Func tions 321 11.5. Profiling323 11.6. Example Func tions 326 12. Reflecti on329 12.1. Why Reflec tion?329 12.2. reflect.Type and reflect.Value 330 12.3. Display,aRec ursiveValue Print er333 12.4. Example: Enco dingS-E xpressions 338 12.5. Setting Var iables wit h reflect.Value 341 12.6. Example: DecodingS-E xpressions 344 12.7. AccessingStr uct Field Tags 348 12.8. Displaying the Met hodsofaTyp e 351 12.9. A Wo rdofCaution 352 13. Low-L evel Pro gramming353 13.1. unsafe.Sizeof, Alignof,and Offsetof 354 13.2. unsafe.Pointer 356 ptg16091132 13.3. Example: DeepEquivalence 358 13.4. Cal lingCCodewit h cgo 361 13.5. Another WordofCaution 366 Index367 www.it-ebooks.info The Go Programming Language © 2016 Alan A. A. Donovan & Brian W. Kernighan revision 3b600c, date 29 Sep 2015 Pref ace ‘‘Go is anopensourc e prog rammi n g lang uagethatmak esiteasytobui ldsimpl e,rel iab le, an d efficientsof tware.’’ (Fro m theGoweb sit e at golang.org) Go was conceive d in Septemb er2007 byRob ert Gries emer,Rob Pike, and Ken Thomps on, all ptg16091132 at Google, and was announced inNov emb er2009. Thegoals ofthe langu ageand its accom- pany ing tools weretobeexpressive, efficient in bot h comp ilation and exe cut ion,and effec tive in writing reliableand robustprograms. Go bears a sur face simi lar ity toC and,likeC,isatoolfor prof essionalprogrammers, achie v- ingmaximum effe ctwit h minimum means.But it ismuchmorethananupdated versionof C. Itbor rowsand adaptsgood ide as from manyother langu ages, whi leavoidingfeaturesthat have led tocomplexity and unreliablecode. Its facilities for con cur rency are new and efficient, andits approach to dat aabstrac tionand obj e ct-oriente d prog rammingisunu sually flexible. It hasaut omat ic memory managementor garb age col lec tion. Go isesp eci ally wel l suit edfor bui ldinginf rastr ucturelikenet wor ked ser vers, andtools and systems for prog rammers, but it istruly a general-pur pos e language and find s us e in domains as divers e as graphics, mobileapp lic ations,and machinelearning. Ithas becom e popu lar as a repl acementfor unt ypedscr ipt ing langu ages because itbal ances expressivenesswit h safety : Go programstypic ally run fasterthanprogramswritt enindynamic langu ages andsuf fer far fe wer crashesdue tounexp ected typ e er ror s. Go isanopen-s ource pro jec t,sosourcecodefor itscompi ler,librar ies,andtools is fre ely avai l- able toany one.Contr ibution s to the pro jec t come fro m an active worldw ide community.Go runs onUnix-li kesystems—Linux, Fre eBSD, OpenBSD, Mac OS X—andonPlan9and Micros oft Windows.
Recommended publications
  • B-Prolog User's Manual
    B-Prolog User's Manual (Version 8.1) Prolog, Agent, and Constraint Programming Neng-Fa Zhou Afany Software & CUNY & Kyutech Copyright c Afany Software, 1994-2014. Last updated February 23, 2014 Preface Welcome to B-Prolog, a versatile and efficient constraint logic programming (CLP) system. B-Prolog is being brought to you by Afany Software. The birth of CLP is a milestone in the history of programming languages. CLP combines two declarative programming paradigms: logic programming and constraint solving. The declarative nature has proven appealing in numerous ap- plications, including computer-aided design and verification, databases, software engineering, optimization, configuration, graphical user interfaces, and language processing. It greatly enhances the productivity of software development and soft- ware maintainability. In addition, because of the availability of efficient constraint- solving, memory management, and compilation techniques, CLP programs can be more efficient than their counterparts that are written in procedural languages. B-Prolog is a Prolog system with extensions for programming concurrency, constraints, and interactive graphics. The system is based on a significantly refined WAM [1], called TOAM Jr. [19] (a successor of TOAM [16]), which facilitates software emulation. In addition to a TOAM emulator with a garbage collector that is written in C, the system consists of a compiler and an interpreter that are written in Prolog, and a library of built-in predicates that are written in C and in Prolog. B-Prolog does not only accept standard-form Prolog programs, but also accepts matching clauses, in which the determinacy and input/output unifications are explicitly denoted. Matching clauses are compiled into more compact and faster code than standard-form clauses.
    [Show full text]
  • Cobol Vs Standards and Conventions
    Number: 11.10 COBOL VS STANDARDS AND CONVENTIONS July 2005 Number: 11.10 Effective: 07/01/05 TABLE OF CONTENTS 1 INTRODUCTION .................................................................................................................................................. 1 1.1 PURPOSE .................................................................................................................................................. 1 1.2 SCOPE ...................................................................................................................................................... 1 1.3 APPLICABILITY ........................................................................................................................................... 2 1.4 MAINFRAME COMPUTER PROCESSING ....................................................................................................... 2 1.5 MAINFRAME PRODUCTION JOB MANAGEMENT ............................................................................................ 2 1.6 COMMENTS AND SUGGESTIONS ................................................................................................................. 3 2 COBOL DESIGN STANDARDS .......................................................................................................................... 3 2.1 IDENTIFICATION DIVISION .................................................................................................................. 4 2.1.1 PROGRAM-ID ..........................................................................................................................
    [Show full text]
  • A Quick Reference to C Programming Language
    A Quick Reference to C Programming Language Structure of a C Program #include(stdio.h) /* include IO library */ #include... /* include other files */ #define.. /* define constants */ /* Declare global variables*/) (variable type)(variable list); /* Define program functions */ (type returned)(function name)(parameter list) (declaration of parameter types) { (declaration of local variables); (body of function code); } /* Define main function*/ main ((optional argc and argv arguments)) (optional declaration parameters) { (declaration of local variables); (body of main function code); } Comments Format: /*(body of comment) */ Example: /*This is a comment in C*/ Constant Declarations Format: #define(constant name)(constant value) Example: #define MAXIMUM 1000 Type Definitions Format: typedef(datatype)(symbolic name); Example: typedef int KILOGRAMS; Variables Declarations: Format: (variable type)(name 1)(name 2),...; Example: int firstnum, secondnum; char alpha; int firstarray[10]; int doublearray[2][5]; char firststring[1O]; Initializing: Format: (variable type)(name)=(value); Example: int firstnum=5; Assignments: Format: (name)=(value); Example: firstnum=5; Alpha='a'; Unions Declarations: Format: union(tag) {(type)(member name); (type)(member name); ... }(variable name); Example: union demotagname {int a; float b; }demovarname; Assignment: Format: (tag).(member name)=(value); demovarname.a=1; demovarname.b=4.6; Structures Declarations: Format: struct(tag) {(type)(variable); (type)(variable); ... }(variable list); Example: struct student {int
    [Show full text]
  • A Tutorial Introduction to the Language B
    A TUTORIAL INTRODUCTION TO THE LANGUAGE B B. W. Kernighan Bell Laboratories Murray Hill, New Jersey 1. Introduction B is a new computer language designed and implemented at Murray Hill. It runs and is actively supported and documented on the H6070 TSS system at Murray Hill. B is particularly suited for non-numeric computations, typified by system programming. These usually involve many complex logical decisions, computations on integers and fields of words, especially charac- ters and bit strings, and no floating point. B programs for such operations are substantially easier to write and understand than GMAP programs. The generated code is quite good. Implementation of simple TSS subsystems is an especially good use for B. B is reminiscent of BCPL [2] , for those who can remember. The original design and implementation are the work of K. L. Thompson and D. M. Ritchie; their original 6070 version has been substantially improved by S. C. Johnson, who also wrote the runtime library. This memo is a tutorial to make learning B as painless as possible. Most of the features of the language are mentioned in passing, but only the most important are stressed. Users who would like the full story should consult A User’s Reference to B on MH-TSS, by S. C. Johnson [1], which should be read for details any- way. We will assume that the user is familiar with the mysteries of TSS, such as creating files, text editing, and the like, and has programmed in some language before. Throughout, the symbolism (->n) implies that a topic will be expanded upon in section n of this manual.
    [Show full text]
  • Quick Tips and Tricks: Perl Regular Expressions in SAS® Pratap S
    Paper 4005-2019 Quick Tips and Tricks: Perl Regular Expressions in SAS® Pratap S. Kunwar, Jinson Erinjeri, Emmes Corporation. ABSTRACT Programming with text strings or patterns in SAS® can be complicated without the knowledge of Perl regular expressions. Just knowing the basics of regular expressions (PRX functions) will sharpen anyone's programming skills. Having attended a few SAS conferences lately, we have noticed that there are few presentations on this topic and many programmers tend to avoid learning and applying the regular expressions. Also, many of them are not aware of the capabilities of these functions in SAS. In this presentation, we present quick tips on these expressions with various applications which will enable anyone learn this topic with ease. INTRODUCTION SAS has numerous character (string) functions which are very useful in manipulating character fields. Every SAS programmer is generally familiar with basic character functions such as SUBSTR, SCAN, STRIP, INDEX, UPCASE, LOWCASE, CAT, ANY, NOT, COMPARE, COMPBL, COMPRESS, FIND, TRANSLATE, TRANWRD etc. Though these common functions are very handy for simple string manipulations, they are not built for complex pattern matching and search-and-replace operations. Regular expressions (RegEx) are both flexible and powerful and are widely used in popular programming languages such as Perl, Python, JavaScript, PHP, .NET and many more for pattern matching and translating character strings. Regular expressions skills can be easily ported to other languages like SQL., However, unlike SQL, RegEx itself is not a programming language, but simply defines a search pattern that describes text. Learning regular expressions starts with understanding of character classes and metacharacters.
    [Show full text]
  • The Programming Language Concurrent Pascal
    IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. SE-I, No.2, JUNE 1975 199 The Programming Language Concurrent Pascal PER BRINCH HANSEN Abstract-The paper describes a new programming language Disk buffer for structured programming of computer operating systems. It e.lt­ tends the sequential programming language Pascal with concurx:~t programming tools called processes and monitors. Section I eltplains these concepts informally by means of pictures illustrating a hier­ archical design of a simple spooling system. Section II uses the same enmple to introduce the language notation. The main contribu~on of Concurrent Pascal is to extend the monitor concept with an .ex­ Producer process Consumer process plicit hierarchy Of access' rights to shared data structures that can Fig. 1. Process communication. be stated in the program text and checked by a compiler. Index Terms-Abstract data types, access rights, classes, con­ current processes, concurrent programming languages, hierarchical operating systems, monitors, scheduling, structured multiprogram­ ming. Access rights Private data Sequential 1. THE PURPOSE OF CONCURRENT PASCAL program A. Background Fig. 2. Process. INCE 1972 I have been working on a new programming .. language for structured programming of computer S The next picture shows a process component in more operating systems. This language is called Concurrent detail (Fig. 2). Pascal. It extends the sequential programming language A process consists of a private data structure and a Pascal with concurrent programming tools called processes sequential program that can operate on the data. One and monitors [1J-[3]' process cannot operate on the private data of another This is an informal description of Concurrent Pascal.
    [Show full text]
  • Introduction to Shell Programming Using Bash Part I
    Introduction to shell programming using bash Part I Deniz Savas and Michael Griffiths 2005-2011 Corporate Information and Computing Services The University of Sheffield Email [email protected] [email protected] Presentation Outline • Introduction • Why use shell programs • Basics of shell programming • Using variables and parameters • User Input during shell script execution • Arithmetical operations on shell variables • Aliases • Debugging shell scripts • References Introduction • What is ‘shell’ ? • Why write shell programs? • Types of shell What is ‘shell’ ? • Provides an Interface to the UNIX Operating System • It is a command interpreter – Built on top of the kernel – Enables users to run services provided by the UNIX OS • In its simplest form a series of commands in a file is a shell program that saves having to retype commands to perform common tasks. • Shell provides a secure interface between the user and the ‘kernel’ of the operating system. Why write shell programs? • Run tasks customised for different systems. Variety of environment variables such as the operating system version and type can be detected within a script and necessary action taken to enable correct operation of a program. • Create the primary user interface for a variety of programming tasks. For example- to start up a package with a selection of options. • Write programs for controlling the routinely performed jobs run on a system. For example- to take backups when the system is idle. • Write job scripts for submission to a job-scheduler such as the sun- grid-engine. For example- to run your own programs in batch mode. Types of Unix shells • sh Bourne Shell (Original Shell) (Steven Bourne of AT&T) • csh C-Shell (C-like Syntax)(Bill Joy of Univ.
    [Show full text]
  • An Analysis of the D Programming Language Sumanth Yenduri University of Mississippi- Long Beach
    View metadata, citation and similar papers at core.ac.uk brought to you by CORE provided by CSUSB ScholarWorks Journal of International Technology and Information Management Volume 16 | Issue 3 Article 7 2007 An Analysis of the D Programming Language Sumanth Yenduri University of Mississippi- Long Beach Louise Perkins University of Southern Mississippi- Long Beach Md. Sarder University of Southern Mississippi- Long Beach Follow this and additional works at: http://scholarworks.lib.csusb.edu/jitim Part of the Business Intelligence Commons, E-Commerce Commons, Management Information Systems Commons, Management Sciences and Quantitative Methods Commons, Operational Research Commons, and the Technology and Innovation Commons Recommended Citation Yenduri, Sumanth; Perkins, Louise; and Sarder, Md. (2007) "An Analysis of the D Programming Language," Journal of International Technology and Information Management: Vol. 16: Iss. 3, Article 7. Available at: http://scholarworks.lib.csusb.edu/jitim/vol16/iss3/7 This Article is brought to you for free and open access by CSUSB ScholarWorks. It has been accepted for inclusion in Journal of International Technology and Information Management by an authorized administrator of CSUSB ScholarWorks. For more information, please contact [email protected]. Analysis of Programming Language D Journal of International Technology and Information Management An Analysis of the D Programming Language Sumanth Yenduri Louise Perkins Md. Sarder University of Southern Mississippi - Long Beach ABSTRACT The C language and its derivatives have been some of the dominant higher-level languages used, and the maturity has stemmed several newer languages that, while still relatively young, possess the strength of decades of trials and experimentation with programming concepts.
    [Show full text]
  • C Programming Tutorial
    C Programming Tutorial C PROGRAMMING TUTORIAL Simply Easy Learning by tutorialspoint.com tutorialspoint.com i COPYRIGHT & DISCLAIMER NOTICE All the content and graphics on this tutorial are the property of tutorialspoint.com. Any content from tutorialspoint.com or this tutorial may not be redistributed or reproduced in any way, shape, or form without the written permission of tutorialspoint.com. Failure to do so is a violation of copyright laws. This tutorial may contain inaccuracies or errors and tutorialspoint provides no guarantee regarding the accuracy of the site or its contents including this tutorial. If you discover that the tutorialspoint.com site or this tutorial content contains some errors, please contact us at [email protected] ii Table of Contents C Language Overview .............................................................. 1 Facts about C ............................................................................................... 1 Why to use C ? ............................................................................................. 2 C Programs .................................................................................................. 2 C Environment Setup ............................................................... 3 Text Editor ................................................................................................... 3 The C Compiler ............................................................................................ 3 Installation on Unix/Linux ............................................................................
    [Show full text]
  • Shell Script: the Shell Is the Part of the UNIX That Is Most Visible to the User. It Receives and Interprets the Commands Entered by the User
    Shell Script: The shell is the part of the UNIX that is most visible to the user. It receives and interprets the commands entered by the user. In many respects, this makes it the most important component of the UNIX structure. To do anything in the system, we should give the shell a command. If the command requires a utility, the shell requests that the kernel execute the utility. If the command requires an application program, the shell requests that it be run. The standard shells are of different types as There are two major parts to a shell. The first is the interpreter. The interpreter reads your commands and works with the kernel to execute them. The second part of the shell is a programming capability that allows you to write a shell (command) script. A shell script is a file that contains shell commands that perform a useful function. It is also known as shell program. Three additional shells are used in UNIX today. The Bourne shell, developed by Steve Bourne at the AT&T labs, is the oldest. Because it is the oldest and most primitive, it is not used on many systems today. An enhanced version of Bourne shell, called Bash (Bourne again shell), is used in Linux. The C shell, developed in Berkeley by Bill Joy, received its name from the fact that its commands were supposed to look like C statements. A compatible version of C shell, called tcsh is used in Linux. The Korn shell, developed by David Korn also of the AT&T labs, is the newest and most powerful.
    [Show full text]
  • Programming Languages and Translators
    Programming Languages and Translators Ronghui Gu Spring 2019 Columbia University 1 Instructor Prof. Ronghui Gu 515 Computer Science Building [email protected] Oce hours: Thursdays 1:30 - 2:30 PM / by appointment Prof. Stephen A. Edwards and Prof. Baishakhi Rey also teach 4115. ∗These slides are borrowed from Prof. Edwards. 2 What is a Programming Language? A programming language is a notation that a person and a computer can both understand. • It allows you to express what is the task to compute • It allows a computer to execute the computation task Every programming language has a syntax and semantics. • Syntax: how characters combine to form a program • Semantics: what the program means 3 Components of a language: Syntax How characters combine to form a program. Calculate the n-th Fibonacci number. is syntactically correct English, but isn’t a Java program. c l a s s Foo { p u b l i c int j; p u b l i c int foo(int k){ return j+k;} } is syntactically correct Java, but isn’t C. 4 Specifying Syntax Usually done with a context-free grammar. Typical syntax for algebraic expressions: expr ! expr + expr j expr − expr j expr ∗ expr j expr = expr j ( expr ) j digits 5 Components of a language: Semantics What a well-formed program “means.” The semantics of C says this computes the nth Fibonacci number. i n t fib(int n) { i n t a=0,b=1; i n t i; f o r (i=1 ; i<n ; i++){ i n t c=a+b; a = b ; b = c ; } return b; } 6 Semantics Something may be syntactically correct but semantically nonsensical The rock jumped through the hairy planet.
    [Show full text]
  • An Introduction to Prolog
    Appendix A An Introduction to Prolog A.1 A Short Background Prolog was designed in the 1970s by Alain Colmerauer and a team of researchers with the idea – new at that time – that it was possible to use logic to represent knowledge and to write programs. More precisely, Prolog uses a subset of predicate logic and draws its structure from theoretical works of earlier logicians such as Herbrand (1930) and Robinson (1965) on the automation of theorem proving. Prolog was originally intended for the writing of natural language processing applications. Because of its conciseness and simplicity, it became popular well beyond this domain and now has adepts in areas such as: • Formal logic and associated forms of programming • Reasoning modeling • Database programming • Planning, and so on. This chapter is a short review of Prolog. In-depth tutorials include: in English, Bratko (2012), Clocksin and Mellish (2003), Covington et al. (1997), and Sterling and Shapiro (1994); in French, Giannesini et al. (1985); and in German, Baumann (1991). Boizumault (1988, 1993) contain a didactical implementation of Prolog in Lisp. Prolog foundations rest on first-order logic. Apt (1997), Burke and Foxley (1996), Delahaye (1986), and Lloyd (1987) examine theoretical links between this part of logic and Prolog. Colmerauer started his work at the University of Montréal, and a first version of the language was implemented at the University of Marseilles in 1972. Colmerauer and Roussel (1996) tell the story of the birth of Prolog, including their try-and-fail experimentation to select tractable algorithms from the mass of results provided by research in logic.
    [Show full text]