The SCAlable LAnguage

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

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

Optimizing Higher-Order Functions in Scala

CS Programming Languages: Scala

CS 2340 Objects and Design - Scala

Advanced Object-Oriented Languages Scala

Lecture 09: Introduction to Scala

n n Official Scala website n Scala API n

Arne Brüsch Philipp Wille. Pattern Matching Syntax

Introduction to Scala

Copyright 2018 Tendril, Inc. All rights reserved.

CSCI-GA Final Exam

Life in a Post-Functional World

Scala Style Guide Spring 2018

Programming in Scala. DRAFT September 23, Martin Odersky PROGRAMMING METHODS LABORATORY EPFL SWITZERLAND

Scala. Fernando Medeiros Tomás Paim

CSE 130, Fall 2006: Final Examination

CompSci 220. Programming Methodology 12: Functional Data Structures

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

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

G Programming Languages - Fall 2012

Programs as Data. The Scala language

Software Engineering: Design & Construction

Programming in Scala Second Edition

Imperative Programming 2: Traits

Exercise 8 Parametric polymorphism November 18, 2016

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

Compiling Generics Through User-Directed Type Specialization

Lecture 21: The Many Hats of Scala: OOP 10:00 AM, Mar 14, 2018

Overview. Elements of Programming Languages. Records. Named variants. Last time: Simple data structures: pairing (product types), choice (sum types)

Linked lists and the List class

Scala - Some essential concepts -

Collections and Combinatorial Search

SCALA ARRAYS. Following picture represents array mylist. Here, mylist holds ten double values and the indices are from 0 to 9.

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

An Overview of the Scala Programming Language

G Programming Languages - Fall 2012

15 Multiple Inheritance and Traits

CSE 331 Summer 2017 Final Exam. The exam is closed book and closed electronics. One page of notes is allowed.

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

An Overview of the Scala Programming Language

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

The Kotlin Programming Language. Andrey Breslav Dmitry Jemerov

Functions and Objects. Week 7: Symbolic Computation

Exercise 6 Multiple Inheritance, Multiple Dispatch and Linearization November 4, 2016

Using Scala in CS241

Programming in Scala. DRAFT May 21, Martin Odersky PROGRAMMING METHODS LABORATORY EPFL SWITZERLAND

Featherweight Scala. Week 14

CSE Lecture 7: Polymorphism and generics 16 September Nate Nystrom UTA

Improving Scala's Safe Type-Level Abstraction

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

Exercise 6 Multiple Inheritance, Multiple Dispatch and Linearization November 3, 2017

Parallel Programming Concepts. Actors and Channels. Dr. Peter Tröger M.Sc. Frank Feinbube

Programming Languages

Adding support for CLR Generics

...something useful to do with the JVM.

Control Structures. Christopher Simpkins CS 3693, Fall Chris Simpkins (Georgia Tech) CS 3693 Scala / 1

Introduction to Functional Programming in Haskell 1 / 56

Exercise 6 Multiple Inheritance, Multiple Dispatch and Linearization November 3, 2017

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

Overview. Declarative Languages D7012E. Overloading. Overloading Polymorphism Subtyping

Code Listings. Inheritance APPENDIX A. Subtype Inheritance in Java

Type-indexed functions in Generic Haskell

Last name:... First name:... Department (if not D-INFK):...

Last name:... First name:... Department (if not D-INFK):...

Company Predecessor Domain Concepts

Dependent Object Types - A foundation for Scala's type system

Handout 2 August 25, 2008

CS205: Scalable Software Systems

CS205: Scalable Software Systems

Opaque types. Understanding SIP-35. Erik nescala

Official Survey. Cunning Plan: Focus On Objects. The Need for a Calculus. Object Calculi Summary. Why Not Use λ-calculus for OO?

CompSci 220. Programming Methodology 16: Understanding FP Error Handling Part 2

Recap from last time. Programming Languages. CSE 130 : Fall Lecture 3: Data Types. Put it together: a filter function

COMPUTER SCIENCE TRIPOS

Scala : an LLVM-targeted Scala compiler

Standard ML. Data types. ML Datatypes.1

JAVA MOCK TEST JAVA MOCK TEST III

What is Inheritance?

First Programming Language in CS Education The Arguments for Scala

Implementing a Universe Type System for Scala. Manfred Stock

21 Subtyping and Parameterized Types

CSCI-GA Scripting Languages

Programming Languages Lecture 15: Recursive Types & Subtyping

Exercises on ML. Programming Languages. Chanseok Oh

CSE341 Spring 2016, Final Examination June 6, 2016

CSci 4223 Lecture 12 March 4, 2013 Topics: Lexical scope, dynamic scope, closures

CS-202 Introduction to Object Oriented Programming

Programming Paradigms, Fall 06

Lecture 8: Summary of Haskell course + Type Level Programming

Programming in Scala Mixin inheritance Summer 2008

an overview Alceste Scalas Programming languages reading group

Implementing Higher-Level Languages. Quick tour of programming language implementation techniques. From the Java level to the C level.

Object Oriented Issues in VDM++

Implementing Method Type Specialisation In Dotty

CS61B Lecture #9: Abstract Classes and All That

Object-oriented programming

CS61B Lecture #9: Interfaces and Abstract Classes

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Dependent Object Types - A foundation for Scala s type system

Transcription:

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, contravariance type bounds. Java interoperability

Fast facts about Scala Pure Object Oriented Every value is an object Ultimate supertype: Any Ultimate subtype: All Functional Functions are values, thus objects Simple core language, rich library extensions Plus all Java libraries via JVM bytecode compatibility

It's just like Java def sort(xs: Array[int]): unit = { def swap(i: int, j: int): unit = { val t = xs(i); xs(i) = xs(j); xs(j) = t; def sort1(l: int, r: int): unit = { val pivot = xs((l + r) / 2); var i = l, j = r; while (i <= j) { while (xs(i) < pivot) { i = i + 1 while (xs(j) > pivot) { j = j 1 if (xs(i) <= xs(j)) {swap(i, j); i = i + 1; j = j 1; if (l < j) sort1(l, j); if (j < r) sort1(i, r); sort1(0, xs.length 1);

It's just like SML def sort(xs: List[int]): List[int] = if (xs.length <= 1) xs else { val pivot = xs(xs.length / 2); sort(xs.filter(x => x < pivot)) ::: xs.filter(x => x == pivot) ::: sort(xs.filter(x => x > pivot))

Everything is an Object Even Java value types Even functions Even case patterns It is just hidden behind strange syntax: foo.bar(value) shortened: foo bar value foo.bar:(value) is value bar: foo

The functional example again: def sort(xs: List[int]): List[int] = if (xs.length.<=(1)) xs else { val pivot = xs(xs.length./(2)); sort(xs.filter(x => x.<(pivot))) ::: xs.filter(x => x.==(pivot)) ::: sort(xs.filter(x => x.>(pivot)))

Functions are Objects, too xs.filter(x => x < pivot) Is equivalent to: val compare = new Function1[boolean,int] { def apply(x: int,): int = x < pivot xs.filter(compare) Where Function1 is a library interface: trait Function1[ a,+b] { def apply(x: a): b

Patterns are case class constructors Consider a reimplementation of the List class for ints: trait IntList; case class Nil extends IntList; case class Cons(head: int, tail: IntList) extends IntList; val primes:intlist = Cons(13,Cons(7,Cons(11,Nil()))) def sum(l: IntList): int = l match { case Nil => 0 case Cons(head, tail) => head + sum(tail)

Inheritance and Mixins Java has single full inheritance and multiple interface-inheritance. Scala has single full inheritance and allows multiple mixins: class Thing(x:int,y:int)extends AnyRef{ override def tostring()= ( +x+ : +y+ ) class Point extends Thing{ def distance(that: Point)=... class PositionedIntList extends IntList with Thing

For comprehensions Scala has the traditional functional container interface: persons.filter(p=>p.age>20).map(p=>p.name) But also provides an interesting wrapper syntax for it: for (val p< persons; p.age>20) yield p.name It gets more interesting on more complicated examples: for (val i < List.range(1, n) val j < List.range(1, i); isprime(i+j)) yield Pair(i, j) Relies only on filter, map, flatmap support in the containers: range(1, n).flatmap(i => range(1, i).filter(j => isprime(i+j)).map(j => (i, j)))

Generic Types Abstracting the IntList example over element type: trait GenList[T]; case class Nil[T] extends GenList[T]; case class Cons[T](head: T, tail: GenList[T]) extends GenList[t]; val primes:genlist[int]=cons(13,cons(7,cons(11,nil()))) val objects:genlist[any]=cons(13,cons( seven Nil())) But this does not work yet: val lists:genlist[genlist[any]]=cons(primes,nil()) type mismatch; found : GenList[scala.Int] required: GenList[scala.Any] val lists:genlist[genlist[any]]=cons(primes,nil());

Co-variant subtyping GenList[S] should be a subtype of GenList[T] if S is a subtype of T: trait GenList[+T]; case class Nil[T] extends GenList[T]; case class Cons[T](head: T, tail: GenList[T]) extends GenList[t]; val primes:genlist[int]=cons(13,cons(7,cons(11,nil()))); val objects:genlist[any]=cons(13,cons( seven Nil())); val lists:genlist[genlist[any]]= Cons(primes,Cons(objects,Nil()));

Co-variance II Now we can use a singleton Nil[All] instead of new, typed instances everywhere if we want to: trait GenList[+T]; object Nil extends GenList[All]; class Cons[T](head: T, tail: GenList[T]) extends GenList[t];

Contravariance When is a function a subtype of another? f1:(a1=>r1) is a subtype of f2(a2=>r2) if and only if A1 is a supertype of A1, and R1 is a subtype of R2: abstract class BinaryFunct[ A,+R] { def apply(arg:a):r class isordered extends BinaryFunct[Pair[Ord,Ord], bool]{ def apply(arg){arg._1 =< arg._2 val intpairfunctions: GenList[BinaryFunc[Pair [int,int],any]] = Cons(isOrdered,Nil);

Type Bounds Can we write generic functions for non-covariant containers? Consider the signature of the Array based sort function: sort(xs: Array[Ord]): unit The comparison function is defined in the trait Ord, so all subclasses of Ord are valid inputs for the sorting function. But an array of such elements is not in any subtyping relationship with with Array[Ord]! We need to say Array of subtype of Ord : sort(xs: Array[T :< Ord]): unit Type lower bound can be expressed similarly with :>

Java compatibilty From java bytecode scala can: instaciate objects, call methods, throw/catch exceptions extend classes, implement interfaces Java classes can be mixins when available in source code or decompiled. Java locking and concurency model supported, but normaly wrapped. Execution uses unmodified JVM bootstrapped with the scala base class library.