Concepts of ProgrammingLanguagesEelco Visser         Delft                                                           TI122...
Overviewtoday’s lectureA new course•   from IN1605-B to TI1220What is this course about?•   why study concepts of programm...
IA New Course               TI 1220 - Lecture 1: Introduction   3
A New Coursethe only constant is changeIN1605-B: Algoritmen en Programmeertalen:Programmeertalen•   4 ECTS•   Haskell + C•...
Under New ManagementEelco VisserLecturer•   Dr. Eelco Visser•   UHD in Software Engineering Research Group•   http://eelco...
My Researchsoftware language design & engineeringSpoofax Language Workbench•   design and implement languages & IDEs•   fr...
Examination Old CourseYou can still sit for exams of IN1605-B•   Provided you have finished the lab (practicum)Sittings•  ...
Feedback AppreciatedAn invitation to Murphy•   New content•   New software•   New lectures, assignments, exams•   New lect...
IIConcepts of Programming Languages                      TI 1220 - Lecture 1: Introduction   9
Computers Process Datadata       computer         data                               TI1220 - Introduction 10
Programmable Computersdata       computer         data           program                               TI1220 - Introducti...
Programming Languagedata       computer       data              L           program                             TI1220 - I...
Turing MachinescomputabilityTuring/Church Thesis•   Every effective computation can be carried out by a    Turing machine*...
History of Programming Languages         timelineHistory of Programming Languages  1954                         1960      ...
Programming Languages in TITI1200: Object-Oriented Programming•   JavaTI1400: Computer Systems•   AssemblyTI1500: Web- and...
“A programming language is low level when itsprograms require attention to the irrelevant”  Alan J. Perlis. Epigrams on Pr...
Understanding Computationpurpose of programming languagesEncoding computation•   Computer needs list of instructions to mo...
Increasing the Level of Abstractionconcepts of programming languagescalc: push eBP                                   ; sav...
Programming Modelsconcepts of programming languagesLanguage provides model of computation•   data & operations, compositio...
Programming Language DNAconcepts of programming languagesScope and binding•   declaration and binding of names, free and b...
Why Study Concepts?concepts of programming languagesDesign abstractions for new domains•   from library to language featur...
Goals of this Courseconcepts of programming languages•   Understand programming languages and programs in    terms of conc...
Approachconcepts of programming languagesStudy three concrete languages•   Scala + C + JavaScript•   Learn to program in t...
Scalafunctional programming•   Lecture 1: Getting Started with Scala•   Lecture 2: Functional Objects•   Lecture 3: Functi...
Csystems programming•   Lecture 8: Memory Management    •   stack vs heap    •   pointers•   Lecture 9: Implementing Objec...
JavaScriptweb programmingPrototype-Based Object-Oriented Language•   Lecture 10: Prototypal Inheritance    •   History: Sm...
Meta-Programmingimplementation of programming languagesOther courses consider internals of languages•   IN2505: Fundamenta...
IIICourse Organization                      TI 1220 - Lecture 1: Introduction 28
Ingredientscourse organizationThis is a semester course•   Q3 + Q4Lectures•   Tuesday morningPracticum•   on Tuesday or Th...
Examscourse organizationExam 1•   Monday 11 April, 2011, 9:00-12:00•   E1: about material of Q3 (Scala)Exam 2•   Wednesday...
Examscourse organizationExam 3 (resit)•   If Exam 2 < 6, even if Exam 1 >= 6•   Wednesday, 24 August, 2011, 9:00-12:00•   ...
Practicumcourse organizationScala (Q3)•   Exercises: hand in on paper to assistants at end of lab!•   Assignment 1 (graded...
Final Gradecourse organizationval H = all exercises handed inval A = 0.4*A1 + 0.3*A2 + 0.3*A3val E2 = if(E1 >= 6) (E1 + E2...
Practicum Groupscourse organizationTuesday: Group 1•   mentor groups 1 to 6Thursday: Group 2•   mentor groups 7 to 12     ...
Practicum Assistantscourse organization      Tuesday             Thursday  Maartje de Jonge   Sander van der Burg Laurent ...
coffee break               TI1220 - Introduction 36
IVThe Scala Programming Language                           Term Rewriting 37
Programming Language Schoolsimperative vs functional programmingImperative Programming (Algol, C, Pascal)•   programming w...
PizzahistoryPOPL 1997                             Philip Wadler, Martin Odersky, Gilad Bracha, Dave Stoutamire (source: ht...
ScalahistoryA Scalable Language•   object-oriented + functional programmingProperties•   compatible (combines with Java)• ...
Scala in IndustryhistoryScala at Twitter•   Ruby-on-Rails did not scale•   Replaced back-end processing (API) with ScalaBa...
Programming in ScalaBookProgramming in ScalaA comprehensive step-by-step guideby Martin Odersky, Lex Spoon, and Bill Venne...
Installing ScalaDownload Interpreter & Compiler•   Make your own installation (assignment 1)•   http://www.scala-lang.org/...
The Scala Interpreter$ scalaWelcome to Scala version 2.8.0.final (Java HotSpot(TM)64-Bit Server VM, Java 1.6.0_22).Type in...
VVariables and Functions            B:2           Term Rewriting 45
Evaluating Expressionsrepl: read, eval, print loopscala> 1 + 2res0: Int = 3scala> res0 * 3res1: Int = 9scala> println("Hel...
Variable Declaration and Usebinding values to namesscala> val msg = "Hello, world!"msg: java.lang.String = Hello, world!sc...
Immutable and Mutable Variableschanging value bound to namescala> msg = "Goodbye cruel world!"<console>:6: error: reassign...
Function Definition and Callbinding functions to namesscala> def max(x: Int, y: Int): Int = {         if (x > y) x        ...
Unitthe type of side effectsscala> def greet() = println("Hello, world!")greet: ()Unitscala> greet()Hello, world!         ...
Scala Scripts//file: hello.scalaprintln("Hello, world, from a script!")$ scala hello.scalaHello, world, from a script!    ...
Scala Scriptswith arguments//file: helloarg.scala// Say hello to the first argumentprintln("Hello, "+ args(0) +"!")$ scala...
Control-Flowimperative style// file: printargs.scalavar i = 0while (i < args.length) {  if (i != 0)    print(" ")  print(a...
Control-Flowfunctional style// file: printargsfun.scalaargs.foreach(arg => println(arg))$ scala printargsfun.scala first c...
Control-Flowfunctional stylefor (arg <- args)  println(arg)                    B:2.5   TI1220 - Introduction 55
Functional StyleFunctional style•   functions are values•   operations map input values to output values    •   instead of...
$ scala linecounts.scala linecounts.scala22 | import scala.io.Source 0 |55 | def widthOfLength(s: String) = s.length.toStr...
Print Linescharcountsimport scala.io.Sourceif (args.length > 0) {  for (line <- Source.fromFile(args(0)).getLines)    prin...
Width of Longest Linecharcountsdef widthOfLength(s: String) = s.length.toString.lengthval lines = Source.fromFile(args(0))...
Print Lines with Lengthcharcountsfor (line <- lines) {  val numSpaces = maxWidth - widthOfLength(line)    val padding = " ...
import scala.io.Sourcedef widthOfLength(s: String) = s.length.toString.lengthif (args.length > 0) {  val lines = Source.fr...
VIClasses and Objects           B:2.3      Term Rewriting 62
Class: Object Blueprintdeclaration and instantiationclass ChecksumAccumulator {}val acc = new ChecksumAccumulatorval csa =...
Fields (Instance Variables)object stateclass ChecksumAccumulator {  var sum = 0}val acc = new ChecksumAccumulatorval csa =...
Reference vs Contentobject stateclass ChecksumAccumulator {  var sum = 0}val acc = new ChecksumAccumulatorval csa = new Ch...
Data Hidingobject stateclass ChecksumAccumulator {  private var sum = 0}val acc = new ChecksumAccumulatoracc.sum = 5 // Wo...
Methodsobject behaviorclass ChecksumAccumulator {  private var sum = 0  def add(b: Byte): Unit = {    sum += b  }  def che...
Methodsparameters are valsdef add(b: Byte): Unit = {  b = 1 // This won’t compile, because b is a val  sum += b}          ...
Methodssugar// file: ChecksumAccumulator.scalaclass ChecksumAccumulator {  private var sum = 0  def add(b: Byte) { sum += ...
Singleton Objectsdefining ‘static’ methodsimport scala.collection.mutable.Mapobject ChecksumAccumulator {  private val cac...
Using Singleton Objectsmethods and stateChecksumAccumulator.calculate("Every value is an object.")                 B:4.3  ...
Scala Application// file: Summer.scalaimport ChecksumAccumulator.calculateobject Summer {  def main(args: Array[String]) {...
VIISummary          Term Rewriting 73
Summarylessons learnedProgramming languages are for people•   to reason about solutions for problemsDeclaration and use•  ...
Exam QuestionWhat happens when we execute the following code:val greetStrings = new Array[String](3)greetStrings(0) = "Hel...
Exercises Week 1getting started with ScalaSet up your Scala environment•   download and install Scala interpreter and comp...
Literaturerequired readingProgramming in Scala•   Chapter 1: A Scalable Language•   Chapter 2: First Steps in Scala•   Cha...
Literaturehttp://researchr.org/bibliography/ti1220                                       TI1220 - Introduction 78
Outlookcoming nextFunctional programming•   Lecture 2: Functional Objects    •   Chapters 6, 7•   Lecture 3: Functions & C...
IXNotes        Term Rewriting 80
PicturescopyrightsSlide 1:   Kinetica by Paul Downey, Some rights reservedSlide 2:   McPhillips’ Map of the City of Winnip...
PicturescopyrightsSlide 40:    Dinner at Roussillon (Martin Odersky) by Miles Sabin, some rights reservedSlide 41:    Port...
Upcoming SlideShare
Loading in...5
×

Ti1220 Lecture 1

1,254

Published on

Introduction lecture to course on concepts of programming languages at Delft University of Technology

Published in: Education
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,254
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
33
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Ti1220 Lecture 1

  1. 1. Concepts of ProgrammingLanguagesEelco Visser Delft TI1220 University of Technology Concepts of Programming Languages Challenge the future
  2. 2. Overviewtoday’s lectureA new course• from IN1605-B to TI1220What is this course about?• why study concepts of programming languages?How is this course organized?• lectures and assignmentsIntroduction to Scala• writing and running Scala programs TI1220 - Introduction 2
  3. 3. IA New Course TI 1220 - Lecture 1: Introduction 3
  4. 4. A New Coursethe only constant is changeIN1605-B: Algoritmen en Programmeertalen:Programmeertalen• 4 ECTS• Haskell + C• Peter KluijtTI1220: Concepten van Programmeertalen• 6 ECTS• Scala + C + JavaScript• Eelco Visser TI1220 - Introduction 4
  5. 5. Under New ManagementEelco VisserLecturer• 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. 6. My Researchsoftware language design & engineeringSpoofax Language Workbench• design and implement languages & IDEs• from high-level declarative specificationDomain-specific language design• WebDSL: a DSL for web programming• Mobl: a DSL for mobile web applicationsInteraction design• researchr.org: building a digital library TI1220 - Introduction 6
  7. 7. Examination Old CourseYou 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. 8. Feedback AppreciatedAn 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
  9. 9. IIConcepts of Programming Languages TI 1220 - Lecture 1: Introduction 9
  10. 10. Computers Process Datadata computer data TI1220 - Introduction 10
  11. 11. Programmable Computersdata computer data program TI1220 - Introduction 11
  12. 12. Programming Languagedata computer data L program TI1220 - Introduction 12
  13. 13. Turing MachinescomputabilityTuring/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
  14. 14. History of Programming Languages timelineHistory of Programming Languages 1954 1960 1965 1970 1975 1980 1985 1990 1995 2000 2001 2002 2003 2004 1986 1990 1990 1991 1991 1993 1994 1995 1996 1996 1997 1997 2000 2001 2001 2003 2003 2004 For more than half of the fifty years computer programmers have been This timeline includes fifty of the more than 2500 documented writing code, O’Reilly has provided developers with comprehensive, programming languages. It is based on an original diagram createdwww.oreilly.com in-depth technical information. We’ve kept pace with rapidly changing by Éric Lévénez (www.levenez.com), augmented with suggestions technologies as new languages have emerged, developed, and from O’Reilly authors, friends, and conference attendees. matured. Whether you want to learn something new or need For information and discussion on this poster, answers to tough technical questions, you’ll find what you need go to www.oreilly.com/go/languageposter. in O’Reilly books and on the O’Reilly Network. ©2004 O’Reilly Media, Inc. O’Reilly logo is a registered trademark of O’Reilly Media, Inc. All other trademarks are property of their respective owners. part#30417 This timeline includes 50 of the more than 2500 documented programming languages. TI1220 - Introduction 14
  15. 15. Programming Languages in TITI1200: Object-Oriented Programming• JavaTI1400: Computer Systems• AssemblyTI1500: Web- and Database Technology• HTML, PHP, SQL, JavaScriptTI1600: Multi-Agent Systems• Prolog, GOAL TI1220 - Introduction 15
  16. 16. “A programming language is low level when itsprograms require attention to the irrelevant” Alan J. Perlis. Epigrams on Programming. SIGPLAN Notices, 17(9):7-13, 1982. TI1220 - Introduction 16
  17. 17. Understanding Computationpurpose of programming languagesEncoding computation• Computer needs list of instructions to move its partsUnderstanding computation• Discuss concepts• Formulate algorithms• Reason about problem solutionsProgramming languages are for people TI1220 - Introduction 17
  18. 18. Increasing the Level of Abstractionconcepts of programming languagescalc: 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 returnpush eAX ; pass some register resultpush byte[eBP+20] ; pass some memory variable (FASM/TASM syntax)push 3 ; pass some constantcall calc ; the returned result is now in eAXhttp://en.wikipedia.org/wiki/Calling_conventiondef f(x)={ ... } f(e1) TI1220 - Introduction 18
  19. 19. Programming Modelsconcepts of programming languagesLanguage provides model of computation• data & operations, composition & abstractionLanguage targets application domain• Systems programming• Embedded systems• Web programming• Enterprise software TI1220 - Introduction 19
  20. 20. Programming Language DNAconcepts of programming languagesScope and binding• declaration and binding of names, free and bound occurrences, renaming, substitutionData structures• product and sum types, records, recursive typesModularization and data abstraction• modules, classes, higher-order functions, class-based vs prototype inheritanceSyntax and interpretation TI1220 - Introduction 20
  21. 21. Why Study Concepts?concepts of programming languagesDesign 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 futureChoosing the right language TI1220 - Introduction 21
  22. 22. Goals of this Courseconcepts 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. 23. Approachconcepts of programming languagesStudy three concrete languages• Scala + C + JavaScript• Learn to program in these languages• Learn concepts by using them in programming• Programming assignments about languagesGeneralize• What are the underlying ideas?• Learn to learn new languages TI1220 - Introduction 23
  24. 24. Scalafunctional 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. 25. Csystems 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. 26. JavaScriptweb programmingPrototype-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. 27. Meta-Programmingimplementation of programming languagesOther 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
  28. 28. IIICourse Organization TI 1220 - Lecture 1: Introduction 28
  29. 29. Ingredientscourse organizationThis is a semester course• Q3 + Q4Lectures• Tuesday morningPracticum• on Tuesday or Thursday afternoon• Exercises + Graded AssignmentsExams TI1220 - Introduction 29
  30. 30. Examscourse organizationExam 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. 31. Examscourse organizationExam 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. 32. Practicumcourse organizationScala (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. 33. Final Gradecourse organizationval H = all exercises handed inval A = 0.4*A1 + 0.3*A2 + 0.3*A3val E2 = if(E1 >= 6) (E1 + E2a)/2 else E2bval E = if(E2 >= 6) E2 else E3val G = if(H && Ai >= 6 && E >= 6) 0.4*A + 0.6E else min(E, 5) TI1220 - Introduction 33
  34. 34. Practicum Groupscourse organizationTuesday: Group 1• mentor groups 1 to 6Thursday: Group 2• mentor groups 7 to 12 TI1220 - Introduction 34
  35. 35. Practicum Assistantscourse organization Tuesday Thursday Maartje de Jonge Sander van der Burg Laurent Verweijen Bart van Vuuren Vlad Vergu Peter Pul Joost Heijkoop TI1220 - Introduction 35
  36. 36. coffee break TI1220 - Introduction 36
  37. 37. IVThe Scala Programming Language Term Rewriting 37
  38. 38. Programming Language Schoolsimperative vs functional programmingImperative Programming (Algol, C, Pascal)• programming with side effects• structured control-flowObject-Oriented Programming (C++, Java)• imperative programming with data abstractionFunctional Programming (ML, Haskell)• functions as first-class citizens• immutable data (pure) TI1220 - Introduction 38
  39. 39. PizzahistoryPOPL 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. 40. ScalahistoryA Scalable Language• object-oriented + functional programmingProperties• compatible (combines with Java)• concise (sugar + abstractions)• high-level• statically typedDesigned by Martin Odersky et al. at EPFL TI1220 - Introduction 40
  41. 41. Scala in IndustryhistoryScala at Twitter• Ruby-on-Rails did not scale• Replaced back-end processing (API) with ScalaBankSimple• Back-end services in Scala or ClojureAlex Payne• Programming Scala by Wampler & Payne TI1220 - Introduction 41
  42. 42. Programming in ScalaBookProgramming in ScalaA comprehensive step-by-step guideby Martin Odersky, Lex Spoon, and Bill Vennershttp://www.artima.com/shop/programming_in_scalaAvailable as e-book (PDF)Lectures are based on book; not everything in book is on slides; readingbook is required; see Literature slides at end of each lecture for requiredreading! TI1220 - Introduction 42
  43. 43. Installing ScalaDownload Interpreter & Compiler• Make your own installation (assignment 1)• http://www.scala-lang.org/downloadsEditors• Emacs, Vi, <your favorite editor>Integrated Development Environments• Plugins for Eclipse, IntelliJ, NetBeans B:2.1 TI1220 - Introduction 43
  44. 44. The Scala Interpreter$ scalaWelcome 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
  45. 45. VVariables and Functions B:2 Term Rewriting 45
  46. 46. Evaluating Expressionsrepl: read, eval, print loopscala> 1 + 2res0: Int = 3scala> res0 * 3res1: Int = 9scala> println("Hello, world!")Hello, world! B:2.1 TI1220 - Introduction 46
  47. 47. Variable Declaration and Usebinding values to namesscala> 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. 48. Immutable and Mutable Variableschanging value bound to namescala> 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. 49. Function Definition and Callbinding functions to namesscala> def max(x: Int, y: Int): Int = { if (x > y) x else y }max: (x: Int,y: Int)Intscala> max(3, 5)res2: Int = 5scala> def max2(x: Int, y: Int) = if (x > y) x else ymax: (x: Int,y: Int)Int B:2.3 TI1220 - Introduction 49
  50. 50. Unitthe type of side effectsscala> def greet() = println("Hello, world!")greet: ()Unitscala> greet()Hello, world! B:2.3 TI1220 - Introduction 50
  51. 51. Scala Scripts//file: hello.scalaprintln("Hello, world, from a script!")$ scala hello.scalaHello, world, from a script! B:2.4 TI1220 - Introduction 51
  52. 52. Scala Scriptswith arguments//file: helloarg.scala// Say hello to the first argumentprintln("Hello, "+ args(0) +"!")$ scala helloarg.scala delftHello, delft! B:2.4 TI1220 - Introduction 52
  53. 53. Control-Flowimperative style// file: printargs.scalavar i = 0while (i < args.length) { if (i != 0) print(" ") print(args(i)) i += 1}println()$ scala printargs.scala imperative styleimperative style B:2.5 TI1220 - Introduction 53
  54. 54. Control-Flowfunctional style// file: printargsfun.scalaargs.foreach(arg => println(arg))$ scala printargsfun.scala first class functionsfirstclassfunctions B:2.5 TI1220 - Introduction 54
  55. 55. Control-Flowfunctional stylefor (arg <- args) println(arg) B:2.5 TI1220 - Introduction 55
  56. 56. Functional StyleFunctional 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. 57. $ scala linecounts.scala linecounts.scala22 | 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.toList37 | 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 = " " * numSpaces47 | println(padding + line.length +" | "+ line) 3 | } 1 | } 4 | else46 | Console.err.println("Please enter filename") B:3.12 TI1220 - Introduction 57
  58. 58. Print Linescharcountsimport scala.io.Sourceif (args.length > 0) { for (line <- Source.fromFile(args(0)).getLines) println(line.length + " | " + line)} else Console.err.println("Please enter filename") $ scala countchars1.scala countchars1.scala 22 | import scala.io.Source 22 | if (args.length > 0) { 49 | for (line <- Source.fromFile(args(0)).getLines) 37 | println(line.length + " " + line) 6 | } else 46 | Console.err.println("Please enter filename") B:2.3 TI1220 - Introduction 58
  59. 59. Width of Longest Linecharcountsdef widthOfLength(s: String) = s.length.toString.lengthval lines = Source.fromFile(args(0)).getLines.toListval longestLine = lines.reduceLeft( (a, b) => if (a.length > b.length) a else b)val maxWidth = widthOfLength(longestLine) B:3.12 TI1220 - Introduction 59
  60. 60. Print Lines with Lengthcharcountsfor (line <- lines) { val numSpaces = maxWidth - widthOfLength(line) val padding = " " * numSpaces println(padding + line.length +" | "+ line)} B:3.12 TI1220 - Introduction 60
  61. 61. import scala.io.Sourcedef widthOfLength(s: String) = s.length.toString.lengthif (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
  62. 62. VIClasses and Objects B:2.3 Term Rewriting 62
  63. 63. Class: Object Blueprintdeclaration and instantiationclass ChecksumAccumulator {}val acc = new ChecksumAccumulatorval csa = new ChecksumAccumulator B:4.1 TI1220 - Introduction 63
  64. 64. Fields (Instance Variables)object stateclass ChecksumAccumulator { var sum = 0}val acc = new ChecksumAccumulatorval csa = new ChecksumAccumulatoracc.sum = 3 B:4.1 TI1220 - Introduction 64
  65. 65. Reference vs Contentobject stateclass ChecksumAccumulator { var sum = 0}val acc = new ChecksumAccumulatorval csa = new ChecksumAccumulatoracc.sum = 3// Won’t compile, because acc is a valacc = new ChecksumAccumulator B:4.1 TI1220 - Introduction 65
  66. 66. Data Hidingobject stateclass ChecksumAccumulator { private var sum = 0}val acc = new ChecksumAccumulatoracc.sum = 5 // Won’t compile, because sum is private B:4.1 TI1220 - Introduction 66
  67. 67. Methodsobject behaviorclass ChecksumAccumulator { private var sum = 0 def add(b: Byte): Unit = { sum += b } def checksum(): Int = { return ~(sum & 0xFF) + 1 }} B:4.1 TI1220 - Introduction 67
  68. 68. Methodsparameters are valsdef add(b: Byte): Unit = { b = 1 // This won’t compile, because b is a val sum += b} B:4.1 TI1220 - Introduction 68
  69. 69. Methodssugar// file: ChecksumAccumulator.scalaclass ChecksumAccumulator { private var sum = 0 def add(b: Byte) { sum += b } def checksum(): Int = ~(sum & 0xFF) + 1} B:4.1 TI1220 - Introduction 69
  70. 70. Singleton Objectsdefining ‘static’ methodsimport scala.collection.mutable.Mapobject ChecksumAccumulator { private val cache = Map[String, Int]() def calculate(s: String): Int = if (cache.contains(s)) cache(s) else { val acc = new ChecksumAccumulator for (c <- s) acc.add(c.toByte) val cs = acc.checksum() cache += (s -> cs) cs }} B:4.3 TI1220 - Introduction 70
  71. 71. Using Singleton Objectsmethods and stateChecksumAccumulator.calculate("Every value is an object.") B:4.3 TI1220 - Introduction 71
  72. 72. Scala Application// file: Summer.scalaimport ChecksumAccumulator.calculateobject Summer { def main(args: Array[String]) { for (arg <- args) println(arg + ": " + calculate(arg)) }}$ scalac ChecksumAccumulator.scala Summer.scala$ scala Summer of loveof: -213love: -182 B:4.4 TI1220 - Introduction 72
  73. 73. VIISummary Term Rewriting 73
  74. 74. Summarylessons learnedProgramming languages are for people• to reason about solutions for problemsDeclaration and use• binding values to names, referring to values using namesImmutable values• cannot be changed once created (no side effects)Objects• data structures with methods B:2.3 TI1220 - Introduction 74
  75. 75. Exam QuestionWhat 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. 76. Exercises Week 1getting started with ScalaSet up your Scala environment• download and install Scala interpreter and compilerScala basics• evaluating expressions• defining functions• running scripts• making applications• hand in on paper to student assistants! B:2.3 TI1220 - Introduction 76
  77. 77. Literaturerequired readingProgramming 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
  78. 78. Literaturehttp://researchr.org/bibliography/ti1220 TI1220 - Introduction 78
  79. 79. Outlookcoming nextFunctional programming• Lecture 2: Functional Objects • Chapters 6, 7• Lecture 3: Functions & Closures • Chapters 8, 9• Lecture 4: List Programming • Chapters 15, 16, 17Lab Week 1• Getting started with Scala B:2.3 TI1220 - Introduction 79
  80. 80. IXNotes Term Rewriting 80
  81. 81. PicturescopyrightsSlide 1: Kinetica by Paul Downey, Some rights reservedSlide 2: McPhillips’ Map of the City of Winnipeg by Manitoba Historical Maps, some rights reservedSlide 4: The Blue Hour by Andreas Wonisch, Some rights reservedSlide 5: by Eelco Visser, Some rights reservedSlide 8: I’m listening by Melvin Gaal, some rights reservedSlide 10: Bombe detail by Garret Coakley, Some rights reservedSlide 13: Alan Turing by oalfonso, some rights reservedSlide 14: History of Programming Languages by O’ReillySlide: ABZ-DNA by dulhunk, some rights reservedSlide 32, 34: Envelopes by benchilada, some rights reservedSlide 33: Report card by Carosaurus, some rights reservedSlide 36: paper coffee cup by Shutterstock, some rights reserved B:2.3 TI1220 - Introduction 81
  82. 82. PicturescopyrightsSlide 40: Dinner at Roussillon (Martin Odersky) by Miles Sabin, some rights reservedSlide 41: Portrait: Alex Payne by Dave Fayram, some rights reservedSlide 43: “Plumbing Nightmare” by Natalie Wilkie, some rights reservedSlide 72: HIV: The Moleskine Summary by Niels OlsonSlide 75, 76: remember to thank all the books you haven’t read over the past three years by Natalia Osiatynska, Some rights reservedSlide 7, 73: Stupid Exam by Remi Carreiro, Some rights reservedSlide 74: Practice makes perfect by Simon ProbertSlide 10: Bombe detail by Garret Coakley, Some rights reservedSlide 29: 1.12.2011 <recipes> 362/365 by Phil Roeder, Some rights reservedSlide 22,23: China Tibet Himalaya by Bernhard Goldbach, Some rights reservedSlide 17: Thinking at Hell’s gate by innoxiuss, Some rights reserved B:2.3 TI1220 - Introduction 82
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×