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

Slides:



Advertisements
Similar presentations
OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
Advertisements

CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists Dan Grossman Winter 2013.
U NIVERSITY OF D ELAWARE C OMPUTER & I NFORMATION S CIENCES D EPARTMENT Optimizing Compilers CISC 673 Spring 2009 Potential Languages of the Future Chapel,
6/10/2015Martin Odersky, LAMP, EPFL1 Programming Language Abstractions for Semi-Structured Data Martin Odersky Sebastian Maneth Burak Emir EPFL.
Chess Review May 8, 2003 Berkeley, CA Classes and Inheritance in Actor- Oriented Models Stephen Neuendorffer Edward Lee UC Berkeley.
Functional Design and Programming Lecture 1: Functional modeling, design and programming.
Programming Language Paradigms: summary. Object-oriented programming Objects are the fundamental building blocks of a program. Interaction is structured.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
High-Level Programming Languages
Programming in Scala Chapter 1. Scala: both object-oriented and functional Scala blends –object-oriented and –functional programming in a –statically.
2.3 Cool features in C# academy.zariba.com 1. Lecture Content 1.Extension Methods 2.Anonymous Types 3.Delegates 4.Action and Func 5.Events 6.Lambda Expressions.
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Programming Paradigms for Concurrency Lecture 9 Part III – Message Passing Concurrency.
Scala Actors -Terrance Dsilva.  Thankfully, Scala offers a reasonable, flexible approach to concurrency  Actors aren’t a concept unique to Scala.
Introduction to Ruby CSE 413 Autumn 2008 Credit: Dan Grossman, CSE341.
Symbol Table (  ) Contents Map identifiers to the symbol with relevant information about the identifier All information is derived from syntax tree -
The Scala Experience Martin Odersky EPFL Lausanne, Switzerland.
Modern Concurrency Abstractions for C# by Nick Benton, Luca Cardelli & C´EDRIC FOURNET Microsoft Research.
Programming Languages and Paradigms Object-Oriented Programming.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Object-Oriented Implementation of Reconciliations M.Sc. Seminar Talk by Costa Shapiro under supervision of Prof. Shmuel Katz Computer Science – Technion.
The Scala Programming Language presented by Donna Malayeri.
Scala Overview Brandon Clopton CSCI 431. Scala fuses object-oriented and functional programming in a statically typed programming language. It is aimed.
CSE 425: Object-Oriented Programming I Object-Oriented Programming A design method as well as a programming paradigm –For example, CRC cards, noun-verb.
A Little Language for Surveys: Constructing an Internal DSL in Ruby H. Conrad Cunningham Computer and Information Science University of Mississippi.
- Neeraj Chandra.  It’s language written by by Martin Odersky at EPFL  It’s language written by by Martin Odersky at EPFL (École Polytechnique Fédérale.
Introduction to Object Oriented Programming CMSC 331.
Objects & Dynamic Dispatch CSE 413 Autumn Plan We’ve learned a great deal about functional and object-oriented programming Now,  Look at semantics.
Functions and Methods. Definitions and types A function is a piece of code that takes arguments and returns a result A pure function is a function whose.
Types in programming languages1 What are types, and why do we need them?
CS162 Week 1 Kyle Dewey. Overview Basic Introduction CS Accounts Scala survival guide.
RUBY by Ryan Chase.
CIS 270—Application Development II Chapter 8—Classes and Objects: A Deeper Look.
On Implementing High Level Concurrency in Java G Stewart von Itzstein Mark Jasiunas University of South Australia.
CSE 341 Section 10 Subtyping, Review, and The Future.
C# Fundamentals An Introduction. Before we begin How to get started writing C# – Quick tour of the dev. Environment – The current C# version is 5.0 –
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
Chapter 12: Support for Object- Oriented Programming Lecture # 18.
CSCI 383 Object-Oriented Programming & Design Lecture 15 Martin van Bommel.
Lightweight Language Support for Type-Based, Concurrent Event Processing Philipp Haller EPFL Scala Workshop 2010.
Tom Van Cutsem, Vrije Universiteit Brussel
Scala days 2010 exmachina.
Part 1: Overview of LINQ Intro to LINQ Presenter: PhuongNQK.
SCALA CONCEPTS PROGRAMMING USING FUNCTIONAL OBJECTS UMBC CMSC 331
Chapter 0: Introduction
Planning & System installation
Abstract Data Types and Encapsulation Concepts
OOP What is problem? Solution? OOP
Graph Coverage for Specifications CS 4501 / 6501 Software Testing
Object-Oriented Programming & Design Lecture 14 Martin van Bommel
Microsoft .NET 3. Language Innovations Pan Wuming 2017.
Object Oriented Programming in Java
Object-Orientated Programming
CS360 Windows Programming
Functional Programming with Java
Compiling, Assembling and Executing Java using Java
Setac: A Phased Deterministic Testing Framework for Scala Actors
Martin Odersky EPFL Lausanne, Switzerland
.NET and .NET Core 5.2 Type Operations Pan Wuming 2016.
Abstract Data Types and Encapsulation Concepts
Java Programming Language
Setac: A Phased Deterministic Testing Framework for Scala Actors
Object Oriented Programming
Objects and Aspects: What we’ve seen so far
CISC124 Labs start this week in JEFF 155. Fall 2018
CMPE212 – Reminders The other four assignments are now posted.
Introduction to Data Structure
Declarative Computation Model Single assignment store (VRH 2
Groovy.
Abstract Types Defined as Classes of Variables
Presentation transcript:

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

June 2, 2008Philipp Haller -- An Overview of Scala2/27 The Scala Programming Language ● Unifies functional and object-oriented programming concepts ● Enables embedding rich domain-specific languages (DSLs) ● Supports high-level concurrent programming through library extensions that are efficient and expressive

June 2, 2008Philipp Haller -- An Overview of Scala3/27 A Scalable Language ● Language scalability: express small + large programs using the same constructs ● Unify and generalize object-oriented and functional programming concepts to achieve language scalability ● Interoperable with Java –.NET version under reconstruction ● Open-source distribution available since 2004 – 5000 downloads/month (from EPFL)

June 2, 2008Philipp Haller -- An Overview of Scala4/27 From Java to Scala object Example1 { def main(args: Array[String]) { val b = new StringBuilder() for (i <- 0 until args.length) { if (i > 0) b.append(" ") b.append(args(i).toUpperCase) } Console.println(b.toString) } ● Scala's syntax often the same as Java's (method call, field selection, class inheritance) ● Scala compiles to JVM bytecodes Scala’s version of the extended for loop Arrays are indexed args(i) instead of args[i] Array[String] instead of String[] object instead of static members

June 2, 2008Philipp Haller -- An Overview of Scala5/27 Functional Scala ● Arrays are instances of general sequence abstractions ● Higher-order functions instead of loops object Example2 { def main(args: Array[String]) { println(args.map(arg => arg.toUpperCase).mkString(" ")) } Applies function on its right to each array element Closure that applies toUpperCase method to its String argument Forms a string of all elements with a given separator between them

June 2, 2008Philipp Haller -- An Overview of Scala6/27 Principles of Scala (a)Unify algebraic data types (ADTs) and class hierarchies (b)Unify functions and objects Integrate OOP and FP as tightly as possible in a statically-typed language

June 2, 2008Philipp Haller -- An Overview of Scala7/27 ADTs and Pattern Matching ● FP: ADTs and pattern matching → concise and canonical manipulation of data structures ● OOP objects against ADTs: – Not extensible – Violate purity of OOP data model ● OOP objects against pattern matching: – Breaks encapsulation – Violates representation independence

June 2, 2008Philipp Haller -- An Overview of Scala8/27 Pattern Matching in Scala def inOrder[T](t: Tree[T]): List[T] = t match { case Leaf => List() case Fork(e,l,r) => inOrder(l):::List(e):::inOrder(r) } In-order traversal abstract class Tree[+T] case object Leaf extends Tree[Nothing] case class Fork(elem: T, left: Tree[T], right: Tree[T]) extends Tree[T] Binary trees ● Purity: cases are objects or classes ● Extensibility: can define more cases elsewhere ● Encapsulation: only parameters revealed ● Representation independence: extractors [ECOOP'07] case modifier enables pattern matching

June 2, 2008Philipp Haller -- An Overview of Scala9/27 Extractors ● Objects with unapply methods ● Pattern matcher implicitly calls unapply methods (if they exist) object Twice { def apply(x: Int) = x*2 def unapply(z: Int) = if (z%2==0) Some(z/2) else None } val x = Twice.apply(21) x match { case Twice(y) => println(x+" is two times "+y) case _ => println("x is odd") }

June 2, 2008Philipp Haller -- An Overview of Scala10/27 Principles of Scala (a)Unify algebraic data types (ADTs) and class hierarchies (b)Unify functions and objects Integrate OOP and FP as tightly as possible in a statically-typed language

June 2, 2008Philipp Haller -- An Overview of Scala11/27 Functions in Scala ● Functions are first-class values ● Values are objects → functions are objects ● Function type A => B equivalent to type Function1[A, B] : trait Function1[-A, +B] { def apply(x: A): B } ● Compilation of anonymous functions: (x: Int) => x + 1 new Function1[Int, Int] { def apply(x: Int): Int = x + 1 }

June 2, 2008Philipp Haller -- An Overview of Scala12/27 Subclassing Functions ● Arrays are mutable functions over integer ranges: class Array[T](length: Int) extends (Int => T) { def length: Int =... def apply(i: Int): T =... def update(i: Int, x: T): Unit =... def elements: Iterator[T] =... def exists(p: T => Boolean): Boolean =... } ● Syntactic sugar: a(i) = a(i) + 2 a.update(i, a.apply(i) + 2)

June 2, 2008Philipp Haller -- An Overview of Scala13/27 Partial Functions ● Defined only for subset of domain: trait PartialFunction[-A, +B] extends (A => B) { def isDefinedAt(x: A): Boolean } ● Anonymous partial functions: { case pat 1 : A => body 1 : B... case pat n : A => body n : B } new PartialFunction[A, B] { def isDefinedAt(x: A): Boolean =... def apply(x: A): B =... }

June 2, 2008Philipp Haller -- An Overview of Scala14/27 Principles of Scala (a)Unify algebraic data types (ADTs) and class hierarchies (b)Unify functions and objects Integrate OOP and FP as tightly as possible in a statically-typed language

June 2, 2008Philipp Haller -- An Overview of Scala15/27 Library Extensions ● Functional objects enable rich embedded DSLs ● First-class partial functions enable definition of control structures in libraries ● Example: Scala Actors concurrency library

June 2, 2008Philipp Haller -- An Overview of Scala16/27 Scala Actors ● Two basic operations (adopted from Erlang) ● Asynchronous send ( ! ) buffers messages in receivers's mailbox ● Synchronous receive waits for message that matches any of the patterns msgpat i actor ! message // message send receive { // message receive case msgpat 1 => action 1... case msgpat n => action n }

June 2, 2008Philipp Haller -- An Overview of Scala17/27 A Simple Actor case class Data(bytes: Array[Byte]) case class Sum(receiver: Actor) val checkSumCalculator: Actor = actor { var sum = 0 loop { receive { case Data(bs) => sum += hash(bs) case Sum(receiver) => receiver ! sum }

June 2, 2008Philipp Haller -- An Overview of Scala18/27 Implementing receive def receive[R](f: PartialFunction[Message, R]): R = synchronized { mailbox.dequeueFirst(f.isDefinedAt) match { case Some(msg) => f(msg) case None => waitingFor = f.isDefinedAt suspendActor() } Queue of pending messages Extracts first queue element matching given predicate

June 2, 2008Philipp Haller -- An Overview of Scala19/27 Library vs. Language ● Libraries much easier to extend and adapt than languages ● Example: thread-based receive requires one VM thread per actor – Problem: high memory consumption and context switching overhead – Solution: second, non-returning receive operation called react that makes actors event-based – Haller, Odersky: Actors that Unify Threads and Events, Coordination'07

June 2, 2008Philipp Haller -- An Overview of Scala20/27 Extension: Joins for Actors ● Joins: high-level, declarative synchronization constructs (based on join calculus) ● Goal: enable join patterns alongside normal message patterns ● Example: receive { case Put(x) & Get() => Get reply x case Some(other) =>... }

June 2, 2008Philipp Haller -- An Overview of Scala21/27 Implementing Joins ● Problem: outcome of matching depends on multiple message sends ● When sending a Get message, the pattern case Put(x) & Get() matches iff there is also a Put message in the mailbox ● Idea: use extensible pattern matching to search mailbox

June 2, 2008Philipp Haller -- An Overview of Scala22/27 Matching Join Patterns { case &(Get(), Put(x)) =>... } new PartialFunction[?, Unit] { def isDefinedAt(y: ?) = &.unapply(y) match { case Some((Get(), Put(x))) => true case None => false } (gets compiled into)

June 2, 2008Philipp Haller -- An Overview of Scala23/27 Matching Join Patterns (cont'd) { case &(Get(), Put(x)) =>... } (gets compiled into) new PartialFunction[?, Unit] { def isDefinedAt(y: ?) = &.unapply(y) match { case Some((u, v)) => Get.unapply(u) match { case true => Put.unapply(v) match { case Some(x) => true case None => false } case false => false } case None => false }

June 2, 2008Philipp Haller -- An Overview of Scala24/27 Scala Joins: Summary ● Novel implementation based on extensible pattern matching (Scala, F#) – New library-based solution ● More consistency checks – Re-use variable binding – Re-use guards ● More expressive – Nested patterns and guards – Dynamic join patterns

June 2, 2008Philipp Haller -- An Overview of Scala25/27 Scala Actors: Summary ● Scala library extension for high-level concurrent programming – Pair of message receive operations (receive/react) allows trade-off between efficiency and flexibility ● Message handlers as first-class partial functions – Enables extension of actor behavior ● Support for expressive join-style message patterns (Haller, Van Cutsem: Implementing Joins using Extensible Pattern Matching, Coordination'08)

June 2, 2008Philipp Haller -- An Overview of Scala26/27 Application: lift Web Framework ● Similar to Rails and Seaside, exercises many features of Scala – Actors: AJAX/Comet-style applications – Closures: HTML form elements – Traits/Mixins: persistence, data binding, query building – Pattern matching: extensible URL matching ● Use case: Skittr, a Twittr clone ● Excellent scalability: 10 6 actors on dual-core

June 2, 2008Philipp Haller -- An Overview of Scala27/27 Scala: Conclusion ● Integration of FP and OOP as tight as possible ● A scalable language: the same constructs express small and large programs ● Enables high-level concurrency libraries that are efficient and expressive – Example: Scala Actors ● Try it out: