Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "© Logica 2008. Tous droits réservés Une Introduction à Michel Daviot."— Presentation transcript:

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

2 N°220 mai 2010Une 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

3 N°3Une introduction à Scala Qui utilise Scala ? http://www.scala-lang.org/node/1658

4 N°3Une introduction à Scala Un langage qui émerge lentement http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html Avril 2010

5 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

6 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 + j val i=add(3,5) Chaines « magiques » regexp, html """(\w+)://([^/:]+)(:\d+)?/(.*) """ Retour multiple def div(a:Int, b:Int)= (a/b, a%b) list.partition(_.age>18)

7 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)

8 Programmation fonctionnelle Toute fonction est un objet def square(x:Int)=x*x List(1,2,3,4,5).map(square) Paramètres anonymes List(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

9 N°3Une introduction à Scala Les traits Utilisable comme interface Java trait 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)) } }

10 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"

11 N°3Une introduction à Scala Les traits (3) : Mixin sur une instance val p=new Person with Observable p.addObserver(o) p changeName "toto"

12 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") }

13 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"))

14 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

15 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

16 N°3Une introduction à Scala Résultats de l’utilisation des acteurs (701408732,6020) (701408732,3776)

17 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)

18 N°3Une introduction à Scala XML Simple à produire : val content= some more val name="logica" val r= {content} Assez simple à parser : r \\ "data" foreach {e=> println(e.text) } r \\ "data" foreach println Limitation : moins élégant pour filtrer sur les attributs

19 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); }}

20 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.

21 Pour essayer N°3Une introduction à Scala http://www.simplyscala.com/http://www.simplyscala.com/ : en ligne, rien à télécharger

22 Pour essayer (2) : interpréteur en ligne de commande N°3Une introduction à Scala http://www.scala-lang.org/downloads

23 Pour essayer (3) : Eclipse N°3Une introduction à Scala http://download.scala-ide.org/

24 No. 24 Une introduction à Scala or

25 Programmation fonctionnelle (2) Le curry def sum(i:Int)(j:Int) = i + j def s2 =sum(2) _ val k=s2(9) Closures def repeat(n : Int, closure : Int => Unit) { for (i <- 1 to n) {closure(i)}} var context=new StringBuilder repeat(5, {i => context.append(i)}) println(context.toString) ou aussi : (1 to 5) mkString(",") N°3Une introduction à Scala

26 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")}


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

Similar presentations


Ads by Google