In Scala, val declares immutable variables and var declares mutable variables. The value of a val cannot be changed after declaration, while the value of a var can be reassigned.
2. Overview
today’s lecture
A new course
• from IN1605-B to TI1220
What is this course about?
• why study concepts of programming languages?
How is this course organized?
• lectures and assignments
Introduction to Scala
• writing and running Scala programs
TI1220 - Introduction 2
4. A New Course
the only constant is change
IN1605-B: Algoritmen en Programmeertalen:
Programmeertalen
• 4 ECTS
• Haskell + C
• Peter Kluijt
TI1220: Concepten van Programmeertalen
• 6 ECTS
• Scala + C + JavaScript
• Eelco Visser
TI1220 - Introduction 4
5. Under New Management
Eelco Visser
Lecturer
• Dr. Eelco Visser
• UHD in Software Engineering Research Group
• http://eelcovisser.org
• Contact: e.visser@tudelft.nl
• first ask student assistants
• send questions by email
• appointment if necessary
TI1220 - Introduction 5
6. My Research
software language design & engineering
Spoofax Language Workbench
• design and implement languages & IDEs
• from high-level declarative specification
Domain-specific language design
• WebDSL: a DSL for web programming
• Mobl: a DSL for mobile web applications
Interaction design
• researchr.org: building a digital library
TI1220 - Introduction 6
7. Examination Old Course
You can still sit for exams of IN1605-B
• Provided you have finished the lab (practicum)
Sittings
• Together with exam for this course (TI1220)
• April 11, 2010
• June 22, 2010
TI1220 - Introduction 7
8. Feedback Appreciated
An invitation to Murphy
• New content
• New software
• New lectures, assignments, exams
• New lecturer
• New assistants (mostly)
Please let us know how it goes
• report problems early
• also let us know what goes right :)
TI1220 - Introduction 8
13. Turing Machines
computability
Turing/Church Thesis
• Every effective computation can be carried out by a
Turing machine*
Corollary
• All (Turing Complete) programming languages can
express all effective computations
• Why bother with new programming languages?
(*) see IN2505
TI1220 - Introduction 13
15. Programming Languages in TI
TI1200: Object-Oriented Programming
• Java
TI1400: Computer Systems
• Assembly
TI1500: Web- and Database Technology
• HTML, PHP, SQL, JavaScript
TI1600: Multi-Agent Systems
• Prolog, GOAL
TI1220 - Introduction 15
16. “A programming language is low level when its
programs require attention to the irrelevant”
Alan J. Perlis. Epigrams on Programming. SIGPLAN Notices, 17(9):7-13, 1982.
TI1220 - Introduction 16
17. Understanding Computation
purpose of programming languages
Encoding computation
• Computer needs list of instructions to move its parts
Understanding computation
• Discuss concepts
• Formulate algorithms
• Reason about problem solutions
Programming languages are for people
TI1220 - Introduction 17
18. Increasing the Level of Abstraction
concepts of programming languages
calc:
push eBP ; save old frame pointer
mov eBP,eSP ; get new frame pointer
sub eSP,localsize ; reserve place for locals
.
. ; perform calculations, leave result in AX
.
mov eSP,eBP ; free space for locals
pop eBP ; restore old frame pointer
ret paramsize ; free parameter space and return
push eAX ; pass some register result
push byte[eBP+20] ; pass some memory variable (FASM/TASM syntax)
push 3 ; pass some constant
call calc ; the returned result is now in eAX
http://en.wikipedia.org/wiki/Calling_convention
def f(x)={ ... } f(e1)
TI1220 - Introduction 18
19. Programming Models
concepts of programming languages
Language provides model of computation
• data & operations, composition & abstraction
Language targets application domain
• Systems programming
• Embedded systems
• Web programming
• Enterprise software
TI1220 - Introduction 19
20. Programming Language DNA
concepts of programming languages
Scope and binding
• declaration and binding of names, free and bound
occurrences, renaming, substitution
Data structures
• product and sum types, records, recursive types
Modularization and data abstraction
• modules, classes, higher-order functions, class-based
vs prototype inheritance
Syntax and interpretation
TI1220 - Introduction 20
21. Why Study Concepts?
concepts of programming languages
Design abstractions for new domains
• from library to language feature
• apply PL techniques (MapReduce)
Learn new computational models
• understand fundamental ideas underlying PLs
• experience with variety of models
• learn new languages in future
Choosing the right language
TI1220 - Introduction 21
22. Goals of this Course
concepts of programming languages
• Understand programming languages and programs in
terms of concepts that transcend individual languages
• Consider advantages and disadvantages in the use of
particular languages and concepts
• Analyze programs in terms of concepts
• Application of concepts in designing programs
TI1220 - Introduction 22
23. Approach
concepts of programming languages
Study three concrete languages
• Scala + C + JavaScript
• Learn to program in these languages
• Learn concepts by using them in programming
• Programming assignments about languages
Generalize
• What are the underlying ideas?
• Learn to learn new languages
TI1220 - Introduction 23
24. Scala
functional programming
• Lecture 1: Getting Started with Scala
• Lecture 2: Functional Objects
• Lecture 3: Functions & Closures
• Lecture 4: List Programming (Recursion)
• Lecture 5: Trees & XML
• Lecture 6: Composition, Inheritance, Traits
• Lecture 7: Modular Programming
• Assignment: interpreter for tiny functional language
TI1220 - Introduction 24
25. C
systems programming
• Lecture 8: Memory Management
• stack vs heap
• pointers
• Lecture 9: Implementing Objects
• function pointers
• simulating dynamic dispatch
• Assignment: implementing OO in C
TI1220 - Introduction 25
26. JavaScript
web programming
Prototype-Based Object-Oriented Language
• Lecture 10: Prototypal Inheritance
• History: Smalltalk, Self (Squeak)
• Lecture 11: Asynchronous functions
• Lecture 12: DOM manipulation
• Lecture 13: Regular expressions
• Lecture 14: mobl: a domain-specific language for the
mobile web
• Assignment: playing with prototypes
TI1220 - Introduction 26
27. Meta-Programming
implementation of programming languages
Other courses consider internals of languages
• IN2505: Fundamental Computer Science 2: Theory of Computation
• grammars and automata
• IN4303: Compiler Construction
• translation of high-level source to machine language
• IN4308: Model-Driven Software Development
• design of domain-specific software languages
TI1220 - Introduction 27
29. Ingredients
course organization
This is a semester course
• Q3 + Q4
Lectures
• Tuesday morning
Practicum
• on Tuesday or Thursday afternoon
• Exercises + Graded Assignments
Exams
TI1220 - Introduction 29
30. Exams
course organization
Exam 1
• Monday 11 April, 2011, 9:00-12:00
• E1: about material of Q3 (Scala)
Exam 2
• Wednesday, 22 June, 2011, 9:00-12:00
• If Exam 1 >= 6
• then E2a: material of Q4 (C+JavaScript)
• else E2b: material Q3+Q4 (Scala+C+JavaScript)
TI1220 - Introduction 30
31. Exams
course organization
Exam 3 (resit)
• If Exam 2 < 6, even if Exam 1 >= 6
• Wednesday, 24 August, 2011, 9:00-12:00
• E3: material Q3+Q4 (Scala+C+JavaScript)
Note
• next year programming exams
TI1220 - Introduction 31
32. Practicum
course organization
Scala (Q3)
• Exercises: hand in on paper to assistants at end of lab!
• Assignment 1 (graded)
C (Q4)
• Assignment 2 (graded)
JavaScript (Q4)
• Assignment 3 (graded)
Graded assignments should be submitted as code
TI1220 - Introduction 32
33. Final Grade
course organization
val H = all exercises handed in
val A = 0.4*A1 + 0.3*A2 + 0.3*A3
val E2 = if(E1 >= 6) (E1 + E2a)/2
else E2b
val E = if(E2 >= 6) E2 else E3
val G = if(H && Ai >= 6 && E >= 6)
0.4*A + 0.6E
else min(E, 5)
TI1220 - Introduction 33
35. Practicum Assistants
course organization
Tuesday Thursday
Maartje de Jonge Sander van der Burg
Laurent Verweijen Bart van Vuuren
Vlad Vergu Peter Pul
Joost Heijkoop
TI1220 - Introduction 35
38. Programming Language Schools
imperative vs functional programming
Imperative Programming (Algol, C, Pascal)
• programming with side effects
• structured control-flow
Object-Oriented Programming (C++, Java)
• imperative programming with data abstraction
Functional Programming (ML, Haskell)
• functions as first-class citizens
• immutable data (pure)
TI1220 - Introduction 38
39. Pizza
history
POPL 1997 Philip Wadler, Martin Odersky, Gilad Bracha, Dave Stoutamire (source: http://lamp.epfl.ch/pizza/gj/)
• "Pizza into Java: Translating theory into practice", Martin Odersky and
Philip Wadler. Proc. 24th ACM Symposium on Principles of Programming
Languages, Paris, France, January 1997.
Extending Java with Functional Concepts
• Parametric polymorphism (generics)
• First-class functions (function pointers)
• Algebraic data types (class cases and pattern matching)
Continued in GJ and Java Generics
TI1220 - Introduction 39
40. Scala
history
A Scalable Language
• object-oriented + functional programming
Properties
• compatible (combines with Java)
• concise (sugar + abstractions)
• high-level
• statically typed
Designed by Martin Odersky et al. at EPFL
TI1220 - Introduction 40
41. Scala in Industry
history
Scala at Twitter
• Ruby-on-Rails did not scale
• Replaced back-end processing (API) with Scala
BankSimple
• Back-end services in Scala or Clojure
Alex Payne
• Programming Scala by Wampler & Payne
TI1220 - Introduction 41
42. Programming in Scala
Book
Programming in Scala
A comprehensive step-by-step guide
by Martin Odersky, Lex Spoon, and Bill Venners
http://www.artima.com/shop/programming_in_scala
Available as e-book (PDF)
Lectures are based on book; not everything in book is on slides; reading
book is required; see Literature slides at end of each lecture for required
reading!
TI1220 - Introduction 42
43. Installing Scala
Download Interpreter & Compiler
• Make your own installation (assignment 1)
• http://www.scala-lang.org/downloads
Editors
• Emacs, Vi, <your favorite editor>
Integrated Development Environments
• Plugins for Eclipse, IntelliJ, NetBeans
B:2.1 TI1220 - Introduction 43
44. The Scala Interpreter
$ scala
Welcome to Scala version 2.8.0.final (Java HotSpot(TM)
64-Bit Server VM, Java 1.6.0_22).
Type in expressions to have them evaluated.
Type :help for more information..
B:2.1 TI1220 - Introduction 44
47. Variable Declaration and Use
binding values to names
scala> val msg = "Hello, world!"
msg: java.lang.String = Hello, world!
scala> val msg2: java.lang.String =
| "Hello again, world!"
msg2: java.lang.String = Hello again, world!
scala> val msg3: String = "Hello yet again, world!"
msg3: String = Hello yet again, world!
scala> println(msg)
Hello, world!
B:2.2 TI1220 - Introduction 47
48. Immutable and Mutable Variables
changing value bound to name
scala> msg = "Goodbye cruel world!"
<console>:6: error: reassignment to val
msg = "Goodbye cruel world!"
scala> var greeting = "Hello, world!"
greeting: java.lang.String = Hello, world!
scala> greeting = "Leave me alone, world!"
greeting: java.lang.String = Leave me alone, world!
B:2.3 TI1220 - Introduction 48
49. Function Definition and Call
binding functions to names
scala> def max(x: Int, y: Int): Int = {
if (x > y) x
else y
}
max: (x: Int,y: Int)Int
scala> max(3, 5)
res2: Int = 5
scala> def max2(x: Int, y: Int) = if (x > y) x else y
max: (x: Int,y: Int)Int
B:2.3 TI1220 - Introduction 49
50. Unit
the type of side effects
scala> def greet() = println("Hello, world!")
greet: ()Unit
scala> greet()
Hello, world!
B:2.3 TI1220 - Introduction 50
56. Functional Style
Functional style
• functions are values
• operations map input values to output values
• instead of changing values in place (side effects)
A balanced attitude
• Prefer vals, immutable objects, and methods without side effects.
• Use vars, mutable objects, and methods with side effects when you have
a specific need and justification for them.
B:3.11 TI1220 - Introduction 56
57. $ scala linecounts.scala linecounts.scala
22 | import scala.io.Source
0 |
55 | def widthOfLength(s: String) = s.length.toString.length
0 |
22 | if (args.length > 0) {
54 | val lines = Source.fromFile(args(0)).getLines.toList
37 | val longestLine = lines.reduceLeft(
49 | (a, b) => if (a.length > b.length) a else b
3 | )
43 | val maxWidth = widthOfLength(longestLine)
23 | for (line <- lines) {
50 | val numSpaces = maxWidth - widthOfLength(line)
33 | val padding = " " * numSpaces
47 | println(padding + line.length +" | "+ line)
3 | }
1 | }
4 | else
46 | Console.err.println("Please enter filename")
B:3.12 TI1220 - Introduction 57
59. Width of Longest Line
charcounts
def widthOfLength(s: String) = s.length.toString.length
val lines = Source.fromFile(args(0)).getLines.toList
val longestLine = lines.reduceLeft(
(a, b) => if (a.length > b.length) a else b
)
val maxWidth = widthOfLength(longestLine)
B:3.12 TI1220 - Introduction 59
60. Print Lines with Length
charcounts
for (line <- lines) {
val numSpaces = maxWidth - widthOfLength(line)
val padding = " " * numSpaces
println(padding + line.length +" | "+ line)
}
B:3.12 TI1220 - Introduction 60
61. import scala.io.Source
def widthOfLength(s: String) = s.length.toString.length
if (args.length > 0) {
val lines = Source.fromFile(args(0)).getLines.toList
val longestLine = lines.reduceLeft(
(a, b) => if (a.length > b.length) a else b
)
val maxWidth = widthOfLength(longestLine)
for (line <- lines) {
val numSpaces = maxWidth - widthOfLength(line)
val padding = " " * numSpaces
println(padding + line.length +" | "+ line)
}
}
else
Console.err.println("Please enter filename")
B:3.12 TI1220 - Introduction 61
63. Class: Object Blueprint
declaration and instantiation
class ChecksumAccumulator {}
val acc = new ChecksumAccumulator
val csa = new ChecksumAccumulator
B:4.1 TI1220 - Introduction 63
64. Fields (Instance Variables)
object state
class ChecksumAccumulator {
var sum = 0
}
val acc = new ChecksumAccumulator
val csa = new ChecksumAccumulator
acc.sum = 3
B:4.1 TI1220 - Introduction 64
65. Reference vs Content
object state
class ChecksumAccumulator {
var sum = 0
}
val acc = new ChecksumAccumulator
val csa = new ChecksumAccumulator
acc.sum = 3
// Won’t compile, because acc is a val
acc = new ChecksumAccumulator
B:4.1 TI1220 - Introduction 65
66. Data Hiding
object state
class ChecksumAccumulator {
private var sum = 0
}
val acc = new ChecksumAccumulator
acc.sum = 5 // Won’t compile, because sum is private
B:4.1 TI1220 - Introduction 66
74. Summary
lessons learned
Programming languages are for people
• to reason about solutions for problems
Declaration and use
• binding values to names, referring to values using
names
Immutable values
• cannot be changed once created (no side effects)
Objects
• data structures with methods
B:2.3 TI1220 - Introduction 74
75. Exam Question
What happens when we execute the following code:
val greetStrings = new Array[String](3)
greetStrings(0) = "Hello"
greetStrings(1) = ", "
greetStrings(2) = "world!n"
(a) Error: greetStrings is an immutable variable that cannot
be assigned to
(b) Error: Array is a immutable data structure that cannot
be assigned to
(c) No error: greetStrings is a mutable variable that can be
assigned to
(d) No error: Array is a mutable data structure that can be
assigned to
B:2.3 TI1220 - Introduction 75
76. Exercises Week 1
getting started with Scala
Set up your Scala environment
• download and install Scala interpreter and compiler
Scala basics
• evaluating expressions
• defining functions
• running scripts
• making applications
• hand in on paper to student assistants!
B:2.3 TI1220 - Introduction 76
77. Literature
required reading
Programming in Scala
• Chapter 1: A Scalable Language
• Chapter 2: First Steps in Scala
• Chapter 3: Next Steps in Scala
• Chapter 4: Classes and Objects
• Chapter 5: Basic Types and Operations
TI1220 - Introduction 77
81. Pictures
copyrights
Slide 1:
Kinetica by Paul Downey, Some rights reserved
Slide 2:
McPhillips’ Map of the City of Winnipeg by Manitoba Historical Maps, some rights reserved
Slide 4:
The Blue Hour by Andreas Wonisch, Some rights reserved
Slide 5:
by Eelco Visser, Some rights reserved
Slide 8:
I’m listening by Melvin Gaal, some rights reserved
Slide 10:
Bombe detail by Garret Coakley, Some rights reserved
Slide 13:
Alan Turing by oalfonso, some rights reserved
Slide 14:
History of Programming Languages by O’Reilly
Slide:
ABZ-DNA by dulhunk, some rights reserved
Slide 32, 34:
Envelopes by benchilada, some rights reserved
Slide 33:
Report card by Carosaurus, some rights reserved
Slide 36:
paper coffee cup by Shutterstock, some rights reserved
B:2.3 TI1220 - Introduction 81
82. Pictures
copyrights
Slide 40:
Dinner at Roussillon (Martin Odersky) by Miles Sabin, some rights reserved
Slide 41:
Portrait: Alex Payne by Dave Fayram, some rights reserved
Slide 43:
“Plumbing Nightmare” by Natalie Wilkie, some rights reserved
Slide 72:
HIV: The Moleskine Summary by Niels Olson
Slide 75, 76:
remember to thank all the books you haven’t read over the past three years
by Natalia Osiatynska, Some rights reserved
Slide 7, 73:
Stupid Exam by Remi Carreiro, Some rights reserved
Slide 74:
Practice makes perfect by Simon Probert
Slide 10:
Bombe detail by Garret Coakley, Some rights reserved
Slide 29:
1.12.2011 <recipes> 362/365 by Phil Roeder, Some rights reserved
Slide 22,23:
China Tibet Himalaya by Bernhard Goldbach, Some rights reserved
Slide 17:
Thinking at Hell’s gate by innoxiuss, Some rights reserved
B:2.3 TI1220 - Introduction 82