Concepts, Techniques, and Models
of Computer Programming
PETER VAN ROY
1
Universit´e catholique de Louvain (at Louvain-la-Neuve)
Swedish Institute of Computer Science
SEIF HARIDI
2
Royal Institute of Technology (KTH)
Swedish Institute of Computer Science
June 5, 2003
1
Email: ,Web: />2
Email: ,Web: />ii
Copyright
c
2001-3 by P. Van Roy and S. Haridi. All rights reserved.
Contents
List of Figures xvi
List of Tables xxiv
Preface xxvii
Running the example programs xliii
I Introduction 1
1 Introduction to Programming Concepts 3
1.1 Acalculator 3
1.2 Variables 4
1.3 Functions 4
1.4 Lists 6
1.5 Functionsoverlists 9
1.6 Correctness 11
1.7 Complexity 12
1.8 Lazyevaluation 13
1.9 Higher-orderprogramming 15
1.10Concurrency 16
1.11Dataflow 17
1.12State 18
1.13Objects 19
1.14Classes 20
1.15Nondeterminismandtime 21
1.16Atomicity 23
1.17Wheredowegofromhere 24
1.18Exercises 24
II General Computation Models 29
2 Declarative Computation Model 31
Copyright
c
2001-3 by P. Van Roy and S. Haridi. All rights reserved.
iv CONTENTS
2.1 Definingpracticalprogramminglanguages 33
2.1.1 Languagesyntax 33
2.1.2 Languagesemantics 38
2.2 Thesingle-assignmentstore 44
2.2.1 Declarativevariables 44
2.2.2 Valuestore 44
2.2.3 Valuecreation 45
2.2.4 Variableidentifiers 46
2.2.5 Valuecreationwithidentifiers 47
2.2.6 Partialvalues 47
2.2.7 Variable-variablebinding 48
2.2.8 Dataflowvariables 49
2.3 Kernellanguage 50
2.3.1 Syntax 50
2.3.2 Valuesandtypes 51
2.3.3 Basictypes 53
2.3.4 Recordsandprocedures 54
2.3.5 Basicoperations 56
2.4 Kernellanguagesemantics 57
2.4.1 Basicconcepts 57
2.4.2 Theabstractmachine 61
2.4.3 Non-suspendablestatements 64
2.4.4 Suspendablestatements 67
2.4.5 Basicconceptsrevisited 69
2.4.6 Lastcalloptimization 74
2.4.7 Activememoryandmemorymanagement 75
2.5 Fromkernellanguagetopracticallanguage 80
2.5.1 Syntacticconveniences 80
2.5.2 Functions (the
fun statement) 85
2.5.3 Interactive interface (the
declare statement) 88
2.6 Exceptions 91
2.6.1 Motivationandbasicconcepts 91
2.6.2 Thedeclarativemodelwithexceptions 93
2.6.3 Fullsyntax 95
2.6.4 Systemexceptions 97
2.7 Advancedtopics 98
2.7.1 Functionalprogramminglanguages 98
2.7.2 Unificationandentailment 100
2.7.3 Dynamicandstatictyping 106
2.8 Exercises 108
Copyright
c
2001-3 by P. Van Roy and S. Haridi. All rights reserved.
CONTENTS v
3 Declarative Programming Techniques 113
3.1 Whatisdeclarativeness? 117
3.1.1 Aclassificationofdeclarativeprogramming 117
3.1.2 Specificationlanguages 119
3.1.3 Implementing components in the declarative model . . . . 119
3.2 Iterativecomputation 120
3.2.1 Ageneralschema 120
3.2.2 Iterationwithnumbers 122
3.2.3 Usinglocalprocedures 122
3.2.4 Fromgeneralschematocontrolabstraction 125
3.3 Recursivecomputation 126
3.3.1 Growingstacksize 127
3.3.2 Substitution-based abstract machine 128
3.3.3 Converting a recursive to an iterative computation . . . . 129
3.4 Programmingwithrecursion 130
3.4.1 Typenotation 131
3.4.2 Programmingwithlists 132
3.4.3 Accumulators 142
3.4.4 Differencelists 144
3.4.5 Queues 149
3.4.6 Trees 153
3.4.7 Drawingtrees 161
3.4.8 Parsing 163
3.5 Timeandspaceefficiency 169
3.5.1 Executiontime 169
3.5.2 Memoryusage 175
3.5.3 Amortizedcomplexity 177
3.5.4 Reflectionsonperformance 178
3.6 Higher-orderprogramming 180
3.6.1 Basicoperations 180
3.6.2 Loopabstractions 186
3.6.3 Linguisticsupportforloops 190
3.6.4 Data-driventechniques 193
3.6.5 Explicitlazyevaluation 196
3.6.6 Currying 196
3.7 Abstractdatatypes 197
3.7.1 Adeclarativestack 198
3.7.2 Adeclarativedictionary 199
3.7.3 Awordfrequencyapplication 201
3.7.4 Secureabstractdatatypes 204
3.7.5 Thedeclarativemodelwithsecuretypes 205
3.7.6 Asecuredeclarativedictionary 210
3.7.7 Capabilities and security 210
3.8 Nondeclarativeneeds 213
Copyright
c
2001-3 by P. Van Roy and S. Haridi. All rights reserved.
vi CONTENTS
3.8.1 Text input/output with a file 213
3.8.2 Text input/output with a graphical user interface 216
3.8.3 StatelessdataI/Owithfiles 219
3.9 Programdesigninthesmall 221
3.9.1 Designmethodology 221
3.9.2 Exampleofprogramdesign 222
3.9.3 Softwarecomponents 223
3.9.4 Exampleofastandaloneprogram 228
3.10Exercises 233
4 Declarative Concurrency 237
4.1 Thedata-drivenconcurrentmodel 239
4.1.1 Basicconcepts 241
4.1.2 Semanticsofthreads 243
4.1.3 Exampleexecution 246
4.1.4 Whatisdeclarativeconcurrency? 247
4.2 Basicthreadprogrammingtechniques 251
4.2.1 Creatingthreads 251
4.2.2 Threadsandthebrowser 251
4.2.3 Dataflowcomputationwiththreads 252
4.2.4 Threadscheduling 256
4.2.5 Cooperativeandcompetitiveconcurrency 259
4.2.6 Threadoperations 260
4.3 Streams 261
4.3.1 Basicproducer/consumer 261
4.3.2 Transducersandpipelines 263
4.3.3 Managing resources and improving throughput 265
4.3.4 Streamobjects 270
4.3.5 Digitallogicsimulation 271
4.4 Usingthedeclarativeconcurrentmodeldirectly 277
4.4.1 Order-determiningconcurrency 277
4.4.2 Coroutines 279
4.4.3 Concurrentcomposition 281
4.5 Lazyexecution 283
4.5.1 Thedemand-drivenconcurrentmodel 286
4.5.2 Declarativecomputationmodels 290
4.5.3 Lazystreams 293
4.5.4 Bounded buffer 295
4.5.5 Readingafilelazily 297
4.5.6 TheHammingproblem 298
4.5.7 Lazylistoperations 299
4.5.8 Persistentqueuesandalgorithmdesign 303
4.5.9 Listcomprehensions 307
4.6 Softreal-timeprogramming 309
Copyright
c
2001-3 by P. Van Roy and S. Haridi. All rights reserved.
CONTENTS vii
4.6.1 Basicoperations 309
4.6.2 Ticking 311
4.7 Limitationsandextensionsofdeclarativeprogramming 314
4.7.1 Efficiency 314
4.7.2 Modularity 315
4.7.3 Nondeterminism 319
4.7.4 Therealworld 322
4.7.5 Pickingtherightmodel 323
4.7.6 Extendedmodels 323
4.7.7 Usingdifferentmodelstogether 325
4.8 TheHaskelllanguage 327
4.8.1 Computationmodel 328
4.8.2 Lazyevaluation 328
4.8.3 Currying 329
4.8.4 Polymorphictypes 330
4.8.5 Typeclasses 331
4.9 Advancedtopics 332
4.9.1 The declarative concurrent model with exceptions . . . . . 332
4.9.2 Moreonlazyexecution 334
4.9.3 Dataflowvariablesascommunicationchannels 337
4.9.4 Moreonsynchronization 339
4.9.5 Usefulnessofdataflowvariables 340
4.10Historicalnotes 343
4.11Exercises 344
5 Message-Passing Concurrency 353
5.1 Themessage-passingconcurrentmodel 354
5.1.1 Ports 354
5.1.2 Semanticsofports 355
5.2 Portobjects 357
5.2.1 The
NewPortObject abstraction 358
5.2.2 Anexample 359
5.2.3 Reasoningwithportobjects 360
5.3 Simplemessageprotocols 361
5.3.1 RMI(RemoteMethodInvocation) 361
5.3.2 AsynchronousRMI 364
5.3.3 RMIwithcallback(usingthread) 364
5.3.4 RMIwithcallback(usingrecordcontinuation) 366
5.3.5 RMI with callback (using procedure continuation) . . . . . 367
5.3.6 Errorreporting 367
5.3.7 AsynchronousRMIwithcallback 368
5.3.8 Doublecallbacks 369
5.4 Programdesignforconcurrency 370
5.4.1 Programmingwithconcurrentcomponents 370
Copyright
c
2001-3 by P. Van Roy and S. Haridi. All rights reserved.
viii CONTENTS
5.4.2 Designmethodology 372
5.4.3 Listoperationsasconcurrencypatterns 373
5.4.4 Lift control system 374
5.4.5 Improvements to the lift control system 383
5.5 Usingthemessage-passingconcurrentmodeldirectly 385
5.5.1 Portobjectsthatshareonethread 385
5.5.2 Aconcurrentqueuewithports 387
5.5.3 Athreadabstractionwithterminationdetection 390
5.5.4 Eliminatingsequentialdependencies 393
5.6 TheErlanglanguage 394
5.6.1 Computationmodel 394
5.6.2 IntroductiontoErlangprogramming 395
5.6.3 The receive operation 398
5.7 Advancedtopics 402
5.7.1 Thenondeterministicconcurrentmodel 402
5.8 Exercises 407
6 Explicit State 413
6.1 Whatisstate? 416
6.1.1 Implicit(declarative)state 416
6.1.2 Explicitstate 417
6.2 State and system building 418
6.2.1 Systemproperties 419
6.2.2 Component-basedprogramming 420
6.2.3 Object-orientedprogramming 421
6.3 Thedeclarativemodelwithexplicitstate 421
6.3.1 Cells 422
6.3.2 Semanticsofcells 424
6.3.3 Relationtodeclarativeprogramming 425
6.3.4 Sharingandequality 426
6.4 Abstractdatatypes 427
6.4.1 EightwaystoorganizeADTs 427
6.4.2 Variationsonastack 429
6.4.3 Revocable capabilities . . 433
6.4.4 Parameterpassing 434
6.5 Statefulcollections 438
6.5.1 Indexed collections 439
6.5.2 Choosinganindexedcollection 441
6.5.3 Othercollections 442
6.6 Reasoningwithstate 444
6.6.1 Invariantassertions 444
6.6.2 Anexample 445
6.6.3 Assertions 448
6.6.4 Proofrules 449
Copyright
c
2001-3 by P. Van Roy and S. Haridi. All rights reserved.
CONTENTS ix
6.6.5 Normaltermination 452
6.7 Programdesigninthelarge 453
6.7.1 Designmethodology 454
6.7.2 Hierarchical system structure . . . 456
6.7.3 Maintainability 461
6.7.4 Futuredevelopments 464
6.7.5 Furtherreading 466
6.8 Casestudies 467
6.8.1 Transitiveclosure 467
6.8.2 Wordfrequencies(withstatefuldictionary) 475
6.8.3 Generatingrandomnumbers 476
6.8.4 “WordofMouth”simulation 481
6.9 Advancedtopics 484
6.9.1 Limitationsofstatefulprogramming 484
6.9.2 Memorymanagementandexternalreferences 485
6.10Exercises 487
7 Object-Oriented Programming 493
7.1 Motivations 495
7.1.1 Inheritance . . 495
7.1.2 Encapsulatedstateandinheritance 497
7.1.3 Objectsandclasses 497
7.2 ClassesascompleteADTs 498
7.2.1 Anexample 499
7.2.2 Semanticsoftheexample 500
7.2.3 Definingclasses 501
7.2.4 Initializing attributes 503
7.2.5 First-classmessages 504
7.2.6 First-class attributes 507
7.2.7 Programmingtechniques 507
7.3 ClassesasincrementalADTs 507
7.3.1 Inheritance . . 508
7.3.2 Staticanddynamicbinding 511
7.3.3 Controlling encapsulation 512
7.3.4 Forwardinganddelegation 517
7.3.5 Reflection 522
7.4 Programmingwithinheritance 524
7.4.1 Thecorrectuseofinheritance 524
7.4.2 Constructingahierarchybyfollowingthetype 528
7.4.3 Genericclasses 531
7.4.4 Multipleinheritance 533
7.4.5 Rulesofthumbformultipleinheritance 539
7.4.6 Thepurposeofclassdiagrams 539
7.4.7 Designpatterns 540
Copyright
c
2001-3 by P. Van Roy and S. Haridi. All rights reserved.
x CONTENTS
7.5 Relationtoothercomputationmodels 543
7.5.1 Object-basedandcomponent-basedprogramming 543
7.5.2 Higher-orderprogramming 544
7.5.3 Functional decomposition versus type decomposition . . . 547
7.5.4 Shouldeverythingbeanobject? 548
7.6 Implementing the object system . 552
7.6.1 Abstractiondiagram 552
7.6.2 Implementingclasses 554
7.6.3 Implementingobjects 555
7.6.4 Implementinginheritance 556
7.7 TheJavalanguage(sequentialpart) 556
7.7.1 Computationmodel 557
7.7.2 IntroductiontoJavaprogramming 558
7.8 Activeobjects 563
7.8.1 Anexample 564
7.8.2 The
NewActive abstraction 564
7.8.3 TheFlaviusJosephusproblem 565
7.8.4 Otheractiveobjectabstractions 568
7.8.5 Eventmanagerwithactiveobjects 569
7.9 Exercises 574
8 Shared-State Concurrency 577
8.1 Theshared-stateconcurrentmodel 581
8.2 Programmingwithconcurrency 581
8.2.1 Overviewofthedifferentapproaches 581
8.2.2 Usingtheshared-statemodeldirectly 585
8.2.3 Programmingwithatomicactions 588
8.2.4 Furtherreading 589
8.3 Locks 590
8.3.1 BuildingstatefulconcurrentADTs 592
8.3.2 Tuplespaces(“Linda”) 594
8.3.3 Implementinglocks 599
8.4 Monitors 600
8.4.1 Bounded buffer 602
8.4.2 Programmingwithmonitors 605
8.4.3 Implementingmonitors 605
8.4.4 Anothersemanticsformonitors 607
8.5 Transactions 608
8.5.1 Concurrencycontrol 610
8.5.2 Asimpletransactionmanager 613
8.5.3 Transactionsoncells 616
8.5.4 Implementingtransactionsoncells 619
8.5.5 Moreontransactions 623
8.6 TheJavalanguage(concurrentpart) 625
Copyright
c
2001-3 by P. Van Roy and S. Haridi. All rights reserved.
CONTENTS xi
8.6.1 Locks 626
8.6.2 Monitors 626
8.7 Exercises 626
9 Relational Programming 633
9.1 Therelationalcomputationmodel 635
9.1.1 The
choice and fail statements 635
9.1.2 Searchtree 636
9.1.3 Encapsulatedsearch 637
9.1.4 The
Solve function 638
9.2 Furtherexamples 639
9.2.1 Numericexamples 639
9.2.2 Puzzles and the n-queensproblem 641
9.3 Relationtologicprogramming 644
9.3.1 Logicandlogicprogramming 644
9.3.2 Operationalandlogicalsemantics 647
9.3.3 Nondeterministiclogicprogramming 650
9.3.4 RelationtopureProlog 652
9.3.5 Logicprogramminginothermodels 653
9.4 Naturallanguageparsing 654
9.4.1 Asimplegrammar 655
9.4.2 Parsingwiththegrammar 656
9.4.3 Generatingaparsetree 656
9.4.4 Generatingquantifiers 657
9.4.5 Running the parser 660
9.4.6 Running the parser “backwards” . 660
9.4.7 Unificationgrammars 661
9.5 Agrammarinterpreter 662
9.5.1 Asimplegrammar 663
9.5.2 Encodingthegrammar 663
9.5.3 Running the grammar interpreter . 664
9.5.4 Implementingthegrammarinterpreter 665
9.6 Databases 667
9.6.1 Definingarelation 668
9.6.2 Calculatingwithrelations 669
9.6.3 Implementingrelations 671
9.7 TheProloglanguage 673
9.7.1 Computationmodel 674
9.7.2 IntroductiontoPrologprogramming 676
9.7.3 TranslatingPrologintoarelationalprogram 681
9.8 Exercises 684
Copyright
c
2001-3 by P. Van Roy and S. Haridi. All rights reserved.
xii CONTENTS
III Specialized Computation Models 687
10 Graphical User Interface Programming 689
10.1Basicconcepts 691
10.2Usingthedeclarative/proceduralapproach 692
10.2.1 Basicuserinterfaceelements 693
10.2.2 Buildingthegraphicaluserinterface 694
10.2.3 Declarativegeometry 696
10.2.4 Declarativeresizebehavior 697
10.2.5 Dynamicbehaviorofwidgets 698
10.3Casestudies 699
10.3.1 Asimpleprogressmonitor 699
10.3.2 Asimplecalendarwidget 700
10.3.3 Automaticgenerationofauserinterface 703
10.3.4 Acontext-sensitiveclock 707
10.4ImplementingtheGUItool 712
10.5Exercises 712
11 Distributed Programming 713
11.1 Taxonomy of distributed systems 716
11.2Thedistributionmodel 718
11.3Distributionofdeclarativedata 720
11.3.1 Opendistributionandglobalnaming 720
11.3.2 Sharingdeclarativedata 722
11.3.3 Ticketdistribution 723
11.3.4 Streamcommunication 725
11.4Distributionofstate 726
11.4.1 Simplestatesharing 726
11.4.2 Distributedlexicalscoping 728
11.5Networkawareness 729
11.6Commondistributedprogrammingpatterns 730
11.6.1 Stationaryandmobileobjects 730
11.6.2 Asynchronousobjectsanddataflow 732
11.6.3 Servers 734
11.6.4 Closeddistribution 737
11.7Distributionprotocols 738
11.7.1 Languageentities 738
11.7.2 Mobilestateprotocol 740
11.7.3 Distributedbindingprotocol 742
11.7.4 Memorymanagement 743
11.8Partialfailure 744
11.8.1 Faultmodel 745
11.8.2 Simplecasesoffailurehandling 747
11.8.3 A resilient server 748
Copyright
c
2001-3 by P. Van Roy and S. Haridi. All rights reserved.
CONTENTS xiii
11.8.4Activefaulttolerance 749
11.9Security 749
11.10Buildingapplications 751
11.10.1Centralizedfirst,distributedlater 751
11.10.2Handlingpartialfailure 751
11.10.3Distributedcomponents 752
11.11Exercises 752
12 Constraint Programming 755
12.1 Propagate and search . 756
12.1.1Basicideas 756
12.1.2Calculatingwithpartialinformation 757
12.1.3Anexample 758
12.1.4Executingtheexample 760
12.1.5Summary 761
12.2Programmingtechniques 761
12.2.1Acryptarithmeticproblem 761
12.2.2Palindromeproductsrevisited 763
12.3Theconstraint-basedcomputationmodel 764
12.3.1 Basic constraints and propagators . 766
12.4Computationspaces 766
12.4.1Programmingsearchwithcomputationspaces 767
12.4.2Definition 767
12.5Implementingtherelationalcomputationmodel 777
12.5.1 The
choice statement 778
12.5.2 Implementing the
Solve function 778
12.6Exercises 778
IV Semantics 781
13 Language Semantics 783
13.1Theshared-stateconcurrentmodel 784
13.1.1Thestore 785
13.1.2Thesingle-assignment(constraint)store 785
13.1.3Abstractsyntax 786
13.1.4Structuralrules 787
13.1.5Sequentialandconcurrentexecution 789
13.1.6 Comparison with the abstract machine semantics . . . . . 789
13.1.7Variableintroduction 790
13.1.8Imposingequality(tell) 791
13.1.9Conditionalstatements(ask) 793
13.1.10Names 795
13.1.11Proceduralabstraction 795
Copyright
c
2001-3 by P. Van Roy and S. Haridi. All rights reserved.
xiv CONTENTS
13.1.12Explicitstate 797
13.1.13By-needtriggers 798
13.1.14Read-onlyvariables 800
13.1.15Exceptionhandling 801
13.1.16Failedvalues 804
13.1.17Variablesubstitution 805
13.2Declarativeconcurrency 806
13.3Eightcomputationmodels 808
13.4Semanticsofcommonabstractions 809
13.5Historicalnotes 810
13.6Exercises 811
V Appendices 815
A Mozart System Development Environment 817
A.1 Interactiveinterface 817
A.1.1 Interfacecommands 817
A.1.2 Usingfunctorsinteractively 818
A.2 Batchinterface 819
B Basic Data Types 821
B.1 Numbers(integers,floats,andcharacters) 821
B.1.1 Operationsonnumbers 823
B.1.2 Operationsoncharacters 824
B.2 Literals(atomsandnames) 825
B.2.1 Operationsonatoms 826
B.3 Recordsandtuples 826
B.3.1 Tuples 827
B.3.2 Operationsonrecords 828
B.3.3 Operationsontuples 829
B.4 Chunks(limitedrecords) 829
B.5 Lists 830
B.5.1 Operationsonlists 831
B.6 Strings 832
B.7 Virtualstrings 833
C Language Syntax 835
C.1 Interactivestatements 836
C.2 Statementsandexpressions 836
C.3 Nonterminalsforstatementsandexpressions 838
C.4 Operators 838
C.4.1 Ternaryoperator 841
C.5 Keywords 841
C.6 Lexicalsyntax 843
Copyright
c
2001-3 by P. Van Roy and S. Haridi. All rights reserved.
CONTENTS xv
C.6.1 Tokens 843
C.6.2 Blankspaceandcomments 843
D General Computation Model 845
D.1 Creativeextensionprinciple 846
D.2 Kernellanguage 847
D.3 Concepts 848
D.3.1 Declarativemodels 848
D.3.2 Security 849
D.3.3 Exceptions 849
D.3.4 Explicitstate 850
D.4 Differentformsofstate 850
D.5 Otherconcepts 851
D.5.1 What’snext? 851
D.5.2 Domain-specificconcepts 851
D.6 Layeredlanguagedesign 852
Bibliography 853
Index 869
Copyright
c
2001-3 by P. Van Roy and S. Haridi. All rights reserved.
xvi
Copyright
c
2001-3 by P. Van Roy and S. Haridi. All rights reserved.
List of Figures
1.1 Taking apart the list [5678] 7
1.2 CalculatingthefifthrowofPascal’striangle 8
1.3 Asimpleexampleofdataflowexecution 17
1.4 All possible executions of the first nondeterministic example . . . 21
1.5 One possible execution of the second nondeterministic example . . 23
2.1 Fromcharacterstostatements 33
2.2 Thecontext-freeapproachtolanguagesyntax 35
2.3 Ambiguityinacontext-freegrammar 36
2.4 Thekernellanguageapproachtosemantics 39
2.5 Translationapproachestolanguagesemantics 42
2.6 Asingle-assignmentstorewiththreeunboundvariables 44
2.7 Twoofthevariablesareboundtovalues 44
2.8 Avaluestore:allvariablesareboundtovalues 45
2.9 Avariableidentifierreferringtoanunboundvariable 46
2.10Avariableidentifierreferringtoaboundvariable 46
2.11Avariableidentifierreferringtoavalue 47
2.12Apartialvalue 47
2.13 A partial value with no unbound variables, i.e., a complete value . 48
2.14Twovariablesboundtogether 48
2.15Thestoreafterbindingoneofthevariables 49
2.16Thetypehierarchyofthedeclarativemodel 53
2.17Thedeclarativecomputationmodel 62
2.18Lifecycleofamemoryblock 76
2.19Declaringglobalvariables 88
2.20TheBrowser 90
2.21Exceptionhandling 92
2.22Unificationofcyclicstructures 102
3.1 Adeclarativeoperationinsideageneralcomputation 114
3.2 Structureofthechapter 115
3.3 Aclassificationofdeclarativeprogramming 116
3.4 FindingrootsusingNewton’smethod(firstversion) 121
3.5 FindingrootsusingNewton’smethod(secondversion) 123
Copyright
c
2001-3 by P. Van Roy and S. Haridi. All rights reserved.
xviii LIST OF FIGURES
3.6 FindingrootsusingNewton’smethod(thirdversion) 124
3.7 FindingrootsusingNewton’smethod(fourthversion) 124
3.8 FindingrootsusingNewton’smethod(fifthversion) 125
3.9 Sortingwithmergesort 140
3.10Controlflowwiththreadedstate 141
3.11 Deleting node
Y whenonesubtreeisaleaf(easycase) 156
3.12 Deleting node
Y whenneithersubtreeisaleaf(hardcase) 157
3.13Breadth-firsttraversal 159
3.14Breadth-firsttraversalwithaccumulator 160
3.15Depth-firsttraversalwithexplicitstack 160
3.16Thetreedrawingconstraints 162
3.17Anexampletree 162
3.18Treedrawingalgorithm 164
3.19 The example tree displayed with the tree drawing algorithm . . . 165
3.20Delayedexecutionofaprocedurevalue 181
3.21Defininganintegerloop 186
3.22Definingalistloop 186
3.23Simpleloopsoverintegersandlists 187
3.24Definingaccumulatorloops 188
3.25Accumulatorloopsoverintegersandlists 189
3.26Foldingalist 190
3.27Declarativedictionary(withlinearlist) 199
3.28Declarativedictionary(withorderedbinarytree) 201
3.29Wordfrequencies(withdeclarativedictionary) 202
3.30 Internal structure of binary tree dictionary in
WordFreq (in part) 203
3.31 Doing
S1={Pop S X} withasecurestack 208
3.32AsimplegraphicalI/Ointerfacefortext 217
3.33Screenshotofthewordfrequencyapplication 228
3.34 Standalone dictionary library (file Dict.oz) 229
3.35 Standalone word frequency application (file WordApp.oz) 230
3.36 Component dependencies for the word frequency application . . . 231
4.1 Thedeclarativeconcurrentmodel 240
4.2 Causalordersofsequentialandconcurrentexecutions 242
4.3 Relationship between causal order and interleaving executions . . 242
4.4 Execution of the
thread statement 245
4.5 Thread creations for the call
{Fib 6} 254
4.6 The Oz Panel showing thread creation in
{Fib 26 X} 255
4.7 Dataflowandrubberbands 256
4.8 Cooperativeandcompetitiveconcurrency 259
4.9 Operationsonthreads 260
4.10Producer-consumerstreamcommunication 261
4.11Filteringastream 264
4.12Aprime-numbersievewithstreams 264
Copyright
c
2001-3 by P. Van Roy and S. Haridi. All rights reserved.
LIST OF FIGURES xix
4.13 Pipeline of filters generated by {Sieve Xs 316} 266
4.14 Bounded buffer 267
4.15 Bounded buffer (data-driven concurrent version) 267
4.16Digitallogicgates 272
4.17Afulladder 273
4.18Alatch 275
4.19Alinguisticabstractionforlogicgates 276
4.20 Tree drawing algorithm with order-determining concurrency . . . 278
4.21Procedures,coroutines,andthreads 280
4.22 Implementing coroutines using the
Thread module 281
4.23Concurrentcomposition 282
4.24Theby-needprotocol 287
4.25Stagesinavariable’slifetime 289
4.26Practicaldeclarativecomputationmodels 291
4.27 Bounded buffer (naive lazy version) 296
4.28 Bounded buffer (correct lazy version) . . . 296
4.29LazysolutiontotheHammingproblem 298
4.30Asimple‘PingPong’program 310
4.31Astandalone‘PingPong’program 311
4.32Astandalone‘PingPong’programthatexitscleanly 312
4.33ChangesneededforinstrumentingprocedureP1 317
4.34 How can two clients send to the same server? They cannot! . . . . 319
4.35Impedancematching:exampleofaserializer 326
5.1 Themessage-passingconcurrentmodel 356
5.2 Threeportobjectsplayingball 359
5.3 Messagediagramsofsimpleprotocols 362
5.4 Schematicoverviewofabuildingwithlifts 374
5.5 Component diagram of the lift control system 375
5.6 Notationforstatediagrams 375
5.7 Statediagramofaliftcontroller 377
5.8 Implementationofthetimerandcontrollercomponents 378
5.9 Statediagramofafloor 379
5.10Implementationofthefloorcomponent 380
5.11Statediagramofalift 381
5.12Implementationoftheliftcomponent 382
5.13 Hierarchical component diagram of the lift control system . . . . . 383
5.14Definingportobjectsthatshareonethread 386
5.15Screenshotofthe‘Ping-Pong’program 386
5.16 The ‘Ping-Pong’ program: using port objects that share one thread 387
5.17Queue(naiveversionwithports) 388
5.18Queue(correctversionwithports) 389
5.19Athreadabstractionwithterminationdetection 391
5.20Aconcurrentfilterwithoutsequentialdependencies 392
Copyright
c
2001-3 by P. Van Roy and S. Haridi. All rights reserved.
xx LIST OF FIGURES
5.21 Translation of receive withouttimeout 400
5.22 Translation of receive withtimeout 401
5.23 Translation of receive withzerotimeout 402
5.24Connectingtwoclientsusingastreammerger 404
5.25Symmetricnondeterministicchoice(usingexceptions) 407
5.26 Asymmetric nondeterministic choice (using
IsDet) 407
6.1 Thedeclarativemodelwithexplicitstate 422
6.2 Fivewaystopackageastack 429
6.3 Fourversionsofasecurestack 430
6.4 Differentvarietiesofindexedcollections 439
6.5 Extensiblearray(statefulimplementation) 443
6.6 A system structured as a hierarchical graph 456
6.7 Systemstructure–staticanddynamic 458
6.8 Adirectedgraphanditstransitiveclosure 466
6.9 Onestepinthetransitiveclosurealgorithm 467
6.10Transitiveclosure(firstdeclarativeversion) 469
6.11Transitiveclosure(statefulversion) 471
6.12Transitiveclosure(seconddeclarativeversion) 472
6.13Transitiveclosure(concurrent/parallelversion) 474
6.14Wordfrequencies(withstatefuldictionary) 476
7.1 An example class
Counter (with class syntax) 498
7.2 Defining the
Counter class(withoutsyntacticsupport) 499
7.3 Creating a
Counter object 500
7.4 Illegalandlegalclasshierarchies 508
7.5 Aclassdeclarationisanexecutablestatement 509
7.6 An example class
Account 510
7.7 Themeaningof“private” 513
7.8 Differentwaystoextendfunctionality 517
7.9 Implementingdelegation 519
7.10Anexampleofdelegation 521
7.11Asimplehierarchywiththreeclasses 525
7.12Constructingahierarchybyfollowingthetype 527
7.13Listsinobject-orientedstyle 528
7.14Agenericsortingclass(withinheritance) 529
7.15Makingitconcrete(withinheritance) 530
7.16Aclasshierarchyforgenericity 530
7.17Agenericsortingclass(withhigher-orderprogramming) 531
7.18Makingitconcrete(withhigher-orderprogramming) 532
7.19Classdiagramofthegraphicspackage 534
7.20Drawinginthegraphicspackage 536
7.21Classdiagramwithanassociation 537
7.22TheCompositepattern 541
Copyright
c
2001-3 by P. Van Roy and S. Haridi. All rights reserved.
LIST OF FIGURES xxi
7.23Functionaldecompositionversustypedecomposition 548
7.24Abstractionsinobject-orientedprogramming 553
7.25 An example class
Counter (again) 554
7.26Anexampleofclassconstruction 555
7.27Anexampleofobjectconstruction 556
7.28Implementinginheritance 557
7.29ParameterpassinginJava 562
7.30Twoactiveobjectsplayingball(definition) 563
7.31 Two active objects playing ball (illustration) 564
7.32TheFlaviusJosephusproblem 565
7.33TheFlaviusJosephusproblem(activeobjectversion) 566
7.34 The Flavius Josephus problem (data-driven concurrent version) . 568
7.35Eventmanagerwithactiveobjects 570
7.36Addingfunctionalitywithinheritance 571
7.37Batchingalistofmessagesandprocedures 572
8.1 Theshared-stateconcurrentmodel 580
8.2 Differentapproachestoconcurrentprogramming 582
8.3 Concurrentstack 586
8.4 Thehierarchyofatomicactions 588
8.5 Differencesbetweenatomicactions 589
8.6 Queue(declarativeversion) 591
8.7 Queue(sequentialstatefulversion) 592
8.8 Queue(concurrentstatefulversionwithlock) 593
8.9 Queue(concurrentobject-orientedversionwithlock) 594
8.10Queue(concurrentstatefulversionwithexchange) 595
8.11Queue(concurrentversionwithtuplespace) 596
8.12Tuplespace(object-orientedversion) 597
8.13 Lock (non-reentrant version without exception handling) . . . . . 598
8.14Lock(non-reentrantversionwithexceptionhandling) 598
8.15Lock(reentrantversionwithexceptionhandling) 599
8.16 Bounded buffer (monitor version) 604
8.17Queue(extendedconcurrentstatefulversion) 606
8.18Lock(reentrantget-releaseversion) 607
8.19Monitorimplementation 608
8.20Statediagramofoneincarnationofatransaction 615
8.21 Architecture of the transaction system . . 619
8.22 Implementation of the transaction system (part 1) 621
8.23 Implementation of the transaction system (part 2) 622
8.24Priorityqueue 624
8.25 Bounded buffer (Java version) 627
9.1 Searchtreefortheclothingdesignexample 637
9.2 Twodigitcountingwithdepth-firstsearch 640
Copyright
c
2001-3 by P. Van Roy and S. Haridi. All rights reserved.
xxii LIST OF FIGURES
9.3 The n-queens problem (when n =4) 642
9.4 Solving the n-queensproblemwithrelationalprogramming 643
9.5 Naturallanguageparsing(simplenonterminals) 658
9.6 Naturallanguageparsing(compoundnonterminals) 659
9.7 Encodingofagrammar 664
9.8 Implementingthegrammarinterpreter 666
9.9 Asimplegraph 669
9.10Pathsinagraph 671
9.11Implementingrelations(withfirst-argumentindexing) 672
10.1Buildingthegraphicaluserinterface 693
10.2Simpletextentrywindow 694
10.3Functionfordoingtextentry 695
10.4 Windows generated with the
lr and td widgets 695
10.5 Window generated with
newline and continue codes 696
10.6Declarativeresizebehavior 697
10.7 Window generated with the
glue parameter 698
10.8Asimpleprogressmonitor 700
10.9Asimplecalendarwidget 701
10.10Automaticgenerationofauserinterface 703
10.11Fromtheoriginaldatatotheuserinterface 704
10.12Definingtheread-onlypresentation 705
10.13Definingtheeditablepresentation 705
10.14ThreeviewsofFlexClock,acontext-sensitiveclock 707
10.15Architectureofthecontext-sensitiveclock 707
10.16Viewdefinitionsforthecontext-sensitiveclock 710
10.17Thebestviewforanysizeclockwindow 711
11.1 A simple taxonomy of distributed systems 717
11.2Thedistributedcomputationmodel 718
11.3Process-orientedviewofthedistributionmodel 720
11.4Distributedlocking 727
11.5Theadvantagesofasynchronousobjectswithdataflow 733
11.6Graphnotationforadistributedcell 741
11.7Movingthestatepointer 741
11.8Graphnotationforadistributeddataflowvariable 742
11.9Bindingadistributeddataflowvariable 742
11.10A resilient server 748
12.1 Constraint definition of Send-More-Money puzzle 762
12.2Constraint-basedcomputationmodel 765
12.3Depth-firstsinglesolutionsearch 768
12.4 Visibility of variables and bindings in nested spaces . 770
12.5 Communication between a space and its distribution strategy . . . 775
12.6 Lazy all-solution search engine
Solve 779
Copyright
c
2001-3 by P. Van Roy and S. Haridi. All rights reserved.
LIST OF FIGURES xxiii
13.1Thekernellanguagewithshared-stateconcurrency 787
B.1 Graph representation of the infinite list
C1=a|b|C1 832
C.1 The ternary operator “
.:=” 840
Copyright
c
2001-3 by P. Van Roy and S. Haridi. All rights reserved.
xxiv
Copyright
c
2001-3 by P. Van Roy and S. Haridi. All rights reserved.
List of Tables
2.1 Thedeclarativekernellanguage 50
2.2 Valueexpressionsinthedeclarativekernellanguage 51
2.3 Examplesofbasicoperations 56
2.4 Expressionsforcalculatingwithnumbers 82
2.5 The
if statement 83
2.6 The
case statement 83
2.7 Functionsyntax 85
2.8 Interactivestatementsyntax 88
2.9 Thedeclarativekernellanguagewithexceptions 94
2.10Exceptionsyntax 95
2.11 Equality (unification) and equality test (entailment check) . . . . 100
3.1 Thedescriptivedeclarativekernellanguage 117
3.2 The parser’s input language (which is a token sequence) 166
3.3 Theparser’soutputlanguage(whichisatree) 167
3.4 Executiontimesofkernelinstructions 170
3.5 Memoryconsumptionofkernelinstructions 176
3.6 Thedeclarativekernellanguagewithsecuretypes 206
3.7 Functorsyntax 224
4.1 Thedata-drivenconcurrentkernellanguage 240
4.2 Thedemand-drivenconcurrentkernellanguage 285
4.3 The declarative concurrent kernel language with exceptions . . . . 332
4.4 Dataflowvariableascommunicationchannel 337
4.5 Classifyingsynchronization 340
5.1 Thekernellanguagewithmessage-passingconcurrency 355
5.2 Thenondeterministicconcurrentkernellanguage 403
6.1 Thekernellanguagewithexplicitstate 423
6.2 Celloperations 423
7.1 Classsyntax 501
8.1 Thekernellanguagewithshared-stateconcurrency 580
Copyright
c
2001-3 by P. Van Roy and S. Haridi. All rights reserved.