Analyse Et Conception Formelles Lesson 5 – Crash Course on Scala

Analyse Et Conception Formelles Lesson 5 – Crash Course on Scala

Bibliography Analyse et Conception Formelles Programming in Scala, M. Odersky, L. Spoon, B. Venners. Artima. http://www.artima.com/pins1ed/index.html Lesson 5 An Overview of the Scala Programming Language, M. Odersky & al. http://www.scala-lang.org/docu/files/ScalaOverview.pdf – Crash Course on Scala Scala web site. http://www.scala-lang.org Acknowledgements Many thanks to J. Noy´e and J. Richard-Foy for providing material, answering questions and for fruitful discussions. T. Genet (ISTIC/IRISA) ACF-5 1/35 T. Genet (ISTIC/IRISA) ACF-5 2/35 Scala in a nutshell Outline “Scalable language”: small scripts to architecture of systems 1 Basics Base types and type inference Control : if and match - case Designed by Martin Odersky at EPFL Loops (for) and structures: Lists, Tuples, Maps I Programming language expert 2 Functions I One of the designers of the Java compiler Basic functions Anonymous, Higher order functions and Partial application 3 Object Model Pure object model: only objects and method calls (=Java) ” Class definition and constructors Method/operator/function definition, overriding and implicit defs With functional programming: higher-order, pattern-matching, . Traits and polymorphism Fully interoperable with Java (in both directions) Singleton Objects Case classes and pattern-matching Concise smart syntax (=Java) 4 Interactions with Java ” Interoperability between Java and Scala A compiler and a read-eval-print loop integrated into the IDE 5 Isabelle/HOL export in Scala Scala worksheets!! T. Genet (ISTIC/IRISA) ACF-5 3/35 T. Genet (ISTIC/IRISA) ACF-5 4/35 Outline Base types and type annotations 1 Basics Base types and type inference Control : if and match - case Loops (for) and structures: Lists, Tuples, Maps 1:Int, "toto":String, ’a’:Char, ():Unit 2 Functions Every data is an object, including base types! Basic functions e.g. 1 is an object and Int is its class Anonymous, Higher order functions and Partial application Every access/operation on an object is a method call! 3 Object Model e.g. 1+2executes: 1.+(2) (o.x(y) is equivalent to oxy) Class definition and constructors Method/operator/function definition, overriding and implicit defs Traits and polymorphism Exercise 1 Singleton Objects Use the max(Int) method of class Int to compute the maximum of 1+2 Case classes and pattern-matching and 4. 4 Interactions with Java Interoperability between Java and Scala 5 Isabelle/HOL export in Scala T. Genet (ISTIC/IRISA) ACF-5 5/35 T. Genet (ISTIC/IRISA) ACF-5 6/35 Class hierarchy Section 11.1 Chapter 11 · Scala’s Hierarchy Class hierarchy scala Subtype Any Implicit Conversion Cover · Overview scala scala scala AnyRef AnyVal ScalaObject «java.lang.Object» scala · Double scala Contents Unit Section 11.1 Chapter 11 · Scala’s Hierarchy scala scala Float scala Boolean java.lang Iterable String · Discuss scala scala Long Char scala Subtype Seq scala ... (other Java classes) ... Any Implicit Conversion Cover scala scala Int · List Suggest scala ... (other Scala classes) ... Short · Overview scala scala · scala AnyRef Glossary scala AnyVal Byte ScalaObject «java.lang.Object» scala Null scala · · Double scala Index Contents scala Unit Nothing scala scala Float scala Boolean java.lang Figure 11.1 · Class hierarchy of Scala. Iterable String · T. Genet (ISTIC/IRISA) ACF-5 7/35Discuss scala T. Genet (ISTIC/IRISA)scala ACF-5 8/35 252 Long Char scala Seq ... (other Java classes) ... scala scala Int · List Suggest scala ... (other Scala classes) ... Short · Glossary scala Byte scala Null · Index scala Nothing Figure 11.1 · Class hierarchy of Scala. 252 Section 11.1 Chapter 11 · Scala’s Hierarchy Section 11.1 Chapter 11 · Scala’s Hierarchy scala Subtype Any Implicit Conversion Cover scala Subtype Any Implicit Conversion Cover Class hierarchy · Class hierarchy Overview scala scala scala · AnyRef Overview AnyVal ScalaObject «java.lang.Object» scala scala scala AnyRef AnyVal ScalaObject «java.lang.Object» scala · Double scala Contents scala Unit · Double scala Section 11.1 Chapter 11 · Scala’s Hierarchy Contents Unitscala scala Float Boolean scala Iterable java.lang scala scala String Float · Boolean scala Discuss scala scala java.lang Iterable scala scala Long Subtype Char String · Implicit Conversion Seq Discuss scalaAny scala Cover Long Char scala ... (other Java classes) ... scala Seq scala Int · ... (other Java classes) ... List scala Suggest scala · Overview Int · List scala scala ... (other Scala classes) ... Suggest scala scala AnyRef Short AnyVal ScalaObject scala «java.lang.Object» ... (other Scala classes) ... Short · Glossary scala scala Byte · · Double scala scala Glossary scala Contents Unit Byte Null scala T. Genet (ISTIC/IRISA) ACF-5 9/35 T. Genet (ISTIC/IRISA) ACF-5 10 / 35 scala scala Null Float scala · Boolean Index java.lang Iterable String scala · · Nothing Index Discuss scala scala Long Char scala scala Class hierarchy Seq Nothing val and var ... (other Java classes) ... val associates an object to an identifier and cannot be reassigned scala scala Figure 11.1 · Class hierarchy of Scala. Int · List var associates an object to an identifier and can be reassigned Suggest Figure 11.1 · Class hierarchy of Scala. 252 Scala philosophy is to use val instead of var whenever possible scala ... (other Scala classes) ... Short Types are (generally) automatically252 inferred · Glossary scala Byte scala scala> val x=1 // or val x:Int = 1 Null x: Int = 1 · scala> x=2 Index scala <console>:8: error: reassignment to val Nothing x=2 ˆ scala> var y=1 Figure 11.1 · Class hierarchy of Scala. y: Int = 1 252 scala> y=2 y: Int = 2 T. Genet (ISTIC/IRISA) ACF-5 11 / 35 T. Genet (ISTIC/IRISA) ACF-5 12 / 35 if expressions match - case expressions Syntax is similar to Java if statements ... Replaces (and extends) the usual switch - case construction but that they are not statements but typed expressions The syntax is the following: e match if ( condition ) e1 else e2 { case pattern1 => r1 //patterns can be constants Remark: the type of this expression is the supertype of e1 and e2 case pattern2 => r2 //or terms with variables if ( condition ) e1 // else () ... //or terms with holes: ’ ’ Remark: the type of this expression is the supertype of e1 and Unit case => rn } Exercise 2 Remark: the type of this expression is the supertype of r1, r2, . rn What are the results and types of the corresponding if expressions: Example 1 (Match-case expressions) if (1==2) 1 else 2 x match { if (1==2) 1 else "toto" case "bonjour" => "hello" if (1==1) 1 case "au revoir" => "goodbye" if (1==1) println(1) case => "don’t know" } T. Genet (ISTIC/IRISA) ACF-5 13 / 35 T. Genet (ISTIC/IRISA) ACF-5 14 / 35 (Immutable) Lists: List[A] for loops List definition (with type inference) val l= List(1,2,3,4,5) for ( ident <- s ) e Adding an element to the head of a list Remark: s has to be a subtype of Traversable val l1= 0::l (Arrays, Collections, Tables, Lists, Sets, Ranges, . ) Adding an element to the queue of a list Usual for-loops can be built using .to(...) val l2= l1:+6 ”(1).to(5)” ”1 to 5” results in Range(1, 2, 3, 4, 5) © Concatenating lists val l3= l1++l2 Exercise 3 Getting the element at a given position Given val lb=List(1,2,3,4,5) and using for, build the list of squares val x= l2(2) of lb. Doing pattern-matching over lists l2 match Exercise 4 { Using for and println build a usual 10 10 multiplication table. case Nil => 0 ◊ case e:: => e } T. Genet (ISTIC/IRISA) ACF-5 15 / 35 T. Genet (ISTIC/IRISA) ACF-5 16 / 35 (Immutable) Tuples : (A,B,C,...) (Immutable) maps : Map[A,B] Map definition (with type inference) Tuple definition (with type inference) val m= Map(’C’ -> "Carbon",’H’ -> "Hydrogen") scala> val t= (1,"toto",18.3) Remark: inferred type of m is Map[Char,String] t: (Int, String, Double) = (1,toto,18.3) Finding the element associated to a key in a map, with default value Tuple getters: t. 1, t. 2, etc. m.getOrElse(’K’,"Unknown") ... or with match - case: Adding an association in a map t match case (2,"toto", ) => "found!" val m1= m+(’O’ -> "Oxygen") { case ( ,x, ) => x A Map[A,B] can be traversed (using for)asaCollection of pairs } of type Tuple[A,B], e.g. for((k,v) <- m) ... { } The above expression evaluates in "toto" Exercise 5 Print all the keys of map m1 T. Genet (ISTIC/IRISA) ACF-5 17 / 35 T. Genet (ISTIC/IRISA) ACF-5 18 / 35 Outline Basic functions 1 Basics def f ( arg1: Type1, ..., argn:Typen ): Typef = e Base types and type inference { } Control : if and match - case Remark 1: type of e (the type of the last expression of e) is Typef Loops (for) and structures: Lists, Tuples, Maps Remark 2: Typef can be inferred for non recursive functions 2 Functions Remark 3: The type of f is : (Type1,. ,Typen) Typef Basic functions Anonymous, Higher order functions and Partial application Example 2 3 Object Model def plus(x:Int,y:Int):Int= { Class definition and constructors println("Sum of "+x+" and "+y+" is equal to "+(x+y)) Method/operator/function definition, overriding and implicit defs x+y // no return keyword Traits and polymorphism // the result of the function is the last expression } Singleton Objects Case classes and pattern-matching Exercise 6 4 Interactions with Java Using a map, define a phone book and the functions Interoperability between Java and Scala addName(name:String,tel:String), getTel(name:String):String, 5 Isabelle/HOL export in Scala getUserList:List[String] and getTelList:List[String]. T. Genet (ISTIC/IRISA) ACF-5 19 / 35 T. Genet (ISTIC/IRISA) ACF-5 20 / 35 Anonymous functions and Higher-order functions Partial application The anonymous Scala function adding one to x is: ((x:Int) => x + 1) The ’ ’ symbol permits to partially apply a function Remark: it is written (⁄ x.

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    9 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us