Sie sind auf Seite 1von 118
By Mark Lewis and Lisa Lacher

By Mark Lewis and Lisa Lacher

By Mark Lewis and Lisa Lacher
Introduction to Programming and Problem Solving Using Scala

Introduction to Programming and Problem Solving Using Scala

Introduction to Programming and Problem Solving Using Scala

2

  Preface Welcome to “Introduction to Programming and Problem Solving Using Scala”. This book is
  Preface Welcome to “Introduction to Programming and Problem Solving Using Scala”. This book is
 

Preface

Welcome to “Introduction to Programming and Problem Solving Using Scala”. This book is intended to be used in first semester college classrooms to teach students beginning programming. To accomplish this task, the Scala 1 programming language is used. The book was constructed with a focus on the topics students need to know. These topics were then woven into a format that was deemed the best way to communicate those ideas. Because there are two very different audiences who might be reading this, the rest of the preface is split into two sections.

 

To the Student

Welcome to the world of programming. You are about to embark on a field of study that will hopefully open your mind to new ways of thinking and impact the way you view everything in the world around you. For students who intend to major in Computer Science and make careers working with computer technology, this is your first step in learning how to communicate with the computer and to instruct the computer in how it should solve problems for you. For those who are not planning to make a career in a computing field, a course in computer programming can still be remarkably beneficial. Computer programming is, fun- damentally, about problem solving. It is about figuring out how to solve problems and express them in ways that the computer can understand. Your entire future life is, in one way or another, going to deal with how to solve problems. You will need to have approaches to solving these problems well formed in your own head and be able to communicate them to other people in non-ambiguous ways so that they understand what you want and can act on it. Learning to program computers will help you develop and hone this ability. There are more direct benefits as well. The world you live in is already extremely depen- dent on computing. Many of the things you own that you do not call a computer include microchips and digital processing. Those devices/objects run programs to complete their tasks. Many of the tasks you do during an average day are also enabled by computer power and the ability to process and store information quickly. Activities like browsing the web for work or leisure explicitly involve this. Other activities such as financial transactions made with anything other than cash implicitly involve it. This ubiquitous presence of digital pro- cessing is only going to grow over time. So even if you never have to directly write programs as part of your future life, you can only benefit from having an understanding of what is going on under the hood. Even if you do not write the software yourself, there is a good chance that you will interact with those who do, perhaps as you or your company strives to gain a competitive advantage by improving the information technology you use to do your

 

1 Code samples in this book were compiled and tested using Scala 2.12.x.

i

i

i
  ii work. Even a basic knowledge of programming will help you understand what these
  ii work. Even a basic knowledge of programming will help you understand what these
 

ii

work. Even a basic knowledge of programming will help you understand what these people are doing and communicate more effectively with them. Those who do not intend to make programming into a career might occasionally come across problems where they realize that they could save a lot of time if they could get a computer to do it for them. When that happens, even a basic knowledge of programming can make your life a whole lot better. Data is becoming a bigger and bigger part of the business world. The vast amounts of data created and collected by modern technology can not be processed by humans manually. To sift through this data to find meaning requires using machines, and that means using software. You can either pay someone else to write it or you can write it yourself. That latter is only an option if you know how to program. While many might be tempted to view programming as an advanced concept, the reality is this book is going to take you back to your early education quite a few times. The reason for this is you spent a lot of time in those early years learning how to solve certain basic problems. The approaches became second nature to you and you no longer think about them, you just do them. In the context of programming you have to go back and examine how you solve problems, even ones you have been doing for a long time. The reason for this is now you have to tell a computer how to do those same things, and the computer will need detailed instructions. The reality is, the programming presented in this book is not an advanced topic, it is basic logic and problem solving, done at a level you probably have not worked at since you were much younger. I over refer to programming as an art. Programming shares many features with tradi- tional arts like creative writing and painting or sculpture. The programmer first creates a vague image in his/her mind of what he/she wants to bring into existence. This is followed by a period of work bringing that mental image into a more real form. The end result is something new, born from the imagination of the creator, that can be experienced by oth- ers 2 . The digital medium might, in some sense, seem less real than paint, clay, or stone, but it is also remarkably dynamic. You can create things in a computer that you have no chance of creating in the real world by hand. You can also create things that are remarkably useful. All the software you interact with every day, whether to get things done or just for entertainment, was written by programmers. The exercises and projects in this book have been created with the goal of giving you the ability to express your creativity. Programming bears another characteristic in common with other creative arts, if you want to be good at it, you need to practice. There are many ways to program the solution to any problem. That introduces a lot of nuance. This book will strive to instruct you in regards to the strengths and weaknesses of different approaches, but to really understand how to write good code to solve a problem, you need to have the experience of solving similar ones. Imagine an art major who never draws or paints except for class projects, not even doodling in notes, or a creative writing major who never writes a story except the ones required for class. Hopefully those seem silly to you. A computer science major who never writes code beyond what is assigned for class is exactly the same. So explore the art of programming. Have fun with it and try to do something that interests you.

 

Using this Book

The goal of this book is to help you in your efforts to learn how to program. In addition to the practice that was just mentioned, there are some suggestions for how to get the most out of this book. Clearly, working as many exercises and projects as you can counts as practice. In addition, you should really read descriptions in this book and make sure you understand

 

2 I particularly like the tag line of @muddlymon on Twitter during the time I was writing this book, which read ”I make things out of ideas by wiggling my fingers.”

on Twitter during the time I was writing this book, which read ”I make things out
on Twitter during the time I was writing this book, which read ”I make things out
iii

iii

iii
 

the code samples shown in it. All too often, students treat the task of reading course material as sounding out all the words in your head. While that fits the denotative definition, the connotation is that you string the words together and understand what they mean together. Read for understanding, not just so you can say you have gotten through a chapter. Gaining understanding of early material is especially important in this topic because the material in any given chapter is typically highly dependent on the chapters before it. If you fail to understand one chapter, you are not likely to understand the ones that follow it either. As such, effort spent on the early chapters will pay off later on. Fortunately, there are resources that accompany this book that can help with this. Students coming into this course who have a background in programming should consider taking a “fast path” to chapters ?? and ??. You do not want to skip them completely as there are aspects of Scala that will likely differ from what you have done before. One way to approach this is the go to the end of any given chapter and try to do the exercises. Refer back to the chapter as needed to complete them. Once you can do the exercises and

a

project or two, you should feel comfortable moving on.

Book Website

 

The author has posted a number of different supplements to this book at http://book. programmingusingscala.net that can help you work through the material. Some of the material is code or prose that could not be put into the book due to length restrictions. The most useful things on the website are things that can not be represented in static text. There are video lectures posted on my YouTube channel (https://www.youtube.com/ channel/UCEvjiWkK2BoIH819T-buioQ) that follow along with the material in this book. They are organized in playlists by chapter. Programming is a very non-linear process. This book typically shows completed pieces of code that do what we want. It is hard to demon- strate the process of building that code in the format of a book. The videos show construc- tion of code from the ground up and include descriptions of the programmers thoughts as it

 

is

being done. This type of “live coding” is invaluable in learning to program as it lets you

into the mind of a more experienced programmer where you can see the thought processes associated with the development of the code. The web site also includes solutions of some exercises for you to reference along with sample implementations of certain projects. Some of the projects, especially in the second half of the book, can be challenging to describe in text. To give you a better idea of what is expected, the author has implemented sample solutions that you can run to see what they do. The site also includes some additional exercises and links to data files and remote sites that make the exercises more relevant. The second half of the book also includes large projects. For these, there are UML diagrams of the author’s sample solution to help students see possible ways of breaking their problem down.

To the Instructor

 

If you are reading this, it likely means that you are already aware of many of the features of Scala that make it a great programming language. 3 The flexibility of Scala means that

 
3 If you are currently unconvinced of the benefits of Scala for teaching CS1 and

3 If you are currently unconvinced of the benefits of Scala for teaching CS1 and CS2, there is a complete discussion at http://book.programmingusingscala.net.

benefits of Scala for teaching CS1 and CS2, there is a complete discussion at http://book.programmingusingscala.net .
  iv things can be covered in many different ways. The approach taken in this
  iv things can be covered in many different ways. The approach taken in this
 

iv

things can be covered in many different ways. The approach taken in this book might be summarized as semi-functional/semi-imperative with objects later. It is worth describing exactly what is meant by that. This book takes advantage of the aspects of Scala that support programming in the small. It is expected that students will operate mainly in the REPL and in a scripting environment through at least the first 10 chapters and possibly through the first 15. The benefit of this is that you can focus on logic instead of extra keywords and scoping rules. Students are easily overwhelmed early on and this approach helps to flatten the learning curve a bit. Scala is purely object-oriented, so students will be using objects and calling methods on objects very early on. However, the construction of classes to build their own objects is postponed until later 4 . Fitting with this approach, programs are written as scripts, not as applications, until the last chapter of this book. So the object keyword and things like def main(args: Array[String]) : Unit are postponed until students are ready to write programs that are big enough that they need the organization provided by doing proper OO across multiple files. The approach is described as semi-functional because there is significant use of higher order functions and function literals and immutable style is often preferred. However, this is not enforced in a zealotous way and mutable state is introduced early on. Students are shown mutable and immutable approaches to a number of problems and the benefits and pitfalls of each approach are discussed. While the ideal way to go through this book is in a linear fashion, particularly if you want to use the end-of-chapter projects as assignments, strict linearity is not required and you can choose to move some topics around so that concepts like class declarations are covered earlier. Though it would be a bit more challenging, it would be possible to use this book in a more purely functional manner by simply having students avoid var declarations, assignments into mutable collections like arrays, and the use of while loops.

 

Using this Book

This book is intended to cover CS1. When looking at the chapter list, you might feel that chapters ?? and ?? are outliers in certain ways. They definitely break from the straight algorithmic, problem solving nature of the other chapters. This break was placed at this point in the book at the request of students who often find visual interfaces more compelling than text based ones. Thanks to the syntax of Scala, it is possible to build GUIs without explicitly declaring classes or using keywords associated with it, such as extends. It is possible to skip these, but not advised as graphics play a role in many of the examples later in the book. If you have a desire to cover full OO concepts earlier, chapter ?? can be moved to closely follow chapter ??. There are also a number of chapters through the book that contain material that can be skipped completely. For example, chapter ?? covers XML. Scala makes this fairly easy to do and it fits in well with the projects that are given to have students work on stored data in a formatted manner. However, if you don’t want to spend time on that topic it can be skipped with little impact on later content other than projects and occasional usage in later chapters. To help you decide what you can and can’t skip, figure 1 shows rough dependencies for different chapters in the book. Arrows point from one chapter to later ones that have direct

 

4 That material is covered very briefly at the end of this volume, but most of the treatment for doing real OO is postponed to the second volume ”Object-orientation, Abstraction, and Data Structure Using Scala”.

for doing real OO is postponed to the second volume ”Object-orientation, Abstraction, and Data Structure Using
for doing real OO is postponed to the second volume ”Object-orientation, Abstraction, and Data Structure Using

1 : Basics of Computers

1 : Basics of Computers 2 : Tools 3 : Scala Basics 17 : Wrapping Up

2 : Tools

1 : Basics of Computers 2 : Tools 3 : Scala Basics 17 : Wrapping Up

3 : Scala Basics

17 : Wrapping Up

of Computers 2 : Tools 3 : Scala Basics 17 : Wrapping Up v 16 :

v

16 : Object-Orientation 4 : Conditionals 15 : Recursion 14 : XML 5 : Functions
16 : Object-Orientation
4 : Conditionals
15 : Recursion
14 : XML
5
: Functions
6 : Recursion for Iteration
7 : Array and Lists
13 : Sorting and Searching
8 : Loops
12 : Graphics
9 : Text Files
10 : Case Classes
11 : GUIs

FIGURE 1: This figure shows the dependencies between different chapters in the book so that you can plan what you want to cover or to allow you to intelligently choose alternate paths through the book. Arrows point toward later chapters that use material from an earlier chapter.

dependencies. There will be occasional references to material that is not in the line of the dependency arrows, but the material should still be understandable. The course web site, http://book.programmingusingscala.net, includes a number of different types of material that can be helpful for instructors. There are solutions to certain exercises so you should check there before using exercises for grading purposes. Additional exercises with recent links and data sets are also available on the web. There are executable JAR files for some of the projects to help students, and instructors, understand what is being asked for from the student. In the second half of the book, the projects get bigger and the website shows UML diagrams of the authors solutions. Code for projects is never given so they are safe for graded material. In addition, there are videos posted for many sections of the text. These are generally “live coding” sessions. Instructors should feel free to use these as pre-lectures or to use with a flipped classroom format.

vi

  Contents 1 Basics of Computers, Computing, and Programming   3 1.1 History . .
  Contents 1 Basics of Computers, Computing, and Programming   3 1.1 History . .
 

Contents

1 Basics of Computers, Computing, and Programming

 

3

1.1 History

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

3

1.2 Hardware

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

5

1.2.1

Central Processing Unit

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

5

1.2.2

1.2.3

1.3 Software

. Input/Output Devices .

.

Memory

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

6

7

8

1.4 Nature of Programming

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

10

1.5 Programming Paradigms

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

12

1.5.1 Imperative Programming

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

12

1.5.2 Functional Programming

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

12

1.5.3 Object-Oriented Programming

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

13

1.5.4 Logic Programming

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

14

1.5.5 Nature of Scala .

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

14

1.6 End of Chapter Material

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

14

1.6.1 Summary of Concepts

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

14

1.6.2 Exercises

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

15

1.6.3

Projects

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

16

2 Scala Basics

17

2.1 Scala Tools

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

17

2.2 Expressions, Types, and Basic Math

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

19

2.3 Objects and Methods

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

23

2.4 Other Basic Types

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

24

2.5 Back to the Numbers

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

27

2.5.1 Binary Arithmetic

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

29

2.5.2 Negative Numbers in Binary

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

30

2.5.3 Other Integer Types

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

31

2.5.4 Octal and Hexadecimal

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

32

2.5.5 Non-Integer Numbers

 

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

33

2.6 The math Object

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

34

2.7 Naming Values and Variables

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

36

2.7.1 Patterns in Declarations

 

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

38

2.7.2 Using Variables .

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

38

2.8 Details of Char and String

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

40

2.8.1 Escape Characters

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

40

2.8.2 Raw Strings

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

40

2.8.3 String Interpolation

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

41

2.8.4 String Methods .

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

41

2.8.5 Immutability of Strings

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

44

2.9 Sequential Execution

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

44

vii

vii

vii
  viii   2.9.1 Comments   . . . . . . . . .
  viii   2.9.1 Comments   . . . . . . . . .
 

viii

 

2.9.1

Comments

 

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

45

 

2.10 A Tip for Learning to Program

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

46

2.11 End of Chapter Material

 

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

47

 

2.11.1 Problem Solving Approach

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

47

2.11.2 Summary of Concepts

 

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

47

2.11.3 Self-Directed Study

 

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

49

2.11.4 Exercises

 

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

49

 

3

Conditionals

 

53

 

3.1 Motivating Example

 

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

53

3.2 The if Expression

 

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

54

3.3 Comparisons

 

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

58

3.4 Boolean Logic

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

59

3.5 Precedence

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

62

3.6 Nesting ifs

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

63

3.7 End of Chapter Material

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

67

 

3.7.1 Problem Solving Approach

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

67

3.7.2 Summary of Concepts

 

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

67

3.7.3 Self-Directed Study

 

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

68

3.7.4 Exercises

 

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

69

3.7.5 Projects

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

70

 

A Getting to Know the Tools

 

75

 

A.1

Unix/Linux (includes Mac OS X)

 

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

76

 

A.1.1

Command Line

.

.

.

.

.