Poor Man's Type Classes



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

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

Programming Language Rankings. Lecture 15: Type Inference, polymorphism & Type Classes. Top Combined. Tiobe Index. CSC 131! Fall, 2014!

Analyse et Conception Formelle. Lesson 5. Crash Course on Scala

Tutorial on Writing Modular Programs in Scala

Scala Programming Language

Java Programming Language

Type Classes with Functional Dependencies

Managing large sound databases using Mpeg7

A Scala Tutorial for Java programmers

Java Interview Questions and Answers


Datatype-generic data migrations

Glossary of Object Oriented Terms

CSc 372. Comparative Programming Languages. 21 : Haskell Accumulative Recursion. Department of Computer Science University of Arizona

PHP Object Oriented Classes and objects

POLYTYPIC PROGRAMMING OR: Programming Language Theory is Helpful

Computing Concepts with Java Essentials

Getting Started with the Internet Communications Engine

Formal Engineering for Industrial Software Development


CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5

13 Classes & Objects with Constructors/Destructors

Aspect-Oriented Programming with Type Classes

types, but key declarations and constraints Similar CREATE X commands for other schema ëdrop X name" deletes the created element of beer VARCHARè20è,

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Description of Class Mutation Mutation Operators for Java

Scala type classes and machine learning. David Andrzejewski Bay Area Scala Enthusiasts - 1/14/2013, 1/16/2013

History OOP languages Year Language 1967 Simula Smalltalk

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Checking Access to Protected Members in the Java Virtual Machine

JAVA - INHERITANCE. extends is the keyword used to inherit the properties of a class. Below given is the syntax of extends keyword.

Semester Review. CSC 301, Fall 2015

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

Reactive Slick for Database Programming. Stefan Zeiger

Agile Software Development

Searching Algorithms

Detecting Pattern-Match Failures in Haskell. Neil Mitchell and Colin Runciman York University

Java Interfaces. Recall: A List Interface. Another Java Interface Example. Interface Notes. Why an interface construct? Interfaces & Java Types

Java CPD (I) Frans Coenen Department of Computer Science

Chapter 6: Programming Languages

An Introduction To UML Class Diagrams Classes

Introduction to Object-Oriented Programming

Chapter 4 OOPS WITH C++ Sahaj Computer Solutions

Fundamentals of Java Programming

AP Computer Science Java Subset

Chapter 13 - Inheritance

Part I. Multiple Choice Questions (2 points each):

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

The Clean programming language. Group 25, Jingui Li, Daren Tuzi

How Scala Improved Our Java

Visual Basic Programming. An Introduction

CS 111 Classes I 1. Software Organization View to this point:

Dynamic conguration management in a graph-oriented Distributed Programming Environment

Design by Contract beyond class modelling

In the above, the number 19 is an example of a number because its only positive factors are one and itself.

The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0

D06 PROGRAMMING with JAVA

CS193j, Stanford Handout #10 OOP 3

Anatomy of Programming Languages. William R. Cook

Chapter 5 Names, Bindings, Type Checking, and Scopes

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

SE 360 Advances in Software Development Object Oriented Development in Java. Polymorphism. Dr. Senem Kumova Metin

Object oriented design process

Type Classes as Objects and Implicits

Lecture 12: Abstract data types

Big Data Frameworks: Scala and Spark Tutorial

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Programming Languages Featherweight Java David Walker

Chapter 7: Functional Programming Languages

Statements and Control Flow

A Typing System for an Optimizing Multiple-Backend Tcl Compiler

S4 Classes in 15 pages, more or less

The Needle Programming Language

Independently Extensible Solutions to the Expression Problem

J a v a Quiz (Unit 3, Test 0 Practice)

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

An Algebra for Feature-Oriented Software Development

Abstract Class & Java Interface

5. Advanced Object-Oriented Programming Language-Oriented Programming

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class

How To Write A Program In Java (Programming) On A Microsoft Macbook Or Ipad (For Pc) Or Ipa (For Mac) (For Microsoft) (Programmer) (Or Mac) Or Macbook (For

Outline of this lecture G52CON: Concepts of Concurrency

PRI-(BASIC2) Preliminary Reference Information Mod date 3. Jun. 2015

OpenCL Static C++ Kernel Language Extension

Stack Allocation. Run-Time Data Structures. Static Structures

Business Application

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

Designware: This paper presents a mechanizable framework for software development by renement.

Data-cubing made-simple! with Spark, Algebird and HBase goo.gl/dbgr0h

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Transcription:

Poor Man's Type Classes Martin Odersky EPFL IFIP WG2.8 workin roup meetin Boston, July 2006. 1

Goals Type classes are nice. A cottae industry of Haskell prorammers has sprun up around them. Should we add type classes to OO-lanuaes, specically Scala? Problem: Conceptual expense We have already spent the keywords type and class! Type classes are essentially implicitly passed dictionaries, and dictionaries are essentially objects. Don't want to duplicate that. Idea: Concentrate on the delta between OO classes and type classes: implicits 2

Life without Type Classes Some standard classes for SemiGroup and Monoid: abstract class SemiGroup[a] f def add(x: a, y: a): a abstract class Monoid[a] extends SemiGroup[a] f def unit: a Two implementations of monoids: object strinmonoid extends Monoid[Strin] f def add(x: Strin, y: Strin): Strin = x.concat(y) def unit: Strin = "" object intmonoid extends Monoid[int] f def add(x: Int, y: Int): Int = x + y def unit: Int = 0 3

A sum method which works over arbitrary monoids: def sum[a](xs: List[a])(m: Monoid[a]): a = if (xs.isempty) m.unit else m.add(xs.head, sum(xs.tail)(m) One invokes this sum method by code such as: sum(list("a", "bc", "de"))(strinmonoid) sum(list(1, 2, 3))(intMonoid) 4

Implicit Parameters: The Basics The followin sliht rewrite of sum introduces m as an implicit parameter. def sum[a](xs: List[a])(implicit m: Monoid[a]): a = if (xs.isempty) m.unit else m.add(xs.head, sum(xs.tail)(m)) Can combine normal and implicit parameters. However, there may only be one implicit parameter list, and it must come last. 5

implicit can also be used as a modier for denitions: implicit object strinmonoid extends Monoid[Strin] f def add(x: Strin, y: Strin): Strin = x.concat(y) def unit: Strin = "" implicit object intmonoid extends Monoid[int] f def add(x: Int, y: Int): Int = x + y def unit: Int = 0 Aruments to implicit parameters can be inferred: sum(list(1, 2, 3)) This expands to: sum(list(1, 2, 3))(intMonoid) 6

Inferrin Implicit Aruments If an arument for an implicit parameter of type T is missin, it is inferred. An arument value is eliible to be passed, if it is itself labelled implicit, it's type is compatible with T, one of the followin holds: 1. x is accessible at the point of call by a simple identier (i.e. it is dened in same scope, inherited or imported) 2. x is dened as a static value in (some superclass of) T. If several aruments are eliible, choose most specic one. If no most specic eliible arument exists, type error. 7

Locality A consequence of implicit arument resolution is that one can have several instance denitions of the same operation at the same types. We always pick the one which is visible at the point of call. This is an important dierence between implicits and type classes. Rules to keep coherence: Scala has functions (which are objects) and methods (which are not). Partially applied methods are automatically converted to functions. Only methods can contain implicit parameters. Implicit parameters are instantiated where a method value is eliminated (either applied or converted to a function). 8

Conditional Implicits Implicit methods can themselves have implicit parameters. Example: implicit def listmonoid[a](implicit m: Monoid[a]) = new Monoid[List[a]] f def add(xs: List[a], ys: List[a]): List[a] = if (xs.isempty) ys else if (ys.isempty) xs else m.add(xs.head, ys.head) :: add(xs.tail, ys.tail) def unit = List() Then: println(sum(list(list(1, 2, 3), List(1, 2)))) translates to println(sum(list(list(1, 2, 3), List(1, 2)))(listMonoid(intMonoid)) ==> List(2, 4, 3) 9

External Extensibility Often, we like to add some new functionality to a pre-existin type. trait Ordered[a] f def compare(that: a): Int; def < (that: a): Boolean = (this compare that) < 0 def > (that: a): Boolean = (this compare that) > 0 def (that: a): Boolean = (this compare that) 0 def (that: a): Boolean = (this compare that) 0 Want to make Int, Strin, etc ordered. Want to make lists ordered if their elements are. Common solution: \open classes". 10

Implicit Conversions An implicit conversion is a unary function from S ot T, which is labelled implicit. Example: implicit def int2ordered(x: int) = new Ordered[int] f def compare(y: int) = if (x < y) 1 else if (x > y) 1 else 0 def sort[a](xs: Array[a])(implicit c: a ) Ordered[a]): Array[a] = if (xs.lenth 1) xs else f val pivot = xs(xs.lenth / 2) Array.concat( sort(xs lter (pivot >)) xs lter (pivot ==), sort(xs lter (pivot <))) val xss: Array[List[int]] sort(xss) 11

Translation def sort[a](xs: Array[a])(implicit c: a ) Ordered[a]): Array[a] = if (xs.lenth 1) xs else f val pivot = xs(xs.lenth / 2) Array.concat( sort(xs lter (c(pivot) >)) xs lter (pivot ==), sort(xs lter (c(pivot) <))) val xss: Array[List[int]] sort(xss)(list2ordered(int2ordered)) 12

Applications of Implicit Conversions An implicit conversion is applied to a term e if, e is not compatible with its expected type: val x: Ordered[int] = 1 ==> val x: Ordered[int] = int2ordered(1) In a selection e:m, if e does not have a member m. x.<(1) ==> int2ordered(x).<(1) In an application e:m(a1; : : : ; an), if e does not have a member m which can be applied to (a1; : : : ; an): val x = BiInt(10); 1 + x ==> BiInt(1) + x 13

Summary Scala implements the followin analoies: type class = class instance declaration = implicit denition context in a clas = inheritance context in a type = implicit parameter dictionary = object default method in class = concrete member method sinature in class = abstract member 14

Conclusion Implicit parameters are poor man's type classes. Conceptually lihtweiht. Piy-backed on object system. Implemented in Scala version 2, Can also model + multi-parameter type classes + parametric type classes (but no eneral functional dependencies). + associated types + constructor classes (via encodins, make this convenient we should add hiher-kinded type variables) 15