© Logica 2008. Tous droits réservés Une Introduction à Michel Daviot

Preview:

Citation preview

© Logica 2008. Tous droits réservés

Une Introduction àMichel Daviot

N°220 mai 2010 Une introduction à Scala

2

3

Plan

Scala, c’est quoi ? Pourquoi Scala ?1

Syntaxe Java améliorée

Programmation fonctionnelle

4 Les Traits

5 Pattern Matching

6 Acteurs et immuabilité

8 Interopérabilité avec Java

7 XML

N°3Une introduction à Scala

Qui utilise Scala ?

http://www.scala-lang.org/node/1658

N°3Une introduction à Scala

Un langage qui émerge lentement

http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html

Avril 2010

N°3Une introduction à Scala

Scala, c’est quoi ?

•Scalable Language, inventé en 2003 par Martin Odersky

•Langage hybride : fonctionnel et objet

•Code concis et expressif; fort niveau d’abstraction (plus pour moins)

•Fortement typé (typage statique)

•Compatible avec Java, exécuté dans la JVM

N°3Une introduction à Scala

La Syntaxe

•def, var et val (immuable)

•Éliminer l’inutile . () ; et return DSL"(S|s)cala".r findAllIn "Scala is scalable"

•Typage statique, implicite (inférence)def add(i:Int, j:Int) = i + jval i=add(3,5)

•Chaines « magiques » regexp, html"""(\w+)://([^/:]+)(:\d+)?/(.*) """

•Retour multipledef div(a:Int, b:Int)= (a/b, a%b)

list.partition(_.age>18)

N°3Une introduction à Scala

La Syntaxe (2)

•Classes « intelligentes »

class Person (val id : Int=0, var name : String="") {

override def toString = name

}

val p=new Person(3)

p.name="Jacques"

println(p)

Programmation fonctionnelle

•Toute fonction est un objetdef square(x:Int)=x*x

List(1,2,3,4,5).map(square)

•Paramètres anonymesList(1,2,3,4,5).filter( _ > 2)

•Attention aux excès (au début)

(0 /: List(1,2,3,4,5)) { _ + _ }

N°3Une introduction à Scala

N°3Une introduction à Scala

Les traits

•Utilisable comme interface Javatrait Observer { def receiveAlert(s: String) }

•Permet les Mixins

trait Observable { private var observers : List[Observer]=Nil

def addObserver(o:Observer){observers = o::observers}

def alert(msg : String) { observers.foreach(_.receiveAlert(msg)) }}

N°3Une introduction à Scala

Les traits (2) : Mixin sur une classe

class WatchedPerson() extends Person() with Observable {

def changeName(n:String) { name=n; super.alert("new name "+n) }

}

val p=new WatchedPerson

val o=new Observer{

def receiveAlert(s : String) { println(s)}

}

p.addObserver(o)

p changeName "Dominique"

N°3Une introduction à Scala

Les traits (3) : Mixin sur une instance

val p=new Person with Observable

p.addObserver(o)

p changeName "toto"

N°3Une introduction à Scala

Pattern matching : regexp

val url="http://www.allocine.fr:8080/seance/"

val regexp="""(\w+)://([^/:]+)(:\d+)?/(.*)""".r

url match {

case regexp(protocol, host, port, path) => printf("protocol %s, host %s, port %s, path

%s\n", protocol, host, port, path)

case _ => println("does not match")

}

N°3Une introduction à Scala

Pattern matching : listes et tuples

def test(x:Any) = {

x match {

case List(a,b,c) => "3 elts"

case (a:Int, b:Int) => a+"&"+b

case _ => "no idea"

}}

println(test(List(1,2,3)))

println(test(2,3))

println(test("toto"))

Acteurs et immuabilité : situation initiale (mono thread)

def slowFibo(n:Int) : Int = if(n<=2) 1 else slowFibo(n-1)+slowFibo(n-2)

def time(f: => Int) = {

val t=System.currentTimeMillis

(f, System.currentTimeMillis - t)

}

def sum(n:Int, f: Int => Int) = (0 /: (1 to n).map(f(_))) (_ + _)

time(sum(40,slowFibo))

No. 14

Acteurs et immuabilité

def actorSum(n:Int, f: Int => Int) = {

val caller=self

for (i <- 1 to n) {

actor { caller ! slowFibo(i) }

}

var sum=0

for (i <- 1 to n) {

receive {

case f : Int => sum = sum + f

}}

sum

}

No. 15

N°3Une introduction à Scala

Résultats de l’utilisation des acteurs

(701408732,6020)

(701408732,3776)

N°3Une introduction à Scala

Acteurs et immuabilité

Applications :•Requêtes réseaux•Calcul distribué•Algorithmes MapReduce

•Un code très simple par rapport aux Threads•Pas de synchronize donc pas de risque de deadlock•Possible si on utilise des immuables (val)

N°3Une introduction à Scala

XML

•Simple à produire :val content= <data>some</data> <data tag='important'> more</data> val name="logica" val r= <root xmlns='urn:com.logica.ns'> <elt value={name}/>{content}</root>

•Assez simple à parser :r \\ "data" foreach {e=> println(e.text) }r \\ "data" foreach println

•Limitation : moins élégant pour filtrer sur les attributs

N°3Une introduction à Scala

Interopérabilité avec Java

•Support de la double dépendance à la compilation

•Implémentation d’un trait

•En Scala :trait Observer { def receiveAlert(s: String) }

•En Java :public class JavaObserver implements Observer { @Override public void receiveAlert(String s) { System.out.println(s); }}

N°3Une introduction à Scala

Conclusion : quelques citations

•James Gosling (Java) : During a meeting in the Community Corner, a participant asked an interesting question: "Which Programming Language would you use now on top of JVM, except Java?“

•James Strachan (Groovy, 07/2009) : I'm very impressed with it ! I can honestly say if someone had shown me the Programming Scala book by by Martin Odersky, Lex Spoon & Bill Venners back in 2003 I'd probably have never created Groovy.

•Charles Nutter (JRuby) : Scala is most likely candidate to replace Java, compared to Groovy and JRuby. While Scala is not a dynamic language, it has many of the characteristics of popular dynamic languages, through its rich and flexible type system, its sparse and clean syntax, and its marriage of functional and object paradigms.

Pour essayer

N°3Une introduction à Scala

http://www.simplyscala.com/ : en ligne, rien à télécharger

Pour essayer (2) : interpréteur en ligne de commande

N°3Une introduction à Scala

http://www.scala-lang.org/downloads

Pour essayer (3) : Eclipse

N°3Une introduction à Scala

http://download.scala-ide.org/

No. 24Une introduction à Scala

or

Programmation fonctionnelle (2)

•Le currydef sum(i:Int)(j:Int) = i + jdef s2 =sum(2) _val k=s2(9)

•Closuresdef repeat(n : Int, closure : Int => Unit) { for (i <- 1 to n) {closure(i)}}

var context=new StringBuilderrepeat(5, {i => context.append(i)})println(context.toString)

ou aussi : (1 to 5) mkString(",")

N°3Une introduction à Scala

Programmation fonctionnelle

N°3Une introduction à Scala

import java.io._

def write(file : String)(code : PrintWriter => Unit) { val writer=new PrintWriter(file) try { code(writer) } catch { case e : IOException => println(e.getMessage) } finally { writer.close }}

write("toto.txt"){pw => pw.write("hello")}

Recommended