n n Official Scala website n Scala API n

Size: px
Start display at page:

Download "n n Official Scala website n Scala API n"

Transcription

1 n Quiz 8 Announcements n Rainbow grades: HW1-8, Quiz1-6, Exam1-2 n Still grading: HW9, Quiz 7 Scala n HW10 due today n HW11 out today, due Friday Fall 18 CSCI 4430, A Milanova 1 Today s Lecture Outline n Scala: a functional and object-oriented programming language n Key ideas n : cons, map/reduce, immutable types n Scala is functional: anonymous functions, higherorder functions, call-by-name parameters n Scala is object-oriented: classes, singleton objects, case classes and pattern matching, traits and mixins n And much more 3 Scala Resources n n Official Scala website n index.html n Scala API n n Tutorial n Getting started: tutorial + slides Fall 18 CSCI 4430, A Milanova 4 Scala n General-purpose language n Multi-paradigm: focus is on functional and object-oriented programming n Designed by Martin Odersky at EPFL, first version around 2001 n Built on the Java Virtual Machine (JVM) n Used at Twitter, Linkedin, Spark big data Scala n Model for variables? n Reference model n Scoping discipline? n Static scoping n Typing discipline? n Static typing. Type annotations, some type inference n Subtype, and (explicit) parametric polymorphism n Parameter passing? n Mixed modes. Default by-value, allows by-name Fall 18 CSCI 4430/6430, A Milanova 5 Fall 18 CSCI 4430/6430, A Milanova 6 1

2 Getting Started n Download Scala n On Mac: brew install scala n Scala REPL: n $ scala n scala> val li = 1::Nil li: List[Int] = List(1) // interpreter response Compiling and running Scala n $ scalac Expressions.scala n $ scala Expressions 7 Defining Variables n vars can be reassigned scala> var x = 1 x: Int = 1 scala> x = 42 x: Int = 42 n vals cannot be reassigned scala> val y = 1 y: Int = 1 scala> y = 42 <console>:12: error: reassignment to val y = 42 8 Basic Control Structures n If-then-else scala> val n = 10 scala> if (n%2==0) print( even ) else print( odd ) scala> if (n%2==0) { print( even ) else { print( odd ) n While scala> var x = 0 scala> while (x < 10) { println(x); x = x+1; n In Scala, everything is an expression! scala> var a = while (x < 10) { println(x); x = x+1; a: Unit = () // essentially Java s void 9 n are important in Scala too! scala> var li = List(1,2,3) li: List[Int] = List(1, 2, 3) scala> var li2 = 1::2::3::Nil li2: List[Int] = List(1, 2, 3) n We can have elements of different types scala> var li3 = List(1,List(2),3) li3: List[Any] = List(1, List(2), 3) :: is Cons! n Any is the supertype of all Scala types Fall 18 CSCI 4430/6430, A Milanova 10 n Cons and append scala> val li1 = List(1,2) scala> val li2 = List(3,4) scala> li2::li3 // yields what? res0: List[Any] = List(List(1, 2), 3, 4) ::: is append! scala> val li2:::li3 res1: List[Int] = List(1, 2, 3, 4) Fall 18 CSCI 4430/6430, A Milanova 11 n map, foldleft, foldright, filter are built in n In Scala, everything is an object n map, foldleft, etc. are applied on list objects scala> li1 = List(1,2,3,4) def foldleft[b](z: B)(op: (B, A) B): B foldleft is a function applied on receiver List[A]. It takes z of type B, and a binary scala> li1.map(_+1) operation op; it returns result of type B. res5: List[Int] = List(2, 3, 4, 5) scala> li1.foldleft(0)(_+_) // same semantics as our foldl res6: Int = 10 scala> li1.foldright(0)(_-_) 12 res7: Int = -2 2

3 n are immutable! n Scala supports immutable types (, Strings) as a defense against call-by-sharing n Just as in Scheme, :: and ::: create new lists n Arrays are mutable scala> li1(3) = 5 error (..) is subscript scala> val a = Array(1,2,3,4) a: Array[Int] = Array(1, 2, 3, 4) scala> a(3) = 5 13 n List (sequence) comprehensions n In Scala, known as for comprehensions n for (seq) yield expression n seq includes generators, may include filters scala> def all_pairs(lis1:list[int], lis2:list[int]) = for (x<-lis1; y<-lis2) yield ((x,y)) all_pairs: (lis1: List[Int], lis2: List[Int])List[(Int, Int)] scala> all_pairs(list(1,2,3),list(6,5,4)) // yields what? res9: List[(Int, Int)] = List((1,6), (1,5), (1,4), (2,6), (2,5), (2,4), (3,6), (3,5), (3,4)) 14 and Streams Stream cons Lecture Outline n Scala streams are like lists, however, elements are computed lazily n Can create infinite lists such as [1..] in Haskell scala> def fun (n:int) : Stream[Int] = n #:: fun(n+1) fun: (n: Int)Stream[Int] // must specify return type Stream[Int] scala> fun(1).take(10) // yields what? scala> fun(1)(100) // yields what? res3: Int = 101 Compare to def fun2 (n:int) : List[Int] = n :: fun2(n+1) fun2(1) Fall 18 CSCI 4430/6430, A Milanova 15 n Scala: a functional and object-oriented programming language n Key ideas n : cons, map/reduce, immutable types n Scala is functional: anonymous functions, higherorder functions, call-by-name parameters n Scala is object-oriented: classes, singleton objects, case classes and pattern matching, traits and mixins Fall 18 CSCI 4430, A Milanova 16 Functions n Functions that are part of an object are called methods (more on classes, case classes and singleton objects later) object HelloWorld { def main(args: Array[String]) { println("hello, world!") n In Scala, functions, just like any other value, are objects Fall 18 CSCI 4430/6430, A Milanova 17 Nested Functions and Scoping var i = 1; var j = 3; middle and outer return 3-Int tuple def outer() : (Int,Int,Int) = { var i = 2; def middle(k:int) : (Int,Int,Int) = { def inner() { var i = 4; println(i); inner(); (i,j,k) // middle returns tuple middle(j) // outer returns tuple 18 println (outer()); println (i+","+j); 3

4 Defining Functions scala> def square(x:int) = x*x square: (x: Int)Int // Scala infers return type n Or scala> def square(x:int) = { x*x square: (x: Int)Int // Also, def square(x:int) : Int = x*x scala> square(5) res0: Int = 25 n But not scala> def square(x:int) { x*x square: (x: Int)Unit 19 Higher-order Functions n Of course, higher-order functions everywhere n Scala is a functional language scala> def plusone(x:int) = x+1 plusone: (x: Int)Int // Note that Scala infers return type scala> def apply_n[a](f:a=>a,n:int,x:a) : A = if (n==0) x else apply_n(f,n-1,f(x)) apply_n: [A](f: A => A, n: Int, x: A)A // Can t infer types! scala> apply_n(plusone,10,0) res10: Int = 10 A is a type parameter Fall 18 CSCI 4430/6430, A Milanova 20 Anonymous Functions n Functions are first-class values (objects) n Can be passed as arguments, returned, assigned scala> var lis = List(1,2,3,4) scala> lis.map((x:int) => x+1) // yields what? res3: List[Int] = List(2, 3, 4, 5) scala> val plusone = (x:int) => x+1 plusone: Int => Int = $$Lambda n Different from def: scala> def plusone(x:int) = x+1 plusone: (x: Int)Int 21 Type Inference n Scala does only simple type inference n No rule to say when it can infer, and when it can t scala> val plusone = x => x+1 <console>:11: error: missing parameter type n Have to type parameter scala> val plusone = (x:int) => x+1 n Scala can infer type if anonymous function immediately applied Fall 18 CSCI 4430/6430, A Milanova 22 Call-by-name Parameters HW10 Example (Attempt 1) n By default Scala uses call-by-value scala> def square(x:int) = x*x scala> square(1+2) 1+2 = 3 3*3 = 9 n Can specify call-by-name by using => scala> def square(x: =>Int) = x*x scala> square(1+2) (1+2)*(1+2) = 3*(1+2) 3* def compute(first : Int, last : Int, incr : Int, i : =>Int, term : =>Double) = { var result : Double = 0.0; i = first; while (i <= last) { result = result + term; i = i + incr; result Doesn t work! Parameters are val, i can t be reassigned Homework assumes value model (by-reference parameter passing) Scala uses reference model var i = 0; var a = Array(1,2,3); val s = compute(0,2,1,i,a(i)); 4

5 HW10 Example (Attempt 2) def compute(first:int, last:int, incr:int, j: Int=>Unit, term: =>Double) = { var result : Double = 0.0; var i : Int = first; while (i <= last) { result = result + term; // term evaluated in ref. env. of caller j(incr); // incements main s i i = i+incr; inc is a closure! result var i : Int = 0; var a = Array(1,2,3); def inc(incr:int) { i = i+incr; a(i) evaluated in caller ref. env. print(compute(0,2,1,inc _,a(i))); 25 Lecture Outline n Scala: a functional and object-oriented programming language n Key ideas n : cons, map/reduce, immutable types n Scala is functional: anonymous functions, higherorder functions, call-by-name parameters n Scala is object-oriented: classes, singleton objects, case classes and pattern matching, traits and mixins Fall 18 CSCI 4430, A Milanova 26 Objects n In Scala, everything is an object n Including functions and numbers! n Unlike Java, no distinction between primitive types (value model), and reference types n Numbers are objects scala> 1+2*3 n Or, we can use instance call syntax scala> (1).+((2).*(3)) // yields what? scala> (2::Nil).::(1) // yeilds what? Fall 18 CSCI 4430/6430, A Milanova 27 Objects n Functions are objects too n Means they are first-class values, can be passed, returned and assigned n Anonymous functions, curried functions, higherorder functions, etc. n Essential characteristic of Scala, renders Scala a functional language Fall 18 CSCI 4430/6430, A Milanova 28 Objects n Singleton objects have a single instance. In Java, we needed the Singleton pattern object HelloWorld { def main(args: Array[String]) { println("hello, world!") n Object declaration entails a singleton object n Above declares both a class and an object n No static methods/fields in Scala! Fall 18 CSCI 4430/6430, A Milanova 29 Classes n Scala is object-oriented (concept of class) class Complex(real: Double, imaginary: Double) { def re() = real // or we can write def re = real def im() = imaginary // def im = imaginary n Syntax is similar to Java n Can specify fields in header, real, imaginary n val c = new Complex(1.5, 2.3) n Can add override String tostring() = "" + re + (if (im < 0) "-" else "+") + im + "i" Fall /6430, A Milanova (based on scala-lang.org tutorial) 30 5

6 Case Classes n Class Tree represents ASTs of arithmetic expressions (e.g., x+x+(1+y)) abstract class Tree case class Sum(l: Tree, r: Tree) extends Tree case class Var(n: String) extends Tree case class Const(v: Int) extends Tree n Can be viewed as a classical OO hierarchy (subtype polymorphism, dynamic dispatch)! n Can be viewed as an Algebraic Data Type (as in Haskell, a tagged union of products)! Fall /6430, A Milanova (based on scala-lang.org tutorial) 31 Case Classes n Can write Const(5) instead of new Const(5) n Getter functions are automatically defined for the constructor parameters (e.g., can write c.v) n Default equals and hashcode provided; work on the structure of the instances, not on their identity n Default tostring provided; prints the value in a source form (e.g., the tree for expression x+1 prints as Sum(Var(x),Const(1))) n Instances of these classes can be decomposed through pattern matching Fall 18 CSCI 4430/6430, A Milanova (based on scala-lang.org tutorial) 32 Pattern Matching n We already know what this is! def eval(t: Tree, env: Environment): Int = t match { case Sum(l, r) => eval(l, env) + eval(r, env) case Var(n) => env(n) case Const(v) => v n Just as in Haskell n Test: does value t match pattern (e.g., Sum) n Binding: if yes, then bind components to corresponding variables (e.g., l an r) Fall /6430, A Milanova (based on scala-lang.org tutorial) 33 Pattern Matching n What design patterns jump to mind? n Patterns for traversal of composite structures n Classical GoF Interpreter pattern n GoF Interpreter defined eval methods per node n Easy to add new node, difficult to add new operation n Pattern matching n Easy to add new operation, difficult to add new class/node n In that sense, similar to Procedural/Visitor 34 HW11 Traits In Scala, == goes to equals, i.e., value equality! n Traversal of composite expressions n A-a-again n This time in Scala n One problem: traversal using pattern matching over a hierarchy of case classes n Another problem: Visitor-like traversals using a higher-order method Fall 18 CSCI 4430/6430, A Milanova 35 n A class can mix in code from one or more traits trait Ord { def < (that: Any): Boolean def <=(that: Any): Boolean = (this < that) (this == that) def > (that: Any): Boolean =!(this <= that) def >=(that: Any): Boolean =!(this < that) n Similar to the Java interface, but can have code n Above example creates a new type Ord n In example <=, >, >= are defined in terms of < Fall 18 CSCI 4430/6430, A Milanova (example from scala-lang.org tutorial) 36 6

7 Date extends Ord n A class can mix in code from one or more traits class Date(y: Int, m: Int, d: Int) extends Ord { def year = y def month = m def day = d override def tostring(): String = year + "-" + month + "-" + day n In Scala, override annotation is mandatory when overriding a concrete method Fall 18 CSCI 4430/6430, A Milanova (example from scala-lang.org tutorial) 37 Date extends Ord override def equals(that: Any): Boolean = that.isinstanceof[date] && { val o = that.asinstanceof[date] o.day == day && o.month == month && o.year == year def <(that: Any): Boolean = { if (!that.isinstanceof[date]) sys.error("cannot compare " + that + " and a Date ) val o = that.asinstanceof[date] (year < o.year) (year == o.year && (month < o.month (month == o.month && day < o.day))) Fall 18 CSCI 4430/6430, A Milanova (example from scala-lang.org tutorial) 38 Traits and Mixins abstract class AbsIterator { type T def hasnext: Boolean def next(): T class StringIterator(s: String) extends AbsIterator { type T = Char private var i = 0 def hasnext = i < s.length // must implement member def next() = { // must implement member val ch = s charat i i += 1 ch 39 Traits and Mixins trait RichIterator extends AbsIterator { def foreach(f: T => Unit): Unit = while (hasnext) f(next()) class RichStringIterator extends StringIterator with RichIterator {... n Can mix-in functionality from different traits n class D extends A with B with C { n As in Java, one extends multiple with (implements) n More flexible (and more complex) than Java n Trait can extend an abstract class n There may be conflicting trait members Fall 18 CSCI 4430/6430, A Milanova 40 7

n n Try tutorial on front page to get started! n spring13/ n Stack Overflow!

n   n Try tutorial on front page to get started! n   spring13/ n Stack Overflow! Announcements n Rainbow grades: HW1-6, Quiz1-5, Exam1 n Still grading: HW7, Quiz6, Exam2 Intro to Haskell n HW8 due today n HW9, Haskell, out tonight, due Nov. 16 th n Individual assignment n Start early!

More information

A Scala Tutorial for Java programmers

A Scala Tutorial for Java programmers A Scala Tutorial for Java programmers Version 1.2 January 13, 2009 Michel Schinz, Philipp Haller PROGRAMMING METHODS LABORATORY EPFL SWITZERLAND 2 1 Introduction This document gives a quick introduction

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Week 13 - Part 1 Thomas Wies New York University Review Last lecture Object Oriented Programming Outline Today: Scala Sources: Programming in Scala, Second

More information

Bibliography. Analyse et Conception Formelle. Lesson 5. Crash Course on Scala. Scala in a nutshell. Outline

Bibliography. Analyse et Conception Formelle. Lesson 5. Crash Course on Scala. Scala in a nutshell. Outline Bibliography Analyse et Conception Formelle Lesson 5 Crash Course on Scala Simply Scala. Onlinetutorial: http://www.simply.com/fr http://www.simply.com/ Programming in Scala, M. Odersky, L. Spoon, B. Venners.

More information

Announcements. CSCI 334: Principles of Programming Languages. Lecture 16: Intro to Scala. Announcements. Squeak demo. Instructor: Dan Barowy

Announcements. CSCI 334: Principles of Programming Languages. Lecture 16: Intro to Scala. Announcements. Squeak demo. Instructor: Dan Barowy Announcements CSCI 334: Principles of Programming Languages Lecture 16: Intro to Scala HW7 sent out as promised. See course webpage. Instructor: Dan Barowy Announcements No class on Tuesday, April 17.

More information

CSCI-GA Scripting Languages

CSCI-GA Scripting Languages CSCI-GA.3033.003 Scripting Languages 12/02/2013 OCaml 1 Acknowledgement The material on these slides is based on notes provided by Dexter Kozen. 2 About OCaml A functional programming language All computation

More information

Overview. Elements of Programming Languages. Advanced constructs. Motivating inner class example

Overview. Elements of Programming Languages. Advanced constructs. Motivating inner class example Overview Elements of Programming Languages Lecture 11: Object-oriented functional programming James Cheney University of Edinburgh October 30, 2017 We ve now covered: basics of functional programming (with

More information

Topic VIII. The state of the art Scala < > Scala By Example by M. Odersky. Programming Methods Laboratory, EPFL, 2008.

Topic VIII. The state of the art Scala <  > Scala By Example by M. Odersky. Programming Methods Laboratory, EPFL, 2008. References: Topic VIII The state of the art Scala < www.scala-lang.org > Scala By Example by M. Odersky. Programming Methods Laboratory, EPFL, 2008. An overview of the Scala programming language by M.

More information

CSE6331: Cloud Computing

CSE6331: Cloud Computing CSE6331: Cloud Computing Leonidas Fegaras University of Texas at Arlington c 2018 by Leonidas Fegaras Apache Spark Based on: Shannon Quinn slides at http://cobweb.cs.uga.edu/~squinn/mmd_s15/lectures/lecture13_mar3.pdf

More information

Notes from a Short Introductory Lecture on Scala (Based on Programming in Scala, 2nd Ed.)

Notes from a Short Introductory Lecture on Scala (Based on Programming in Scala, 2nd Ed.) Notes from a Short Introductory Lecture on Scala (Based on Programming in Scala, 2nd Ed.) David Haraburda January 30, 2013 1 Introduction Scala is a multi-paradigm language that runs on the JVM (is totally

More information

Programming in Scala Second Edition

Programming in Scala Second Edition Programming in Scala Second Edition Martin Odersky, Lex Spoon, Bill Venners artima ARTIMA PRESS WALNUT CREEK, CALIFORNIA Contents Contents List of Figures List of Tables List of Listings Foreword Foreword

More information

CS162 Week 1. Kyle Dewey. Friday, January 10, 14

CS162 Week 1. Kyle Dewey. Friday, January 10, 14 CS162 Week 1 Kyle Dewey Overview Basic Introduction CS Accounts Scala survival guide Office Hour Choose an hour from within: Tuesday/Thursday 11 AM - 1 PM Friday 11 AM - 4 PM Also available by appointment

More information

Classical Themes of Computer Science

Classical Themes of Computer Science Functional Programming (Part 1/2) Bernhard K. Aichernig Institute for Software Technology Graz University of Technology Austria Winter Term 2017/18 Version: November 22, 2017 1/49 Agenda I Functional Programming?

More information

Using Scala in CS241

Using Scala in CS241 Using Scala in CS241 Winter 2018 Contents 1 Purpose 1 2 Scala 1 3 Basic Syntax 2 4 Tuples, Arrays, Lists and Vectors in Scala 3 5 Binary output in Scala 5 6 Maps 5 7 Option types 5 8 Objects and Classes

More information

CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures

CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures Dan Grossman Fall 2014 Hi! I m not Hal J I love this stuff and have taught

More information

...something useful to do with the JVM.

...something useful to do with the JVM. Scala Finally... ...something useful to do with the JVM. Image source: http://www.tripadvisor.com/locationphotos-g187789-lazio.html Young Developed in 2003 by Martin Odersky at EPFL Martin also brought

More information

CS 2340 Objects and Design - Scala

CS 2340 Objects and Design - Scala CS 2340 Objects and Design - Scala Objects and Operators Christopher Simpkins chris.simpkins@gatech.edu Chris Simpkins (Georgia Tech) CS 2340 Objects and Design - Scala Objects and Operators 1 / 13 Classes

More information

Scala : an LLVM-targeted Scala compiler

Scala : an LLVM-targeted Scala compiler Scala : an LLVM-targeted Scala compiler Da Liu, UNI: dl2997 Contents 1 Background 1 2 Introduction 1 3 Project Design 1 4 Language Prototype Features 2 4.1 Language Features........................................

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Fall 2016 Lecture 6a Andrew Tolmach Portland State University 1994-2016 Functional Programming An alternative paradigm to imperative programming First-class functions Emphasis

More information

CPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia

CPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia CPL 2016, week 10 Clojure functional core Oleg Batrashev Institute of Computer Science, Tartu, Estonia April 11, 2016 Overview Today Clojure language core Next weeks Immutable data structures Clojure simple

More information

Lecture 15 CIS 341: COMPILERS

Lecture 15 CIS 341: COMPILERS Lecture 15 CIS 341: COMPILERS Announcements HW4: OAT v. 1.0 Parsing & basic code generation Due: March 28 th No lecture on Thursday, March 22 Dr. Z will be away Zdancewic CIS 341: Compilers 2 Adding Integers

More information

CS205: Scalable Software Systems

CS205: Scalable Software Systems CS205: Scalable Software Systems Lecture 4 September 14, 2016 Lecture 4 CS205: Scalable Software Systems September 14, 2016 1 / 16 Quick Recap Things covered so far Problem solving by recursive decomposition

More information

n Closed book n You are allowed 5 cheat pages n Practice problems available in Course Materials n Check grades in Rainbow grades

n Closed book n You are allowed 5 cheat pages n Practice problems available in Course Materials n Check grades in Rainbow grades Announcements Announcements n HW12: Transaction server n Due today at 2pm n You can use up to 2 late days, as always n Final Exam, December 17, 3-6pm, in DCC 308 and 318 n Closed book n You are allowed

More information

Programs as Data. The Scala language

Programs as Data. The Scala language Programs as Data The Scala language Peter Sestoft 2011-11-14 1 Agenda Kursusevaluering slutter i dag! Object-oriented programming in Scala Classes Singletons (object) Traits Compiling and running Scala

More information

INTRODUCTION. SHORT INTRODUCTION TO SCALA INGEGNERIA DEL SOFTWARE Università degli Studi di Padova

INTRODUCTION. SHORT INTRODUCTION TO SCALA INGEGNERIA DEL SOFTWARE Università degli Studi di Padova SHORT INTRODUCTION TO SCALA INGEGNERIA DEL SOFTWARE Università degli Studi di Padova Dipartimento di Matematica Corso di Laurea in Informatica, A.A. 2014 2015 rcardin@math.unipd.it INTRODUCTION Object/functional

More information

CSE341: Programming Languages Lecture 17 Implementing Languages Including Closures. Dan Grossman Autumn 2018

CSE341: Programming Languages Lecture 17 Implementing Languages Including Closures. Dan Grossman Autumn 2018 CSE341: Programming Languages Lecture 17 Implementing Languages Including Closures Dan Grossman Autumn 2018 Typical workflow concrete syntax (string) "(fn x => x + x) 4" Parsing Possible errors / warnings

More information

Scala. Fernando Medeiros Tomás Paim

Scala. Fernando Medeiros Tomás Paim Scala Fernando Medeiros fernfreire@gmail.com Tomás Paim tomasbmp@gmail.com Topics A Scalable Language Classes and Objects Basic Types Functions and Closures Composition and Inheritance Scala s Hierarchy

More information

Axiomatic Rules. Lecture 18: Axiomatic Semantics & Type Safety. Correctness using Axioms & Rules. Axiomatic Rules. Steps in Proof

Axiomatic Rules. Lecture 18: Axiomatic Semantics & Type Safety. Correctness using Axioms & Rules. Axiomatic Rules. Steps in Proof Lecture 18: Axiomatic Semantics & Type Safety CSCI 131 Fall, 2011 Kim Bruce Axiomatic Rules Assignment axiom: - {P [expression / id]} id := expression {P} - Ex: {a+47 > 0} x := a+47 {x > 0} - {x > 1} x

More information

Programming Paradigms, Fall 06

Programming Paradigms, Fall 06 Programming Paradigms, Fall 06 Multiple Choice Exam January 29, 2007, 10:00 11:15 ID Name Each of the following questions has exactly one correct answer. For each question, you may select one or more answers

More information

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml COSE212: Programming Languages Lecture 3 Functional Programming in OCaml Hakjoo Oh 2017 Fall Hakjoo Oh COSE212 2017 Fall, Lecture 3 September 18, 2017 1 / 44 Why learn ML? Learning ML is a good way of

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Lecture 3 Thomas Wies New York University Review Last week Names and Bindings Lifetimes and Allocation Garbage Collection Scope Outline Control Flow Sequencing

More information

Scala, Your Next Programming Language

Scala, Your Next Programming Language Scala, Your Next Programming Language (or if it is good enough for Twitter, it is good enough for me) WORLDCOMP 2011 By Dr. Mark C. Lewis Trinity University Disclaimer I am writing a Scala textbook that

More information

CompSci 220. Programming Methodology 12: Functional Data Structures

CompSci 220. Programming Methodology 12: Functional Data Structures CompSci 220 Programming Methodology 12: Functional Data Structures A Polymorphic Higher- Order Function def findfirst[a](as: Array[A], p: A => Boolean): Int = { def loop(n: Int): Int = if (n >= as.length)

More information

Introduction to Functional Programming in Haskell 1 / 56

Introduction to Functional Programming in Haskell 1 / 56 Introduction to Functional Programming in Haskell 1 / 56 Outline Why learn functional programming? The essence of functional programming What is a function? Equational reasoning First-order vs. higher-order

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Winter 2017 Lecture 7b Andrew Tolmach Portland State University 1994-2017 Values and Types We divide the universe of values according to types A type is a set of values and

More information

CSCI-GA Final Exam

CSCI-GA Final Exam CSCI-GA 2110-003 - Final Exam Instructor: Thomas Wies Name: Sample Solution ID: You have 110 minutes time. There are 7 assignments and you can reach 110 points in total. You can solve the exercises directly

More information

Types and Programming Languages. Lecture 5. Extensions of simple types

Types and Programming Languages. Lecture 5. Extensions of simple types Types and Programming Languages Lecture 5. Extensions of simple types Xiaojuan Cai cxj@sjtu.edu.cn BASICS Lab, Shanghai Jiao Tong University Fall, 2016 Coming soon Simply typed λ-calculus has enough structure

More information

Project 2: Scheme Interpreter

Project 2: Scheme Interpreter Project 2: Scheme Interpreter CSC 4101, Fall 2017 Due: 12 November 2017 For this project, you will implement a simple Scheme interpreter in C++ or Java. Your interpreter should be able to handle the same

More information

Lecture 8: Summary of Haskell course + Type Level Programming

Lecture 8: Summary of Haskell course + Type Level Programming Lecture 8: Summary of Haskell course + Type Level Programming Søren Haagerup Department of Mathematics and Computer Science University of Southern Denmark, Odense October 31, 2017 Principles from Haskell

More information

The type checker will complain that the two branches have different types, one is string and the other is int

The type checker will complain that the two branches have different types, one is string and the other is int 1 Intro to ML 1.1 Basic types Need ; after expression - 42 = ; val it = 42 : int - 7+1; val it = 8 : int Can reference it - it+2; val it = 10 : int - if it > 100 then "big" else "small"; val it = "small"

More information

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,

More information

Homework 7. What To Turn In. Reading. Self Check. Handout 18 CSCI 334: Spring, 2017

Homework 7. What To Turn In. Reading. Self Check. Handout 18 CSCI 334: Spring, 2017 Homework 7 Due 18 April Handout 18 CSCI 334: Spring, 2017 What To Turn In Please hand in work in two pieces, one for the Problems and one for the Pair Programming: Problems: Turn in handwritten or typed

More information

Elements of Programming Languages Assignment 1: Introduction to Scala September 27, 2017

Elements of Programming Languages Assignment 1: Introduction to Scala September 27, 2017 Elements of Programming Languages Assignment 1: Introduction to Scala September 27, 2017 This laboratory session is intended to introduce you to the basic features of Scala, focusing primarily on the pure,

More information

The Typed Racket Guide

The Typed Racket Guide The Typed Racket Guide Version 5.3.6 Sam Tobin-Hochstadt and Vincent St-Amour August 9, 2013 Typed Racket is a family of languages, each of which enforce

More information

Introduction to Typed Racket. The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples

Introduction to Typed Racket. The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples Introduction to Typed Racket The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples Getting started Find a machine with DrRacket installed (e.g. the

More information

Recap: Functions as first-class values

Recap: Functions as first-class values Recap: Functions as first-class values Arguments, return values, bindings What are the benefits? Parameterized, similar functions (e.g. Testers) Creating, (Returning) Functions Iterator, Accumul, Reuse

More information

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Winter 2013

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Winter 2013 CSE341: Programming Languages Lecture 9 Function-Closure Idioms Dan Grossman Winter 2013 More idioms We know the rule for lexical scope and function closures Now what is it good for A partial but wide-ranging

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Fall 2017 Lecture 7b Andrew Tolmach Portland State University 1994-2017 Type Inference Some statically typed languages, like ML (and to a lesser extent Scala), offer alternative

More information

The SCAlable LAnguage

The SCAlable LAnguage The SCAlable LAnguage The Scala Language: Object Oriented Functional Programming Gabor Szokoli Overview Introduction Everything is an Object Inheritance and mixins For comprehensions Generic Types: Covariance,

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Java Object Oriented Design. CSC207 Fall 2014

Java Object Oriented Design. CSC207 Fall 2014 Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code

More information

JVM ByteCode Interpreter

JVM ByteCode Interpreter JVM ByteCode Interpreter written in Haskell (In under 1000 Lines of Code) By Louis Jenkins Presentation Schedule ( 15 Minutes) Discuss and Run the Virtual Machine first

More information

CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 17: Types and Type-Checking 25 Feb 08

CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 17: Types and Type-Checking 25 Feb 08 CS412/CS413 Introduction to Compilers Tim Teitelbaum Lecture 17: Types and Type-Checking 25 Feb 08 CS 412/413 Spring 2008 Introduction to Compilers 1 What Are Types? Types describe the values possibly

More information

CSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341)

CSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341) CSE 413 Languages & Implementation Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341) 1 Goals Representing programs as data Racket structs as a better way to represent

More information

Exercise 1: Graph coloring (10 points)

Exercise 1: Graph coloring (10 points) Exercise 1: Graph coloring (10 points) Graph coloring is the problem of assigning colors to vertices in a non-directed graph, so that no two adjacent nodes have the same color. In other words, if two vertices

More information

An introduction to C++ template programming

An introduction to C++ template programming An introduction to C++ template programming Hayo Thielecke University of Birmingham http://www.cs.bham.ac.uk/~hxt March 2015 Templates and parametric polymorphism Template parameters Member functions of

More information

Practically Functional. Daniel Spiewak

Practically Functional. Daniel Spiewak Practically Functional Daniel Spiewak whoami Author of Scala for Java Refugees and other articles on Scala and FP Former editor Javalobby / EclipseZone Engaged in academic research involving Scala DSLs

More information

Introduction to ML. Based on materials by Vitaly Shmatikov. General-purpose, non-c-like, non-oo language. Related languages: Haskell, Ocaml, F#,

Introduction to ML. Based on materials by Vitaly Shmatikov. General-purpose, non-c-like, non-oo language. Related languages: Haskell, Ocaml, F#, Introduction to ML Based on materials by Vitaly Shmatikov slide 1 ML General-purpose, non-c-like, non-oo language Related languages: Haskell, Ocaml, F#, Combination of Lisp and Algol-like features (1958)

More information

Typical workflow. CSE341: Programming Languages. Lecture 17 Implementing Languages Including Closures. Reality more complicated

Typical workflow. CSE341: Programming Languages. Lecture 17 Implementing Languages Including Closures. Reality more complicated Typical workflow concrete synta (string) "(fn => + ) 4" Parsing CSE341: Programming Languages abstract synta (tree) Lecture 17 Implementing Languages Including Closures Function Constant + 4 Var Var Type

More information

Generating Continuation Passing Style Code for the Co-op Language

Generating Continuation Passing Style Code for the Co-op Language Generating Continuation Passing Style Code for the Co-op Language Mark Laarakkers University of Twente Faculty: Computer Science Chair: Software engineering Graduation committee: dr.ing. C.M. Bockisch

More information

Optimizing Higher-Order Functions in Scala

Optimizing Higher-Order Functions in Scala Optimizing Higher-Order Functions in Scala Iulian Dragos EPFL Outline A quick tour of Scala Generalities Extension through libraries Closure translation in Scala Cost Optimizations in the Scala compiler

More information

CSE 130, Fall 2006: Final Examination

CSE 130, Fall 2006: Final Examination CSE 130, Fall 2006: Final Examination Name: ID: Instructions, etc. 1. Write your answers in the space provided. 2. Wherever it says explain, write no more than three lines as explanation. The rest will

More information

CS Programming Languages: Scala

CS Programming Languages: Scala CS 3101-2 - Programming Languages: Scala Lecture 3: Fun with Functions Daniel Bauer (bauer@cs.columbia.edu) October 29, 2014 Daniel Bauer CS3101-2 Scala - 03 - Fun with Functions 1/37 Contents 1 Defining

More information

Static type safety guarantees for the operators of a relational database querying system. Cédric Lavanchy

Static type safety guarantees for the operators of a relational database querying system. Cédric Lavanchy Static type safety guarantees for the operators of a relational database querying system Cédric Lavanchy June 6, 2008 Contents 1 Previous work 2 2 Goal 3 3 Theory bases 4 3.1 Typing a relation...........................

More information

Kotlin, Start? Start! (pluu) Android Developer GDG Korea Android Organizer

Kotlin, Start? Start! (pluu) Android Developer GDG Korea Android Organizer Kotlin, Start? Start! (pluu) Android Developer GDG Korea Android Organizer Agenda Kotlin Overview Kotlin?? Basic fun main(args: Array): Unit { println("hello, world!") Basic Function Keyword

More information

Advances in Programming Languages

Advances in Programming Languages T O Y H Advances in Programming Languages APL8: Multiparameter Type Classes, Constructor Classes Ian Stark School of Informatics The University of Edinburgh Thursday 4 February Semester 2 Week 4 E H U

More information

Lecture #23: Conversion and Type Inference

Lecture #23: Conversion and Type Inference Lecture #23: Conversion and Type Inference Administrivia. Due date for Project #2 moved to midnight tonight. Midterm mean 20, median 21 (my expectation: 17.5). Last modified: Fri Oct 20 10:46:40 2006 CS164:

More information

Lecture 09: Introduction to Scala

Lecture 09: Introduction to Scala Lecture 09: Introduction to Scala Computer Science Department, University of Crete Multicore Processor Programming Based on slides by D. Malayeri, S.D. Vick, P. Haller, and M. Madsen Pratikakis (CSD) Scala

More information

Overview. Elements of Programming Languages. Objects. Self-Reference

Overview. Elements of Programming Languages. Objects. Self-Reference Overview Elements of Programming Languages Lecture 10: James Cheney University of Edinburgh October 23, 2017 Last time: programming in the large Programs, packages/namespaces, importing Modules and interfaces

More information

Conversion vs. Subtyping. Lecture #23: Conversion and Type Inference. Integer Conversions. Conversions: Implicit vs. Explicit. Object x = "Hello";

Conversion vs. Subtyping. Lecture #23: Conversion and Type Inference. Integer Conversions. Conversions: Implicit vs. Explicit. Object x = Hello; Lecture #23: Conversion and Type Inference Administrivia. Due date for Project #2 moved to midnight tonight. Midterm mean 20, median 21 (my expectation: 17.5). In Java, this is legal: Object x = "Hello";

More information

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen COP4020 Programming Languages Functional Programming Prof. Robert van Engelen Overview What is functional programming? Historical origins of functional programming Functional programming today Concepts

More information

# true;; - : bool = true. # false;; - : bool = false 9/10/ // = {s (5, "hi", 3.2), c 4, a 1, b 5} 9/10/2017 4

# true;; - : bool = true. # false;; - : bool = false 9/10/ // = {s (5, hi, 3.2), c 4, a 1, b 5} 9/10/2017 4 Booleans (aka Truth Values) Programming Languages and Compilers (CS 421) Sasa Misailovic 4110 SC, UIUC https://courses.engr.illinois.edu/cs421/fa2017/cs421a # true;; - : bool = true # false;; - : bool

More information

Object-oriented programming

Object-oriented programming Object-oriented programming HelloWorld The following code print Hello World on the console object HelloWorld { def main(args: Array[String]): Unit = { println("hello World") 2 1 object The keyword object

More information

Concepts of Programming Languages

Concepts of Programming Languages Concepts of Programming Languages Lecture 15 - Functional Programming Patrick Donnelly Montana State University Spring 2014 Patrick Donnelly (Montana State University) Concepts of Programming Languages

More information

Programming Kotlin. Familiarize yourself with all of Kotlin s features with this in-depth guide. Stephen Samuel Stefan Bocutiu BIRMINGHAM - MUMBAI

Programming Kotlin. Familiarize yourself with all of Kotlin s features with this in-depth guide. Stephen Samuel Stefan Bocutiu BIRMINGHAM - MUMBAI Programming Kotlin Familiarize yourself with all of Kotlin s features with this in-depth guide Stephen Samuel Stefan Bocutiu BIRMINGHAM - MUMBAI Programming Kotlin Copyright 2017 Packt Publishing First

More information

Compilers and computer architecture: Semantic analysis

Compilers and computer architecture: Semantic analysis 1 / 1 Compilers and computer architecture: Semantic analysis Martin Berger Alex Jeffery October 2018 Recall the function of compilers 2 / 1 3 / 1 Recall the structure of compilers Source program Lexical

More information

Delite. Hassan Chafi, Arvind Sujeeth, Kevin Brown, HyoukJoong Lee, Kunle Olukotun Stanford University. Tiark Rompf, Martin Odersky EPFL

Delite. Hassan Chafi, Arvind Sujeeth, Kevin Brown, HyoukJoong Lee, Kunle Olukotun Stanford University. Tiark Rompf, Martin Odersky EPFL Delite Hassan Chafi, Arvind Sujeeth, Kevin Brown, HyoukJoong Lee, Kunle Olukotun Stanford University Tiark Rompf, Martin Odersky EPFL Administrative PS 1 due today Email to me PS 2 out soon Build a simple

More information

G Programming Languages Spring 2010 Lecture 6. Robert Grimm, New York University

G Programming Languages Spring 2010 Lecture 6. Robert Grimm, New York University G22.2110-001 Programming Languages Spring 2010 Lecture 6 Robert Grimm, New York University 1 Review Last week Function Languages Lambda Calculus SCHEME review 2 Outline Promises, promises, promises Types,

More information

Values (a.k.a. data) representation. Advanced Compiler Construction Michel Schinz

Values (a.k.a. data) representation. Advanced Compiler Construction Michel Schinz Values (a.k.a. data) representation Advanced Compiler Construction Michel Schinz 2016 03 10 The problem Values representation A compiler must have a way of representing the values of the source language

More information

Values (a.k.a. data) representation. The problem. Values representation. The problem. Advanced Compiler Construction Michel Schinz

Values (a.k.a. data) representation. The problem. Values representation. The problem. Advanced Compiler Construction Michel Schinz Values (a.k.a. data) representation The problem Advanced Compiler Construction Michel Schinz 2016 03 10 1 2 Values representation The problem A compiler must have a way of representing the values of the

More information

Ruby: Introduction, Basics

Ruby: Introduction, Basics Ruby: Introduction, Basics Computer Science and Engineering College of Engineering The Ohio State University Lecture 3 Ruby vs Java: Similarities Imperative and object-oriented Classes and instances (ie

More information

CMSC 330: Organization of Programming Languages. Closures (Implementing Higher Order Functions)

CMSC 330: Organization of Programming Languages. Closures (Implementing Higher Order Functions) CMSC 330: Organization of Programming Languages Closures (Implementing Higher Order Functions) CMSC 330 - Summer 2017 1 Returning Functions as Results In OCaml you can pass functions as arguments to map,

More information

Overloading, Type Classes, and Algebraic Datatypes

Overloading, Type Classes, and Algebraic Datatypes Overloading, Type Classes, and Algebraic Datatypes Delivered by Michael Pellauer Arvind Computer Science and Artificial Intelligence Laboratory M.I.T. September 28, 2006 September 28, 2006 http://www.csg.csail.mit.edu/6.827

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Winter 2018 Lecture 7b Andrew Tolmach Portland State University 1994-2018 Dynamic Type Checking Static type checking offers the great advantage of catching errors early And

More information

Functions, Closures and Control Abstraction

Functions, Closures and Control Abstraction Functions, Closures and Control Abstraction Christopher Simpkins csimpkin@spsu.edu CS 3693, Fall 2011 Chris Simpkins (Georgia Tech) CS 3693 Scala 2011-09-07 1 / 1 Aside: drop and take (Optional) homework:

More information

Functional programming

Functional programming Functional programming Functional programming In functional programming, functions are the core building blocks In pure functional programming, functions are like mathematical functions Mathematical functions

More information

Introduction to OCaml

Introduction to OCaml Fall 2018 Introduction to OCaml Yu Zhang Course web site: http://staff.ustc.edu.cn/~yuzhang/tpl References Learn X in Y Minutes Ocaml Real World OCaml Cornell CS 3110 Spring 2018 Data Structures and Functional

More information

Featherweight Scala. Week 14

Featherweight Scala. Week 14 Featherweight Scala Week 14 1 Today Previously: Featherweight Java Today: Featherweight Scala Live research, unlike what you have seen so far. Focus today on path-dependent types Plan: 1. Rationale 2.

More information

First Programming Language in CS Education The Arguments for Scala

First Programming Language in CS Education The Arguments for Scala First Programming Language in CS Education The Arguments for Scala WORLDCOMP 2011 By Dr. Mark C. Lewis Trinity University Disclaimer I am writing a Scala textbook that is under contract with CRC Press.

More information

Functional Programming

Functional Programming Functional Programming Final Exam Friday, December 18 2015 First Name: Last Name: Your points are precious, don t let them go to waste! Your Name Work that can t be attributed to you is lost: write your

More information

Advanced Object-Oriented Languages Scala

Advanced Object-Oriented Languages Scala Advanced Object-Oriented Languages Scala Programming Paradigms Department of Computer Science University of Aalborg, Denmark Erik Ernst (U. of Aarhus) Overview Purpose of using Scala Introduction syntax

More information

Scope. Chapter Ten Modern Programming Languages 1

Scope. Chapter Ten Modern Programming Languages 1 Scope Chapter Ten Modern Programming Languages 1 Reusing Names Scope is trivial if you have a unique name for everything: fun square a = a * a; fun double b = b + b; But in modern languages, we often use

More information

User-Defined Algebraic Data Types

User-Defined Algebraic Data Types 72 Static Semantics User-Defined Types User-Defined Algebraic Data Types An algebraic data type declaration has the general form: data cx T α 1... α k = K 1 τ 11... τ 1k1... K n τ n1... τ nkn introduces

More information

According to Larry Wall (designer of PERL): a language by geniuses! for geniuses. Lecture 7: Haskell. Haskell 98. Haskell (cont) - Type-safe!

According to Larry Wall (designer of PERL): a language by geniuses! for geniuses. Lecture 7: Haskell. Haskell 98. Haskell (cont) - Type-safe! Lecture 7: Haskell CSC 131 Fall, 2014 Kim Bruce According to Larry Wall (designer of PERL): a language by geniuses for geniuses He s wrong at least about the latter part though you might agree when we

More information

Scala Style Guide Spring 2018

Scala Style Guide Spring 2018 CS18 Integrated Introduction to Computer Science Fisler, Nelson Scala Style Guide Spring 2018 Contents 1 Introduction 1 2 Naming 1 3 Formatting 2 4 Class Declarations 3 5 Functional Paradigms 4 6 Comments

More information

Introducing Scala-like function types into Java-TX

Introducing Scala-like function types into Java-TX Introducing Scala-like function types into Java-TX ManLang 2017 Martin Plümicke Andreas Stadelmeier www.dhbw-stuttgart.de/horb Overview 1 Type of lambda expressions in Java-8 2 Introducing real function

More information

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix PGJC4_JSE8_OCA.book Page ix Monday, June 20, 2016 2:31 PM Contents Figures Tables Examples Foreword Preface xix xxi xxiii xxvii xxix 1 Basics of Java Programming 1 1.1 Introduction 2 1.2 Classes 2 Declaring

More information

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline CS 0 Lecture 8 Chapter 5 Louden Outline The symbol table Static scoping vs dynamic scoping Symbol table Dictionary associates names to attributes In general: hash tables, tree and lists (assignment ) can

More information

CSE 413 Spring Introduction to Ruby. Credit: Dan Grossman, CSE341

CSE 413 Spring Introduction to Ruby. Credit: Dan Grossman, CSE341 CSE 413 Spring 2011 Introduction to Ruby Credit: Dan Grossman, CSE341 Why? Because: Pure object-oriented language Interesting, not entirely obvious implications Interesting design decisions Type system,

More information

An Overview of Scala. Philipp Haller, EPFL. (Lots of things taken from Martin Odersky's Scala talks)

An Overview of Scala. Philipp Haller, EPFL. (Lots of things taken from Martin Odersky's Scala talks) An Overview of Scala Philipp Haller, EPFL (Lots of things taken from Martin Odersky's Scala talks) The Scala Programming Language Unifies functional and object-oriented programming concepts Enables embedding

More information