SlideShare ist ein Scribd-Unternehmen logo
1 von 62
PROGRAMMATION FONCTIONNELLE
SCALA
                     Slim Ouertani
site:        ouertani.com

  blog:        Jtunisie
               jroller.com/ouertani

  mail:        ouertani@gmail.com

twitter:   ouertani
                                      2
AGENDA

I - Motivation

II - Introduction à la PF

III - Introduction à Scala

                             3
4
MOTIVATION

   Loi de Moore

     Le
       nombre de transistors va
     doubler toute les deux années

     Transistors    Performance
     CPU
                                     5
MOTIVATION

Le futur et le présent du hardware
 est dans le parallélisme

  Resteque quelques routines en
   séquentielles


                                      6
MAIS !
 Diviser
       le travail est déjà une tâche de
 conception dure

   L'interblocage


   La   famine

   Etat   invalide                       7
Partager les états
 et la mutabilité
  des variables

                     8
L’orienté objet
   n’est pas
 dédiée pour
      faire
   de l’objet     9
La source principale
de ses problèmes est

  programmation
    impérative
                       10
PI VS FP
 Programmation    impérative est un
 paradigme de programmation qui décrit le
 calcul en termes de déclarations qui
 modifient l'état des programmes

 Laprogrammation fonctionnelle est un
 paradigme de programmation qui décrit le
 calcul de l'évaluation des fonctions
 mathématiques en évitant les états et la
 mutabilité                                 11
FONCTION PURE
   Composition de fonctions Pure

   Avec les mêmes inputs on a toujours le même
    résultat

   Boite noire :
        Pas de modifications
        Pas d’écriture de messages pour l’utilisateur

        Ni sur le disque




 Pas d’effet de bord
                                                         12
EXEMPLES
   f (x) = x2 + 1

       Une fonction pure retourne des valeurs et ne fait
        rien d’autres

   g (a; b; c) = (a + b) * (c / 2) + f (a )

   h (t) = h (t -1) + h (t -2 )

       Les fonctions pures se composent que des
                                                            13
        fonctions pures
Les langues qui
     encouragent
   l'utilisation des
fonctions pures sont
 appelés langages
     fonctionnels      14
   Les langages impératifs

       Description du calcul en termes de changements de
        l'état

       JAVA , C# , PHP

           Séquencement d’opérations et action sur les variables en
            mémoire



           Effet de bord



                                                                       15
L’affectation   est une source d’effet
 de bord

Les variables sont les causes des
 problèmes dans les
 environnements multi-thread

La  mutabilité ainsi que le partage
 d’ état n’est plus la mode
                                          16
Transparence référentielle


int n = 2;
int inc(int k) { n = n + k; return n; }
   incrémentation par effet de bord
inc(1) + inc(1)
   != 2 * inc (1 )


   Avec les variables on oublie le
   temps                                   17
x[t]= x0
x[t + 1] = x[t] + 1


A un instant donné, la valeur
 de x est immutable.
X est l’identité d’une séquence
 de valeurs dans le temps
                                   18
Acteurs
STM




           19
SCALA

        20
If I were to pick a language to use on the JVM
    today other than Java, it would be Scala.

       – James Gosling, creator of Java
                             http://www.adam-
    bien.com/roller/abien/entry/java_net_javaone_which_programming



                       My tip though for the long term replacement of javac is Scala.
                       I'm very impressed with it! I can honestly say if someone had
                        shown me the Programming in Scala book […] back in 2003
                                  I'd probably have never created Groovy.

                                            – James Strachan, creator of Groovy
                                       http://macstrac.blogspot.com/2009/04/scala-as-long-term-replacement-for.html




Scala, it must be stated, is the current heir apparent to the
  Java throne. No other language on the JVM seems as
 capable of being a "replacement for Java" as Scala, and
   the momentum behind Scala is now unquestionable.
                                                                                                                      21

                    – Charlies Nutter, JRuby lead
                     http://blog.headius.com/2009/04/future-part-one.html
“If Java programmers want to use features that
   aren't present in the language, I think they're
probably best off using another language that targets
   the JVM, such as Scala and Groovy“



                                        Joshua Bloch




                                                        22
23
SCALA

●   OO + FP
●   Java compatible
    ●   Compiles to Java bytecode
    ●   Existing libraries/frameworks
●   Simple
●   Objet Pure
●   Statiquement typé
                                        24
25
public class Person {
  private int age;
  private String name;

    public Person(int age, String name) {
      this.age = age;
      this.name = name;
    }

    public int getAge() {
      return this.age;
    }

    public void setAge(int age) {
      this.age = age;
    }

    public String getName() {
      return this.name;
    }

    public void setName(String name) {
      this.name = name;
    }
}                                           26
public class Person {
  private int age
  private String name

    public Person(int age, String name) {
      this.age = age
      this.name = name
    }

    public int getAge() {
      return this.age
    }

    public void setAge(int age) {
      this.age = age
    }

    public String getName() {
      return this.name
    }

    public void setName(String name) {
      this.name = name
    }
}                                           27
VARIABLES


  var i: Int = 42




                    28
VARIABLES


  var i = 42

  i = 3

  i = "Hello world!"   // erreur de
  compilation




                                      29
VALEURS


 val i = 42

 i = 3            // erreur
 de compilation




                              30
MÉTHODES


 def sum(a: Int, b: Int): Int = {
   return a + b
 }




                                    31
MÉTHODES


 def sum(a: Int, b: Int): Int = {
   a + b
 }




                                    32
MÉTHODES


 def sum(a: Int, b: Int) = {
   a + b
 }




                               33
MÉTHODES


 def sum(a: Int, b: Int) = a + b




                                   34
METHODS


 def sayHello(name: String) {
   println("Hello, " + name)
 }




                                35
METHODS


 "apple".charAt(0)   1 .+(2)

 "apple" charAt 0    1 + 2




                               36
COLLECTIONS


  val list   = List("apple", "orange", "banana")
  val map    = Map(1 -> "one", 2 -> "two")
  val array = Array(1, 2, 3, 4, 5)


  list(1)                        // orange
  map(2)                         // two
  array(3)                       // 4



                                                   37
FONCTIONS

Google collections:
 Predicate<Integer> even = new Predicate<Integer>() {
       @Override
       public boolean apply(Integer i) {
             return i % 2 == 0;
       }
 };

 List<Integer> numbers = … // 1, 2, 3, 4
 Iterable<Integer> evenNums =
   Iterables.filter(numbers, even);

 => [2, 4]
                                                    38
FONCTIONS

Scala collections:

 val even = (i: Int) => i % 2 == 0




 val numbers = List(1, 2, 3, 4)
 val evenNums = numbers.filter(even)


 => List(2, 4)
                                       39
FONCTIONS

Scala collections:




 val numbers = List(1, 2, 3, 4)
 val evenNums = numbers.filter((i: Int) => i % 2 == 0)


 => List(2, 4)
                                                    40
FONCTIONS

Scala collections:




 val numbers = List(1, 2, 3, 4)
 val evenNums = numbers.filter(i => i % 2 == 0)


 => List(2, 4)
                                                  41
FONCTIONS

Scala collections:




 val numbers = List(1, 2, 3, 4)
 val evenNums = numbers.filter(_ % 2 == 0)


 => List(2, 4)
                                             42
FONCTIONS

Scala collections:
 Predicate<Integer> even = new Predicate<Integer>() {
       @Override
       public boolean apply(Integer i) {
             return i % 2 == 0;
       }
 };

 val numbers = List(1, 2, 3, 4)
 val evenNums = numbers.filter(_ % 2 == 0)


 => List(2, 4)
                                                    43
CLASSES AND CONSTRUCTORS


  class Person(val age: Int)




                               44
CLASSES AND CONSTRUCTORS


  class Person(val age: Int) {

      def this() = this(42)

      var name: String = _

      override def toString = "My name is " + name
  }




                                                     45
CASE CLASSES

   case class Person(firstName: String, lastName: String)

   val me = Person("slim", "ouertani")
   val first = me.firstName
   val last = me.lastName

   if (me == Person(first, last)) {
      println("Found myself!")
      println(me)
    }


  Found myself!
  Person(slim,ouertani)                                     46
PATTERN MATCHING




  myObject   match {
    case 1   => println("First")
    case 2   => println("Second")
    case _   => println("Unknown")
  }




                                     47
PATTERN MATCHING



  myObject match {
    case i: Int => println("Found number " + i)
    case s: String => println("Found text " + s)
    case _ => println("Unknown")
  }




                                                   48
PATTERN MATCHING


  val email = """(.+)@(.+)""".r

  "scala@java.no" match {
    case email(name, domain) =>
      println("User " + name + " at " + domain)

      case x => println(x + " is not an email")
  }




                                                  49
PATTERN MATCHING (2)




                       50
PATTERN MATCHING (2 )




                        51
OPTION
    def div(a:Int)(b:Int):Option[Int] = if (b <= 0) None
    else if (a < b) Some(0)
    else Some(1 + div(a - b)(b).get)

    div(25)(5) // => Some(5)
    div(13)(0) // => None
    div(25)(-5) // => None


  div(13)(0) match {
          case Some(x) => println(x)
          case None     => println("Problems")
  } // => prints "Problems"

  div(25)(5) match {
         case Some(x) => println(x)
         case None    => println("Problems")               52
  } // => prints "5"
HIGHER-ORDER FUNCTIONS

   def apply(f: Int => String, v: Int) => f(v)



   class Decorator(left: String, right: String) {
       def layout[A](x: A) = left + x.toString() + right
   }
   object FunTest extends Application {
       def apply(f: Int => String, v: Int) = f(v)
       val decorator = new Decorator("[", "]")
       Console.println(apply(decorator.layout, 7))
   }

  [7]
                                                           53
NESTED FUNCTIONS

   object FilterTest extends Application {
        def filter(xs: List[Int], threshold: Int) = {
            def process(ys: List[Int]): List[Int] =
                 if (ys.isEmpty) ys
                 else if (ys.head < threshold) ys.head :: process(ys.tail)
                else process(ys.tail)
           process(xs)
       }
   Console.println(filter(List(1, 9, 2, 8, 3, 7, 4), 5))
   }



  List(1,2,3,4)
                                                                             54
CURRYING

   object CurryTest extends Application {
      def filter(xs: List[Int], p: Int => Boolean): List[Int] =
        if (xs.isEmpty) xs
        else if (p(xs.head)) xs.head :: filter(xs.tail, p)
        else filter(xs.tail, p)

       def modN(n: Int)(x: Int) = ((x % n) == 0)
       val nums = List(1, 2, 3, 4, 5, 6, 7, 8)
       println(filter(nums, modN(2)))
       println(filter(nums, modN(3)))
   }


  List(2,4,6,8)
  List(3,6)                                                       55
AUTOMATIC TYPE-DEPENDENT CLOSURE
CONSTRUCTION

   object TargetTest1 extends Application {
     def whileLoop(cond: => Boolean)(body: => Unit): Unit =
          if (cond) {
               body
               whileLoop(cond)(body)
          }
    var i = 10

       whileLoop (i > 0) {
         Console.println(i)
         i=i-1
       }
   }


                                                              56
TRY-WITH
RESOURCES




            57
58
59
60
61
Q&A




      62

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
 
Scala Bootcamp 1
Scala Bootcamp 1Scala Bootcamp 1
Scala Bootcamp 1
 
Scala 2013 review
Scala 2013 reviewScala 2013 review
Scala 2013 review
 
Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript
 
Testing for share
Testing for share Testing for share
Testing for share
 
Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...
Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...
Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...
 
Suit case class
Suit case classSuit case class
Suit case class
 
Core C#
Core C#Core C#
Core C#
 
Core java Essentials
Core java EssentialsCore java Essentials
Core java Essentials
 
Introduction to julia
Introduction to juliaIntroduction to julia
Introduction to julia
 
06slide
06slide06slide
06slide
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
C# programming
C# programming C# programming
C# programming
 
Jeop game-final-review
Jeop game-final-reviewJeop game-final-review
Jeop game-final-review
 
Joose @jsconf
Joose @jsconfJoose @jsconf
Joose @jsconf
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
 
Built in classes in java
Built in classes in javaBuilt in classes in java
Built in classes in java
 
Modul Praktek Java OOP
Modul Praktek Java OOP Modul Praktek Java OOP
Modul Praktek Java OOP
 

Ähnlich wie Programmation fonctionnelle Scala

Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvmArnaud Giuliani
 
Scala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian DragosScala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian DragosGenevaJUG
 
Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Cody Engel
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoMuhammad Abdullah
 
The Kotlin Programming Language, Svetlana Isakova
The Kotlin Programming Language, Svetlana IsakovaThe Kotlin Programming Language, Svetlana Isakova
The Kotlin Programming Language, Svetlana IsakovaVasil Remeniuk
 
Светлана Исакова «Язык Kotlin»
Светлана Исакова «Язык Kotlin»Светлана Исакова «Язык Kotlin»
Светлана Исакова «Язык Kotlin»e-Legion
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondMario Fusco
 
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Tudor Dragan
 
Introduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicoxIntroduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicoxDavid Rodenas
 
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingGarth Gilmour
 
Intro to scala
Intro to scalaIntro to scala
Intro to scalaJoe Zulli
 
Effective Java with Groovy & Kotlin - How Languages Influence Adoption of Goo...
Effective Java with Groovy & Kotlin - How Languages Influence Adoption of Goo...Effective Java with Groovy & Kotlin - How Languages Influence Adoption of Goo...
Effective Java with Groovy & Kotlin - How Languages Influence Adoption of Goo...Naresha K
 
MiamiJS - The Future of JavaScript
MiamiJS - The Future of JavaScriptMiamiJS - The Future of JavaScript
MiamiJS - The Future of JavaScriptCaridy Patino
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With ScalaMeetu Maltiar
 

Ähnlich wie Programmation fonctionnelle Scala (20)

Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvm
 
Workshop Scala
Workshop ScalaWorkshop Scala
Workshop Scala
 
Scala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian DragosScala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian Dragos
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demo
 
The Kotlin Programming Language, Svetlana Isakova
The Kotlin Programming Language, Svetlana IsakovaThe Kotlin Programming Language, Svetlana Isakova
The Kotlin Programming Language, Svetlana Isakova
 
Светлана Исакова «Язык Kotlin»
Светлана Исакова «Язык Kotlin»Светлана Исакова «Язык Kotlin»
Светлана Исакова «Язык Kotlin»
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
A bit about Scala
A bit about ScalaA bit about Scala
A bit about Scala
 
Introduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicoxIntroduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicox
 
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
Intro to scala
Intro to scalaIntro to scala
Intro to scala
 
Effective Java with Groovy & Kotlin - How Languages Influence Adoption of Goo...
Effective Java with Groovy & Kotlin - How Languages Influence Adoption of Goo...Effective Java with Groovy & Kotlin - How Languages Influence Adoption of Goo...
Effective Java with Groovy & Kotlin - How Languages Influence Adoption of Goo...
 
MiamiJS - The Future of JavaScript
MiamiJS - The Future of JavaScriptMiamiJS - The Future of JavaScript
MiamiJS - The Future of JavaScript
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 

Mehr von Slim Ouertani

Mehr von Slim Ouertani (18)

merged_document_3
merged_document_3merged_document_3
merged_document_3
 
Microservice architecture
Microservice architectureMicroservice architecture
Microservice architecture
 
MongoDb java
MongoDb javaMongoDb java
MongoDb java
 
OCJP
OCJPOCJP
OCJP
 
Effectuation: entrepreneurship for all
Effectuation: entrepreneurship for all Effectuation: entrepreneurship for all
Effectuation: entrepreneurship for all
 
Spring
SpringSpring
Spring
 
Principles of Reactive Programming
Principles of Reactive ProgrammingPrinciples of Reactive Programming
Principles of Reactive Programming
 
Functional Programming Principles in Scala
Functional Programming Principles in ScalaFunctional Programming Principles in Scala
Functional Programming Principles in Scala
 
Introduction to Cmmi for development
Introduction to Cmmi for development Introduction to Cmmi for development
Introduction to Cmmi for development
 
MongoDb java
MongoDb javaMongoDb java
MongoDb java
 
DBA MongoDb
DBA MongoDbDBA MongoDb
DBA MongoDb
 
SOA Trainer
SOA TrainerSOA Trainer
SOA Trainer
 
SOA Professional
SOA ProfessionalSOA Professional
SOA Professional
 
SOA Architect
SOA ArchitectSOA Architect
SOA Architect
 
PMP Score
PMP ScorePMP Score
PMP Score
 
PMP
PMPPMP
PMP
 
Xml & Java
Xml & JavaXml & Java
Xml & Java
 
Singleton Sum
Singleton SumSingleton Sum
Singleton Sum
 

Kürzlich hochgeladen

week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptxJonalynLegaspi2
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQuiz Club NITW
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptxmary850239
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationdeepaannamalai16
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWQuiz Club NITW
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxMan or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxDhatriParmar
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptxmary850239
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataBabyAnnMotar
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptxDhatriParmar
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Association for Project Management
 

Kürzlich hochgeladen (20)

Paradigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTAParadigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTA
 
week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptx
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdf
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentation
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITW
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
prashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Professionprashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Profession
 
Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"
 
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxMan or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped data
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
 

Programmation fonctionnelle Scala

  • 2. site: ouertani.com blog: Jtunisie jroller.com/ouertani mail: ouertani@gmail.com twitter: ouertani 2
  • 3. AGENDA I - Motivation II - Introduction à la PF III - Introduction à Scala 3
  • 4. 4
  • 5. MOTIVATION  Loi de Moore  Le nombre de transistors va doubler toute les deux années  Transistors  Performance CPU 5
  • 6. MOTIVATION Le futur et le présent du hardware est dans le parallélisme  Resteque quelques routines en séquentielles 6
  • 7. MAIS !  Diviser le travail est déjà une tâche de conception dure  L'interblocage  La famine  Etat invalide 7
  • 8. Partager les états et la mutabilité des variables 8
  • 9. L’orienté objet n’est pas dédiée pour faire de l’objet 9
  • 10. La source principale de ses problèmes est programmation impérative 10
  • 11. PI VS FP  Programmation impérative est un paradigme de programmation qui décrit le calcul en termes de déclarations qui modifient l'état des programmes  Laprogrammation fonctionnelle est un paradigme de programmation qui décrit le calcul de l'évaluation des fonctions mathématiques en évitant les états et la mutabilité 11
  • 12. FONCTION PURE  Composition de fonctions Pure  Avec les mêmes inputs on a toujours le même résultat  Boite noire :  Pas de modifications  Pas d’écriture de messages pour l’utilisateur  Ni sur le disque  Pas d’effet de bord 12
  • 13. EXEMPLES  f (x) = x2 + 1  Une fonction pure retourne des valeurs et ne fait rien d’autres  g (a; b; c) = (a + b) * (c / 2) + f (a )  h (t) = h (t -1) + h (t -2 )  Les fonctions pures se composent que des 13 fonctions pures
  • 14. Les langues qui encouragent l'utilisation des fonctions pures sont appelés langages fonctionnels 14
  • 15. Les langages impératifs  Description du calcul en termes de changements de l'état  JAVA , C# , PHP  Séquencement d’opérations et action sur les variables en mémoire  Effet de bord 15
  • 16. L’affectation est une source d’effet de bord Les variables sont les causes des problèmes dans les environnements multi-thread La mutabilité ainsi que le partage d’ état n’est plus la mode 16
  • 17. Transparence référentielle int n = 2; int inc(int k) { n = n + k; return n; }  incrémentation par effet de bord inc(1) + inc(1)  != 2 * inc (1 )  Avec les variables on oublie le temps 17
  • 18. x[t]= x0 x[t + 1] = x[t] + 1 A un instant donné, la valeur de x est immutable. X est l’identité d’une séquence de valeurs dans le temps 18
  • 20. SCALA 20
  • 21. If I were to pick a language to use on the JVM today other than Java, it would be Scala. – James Gosling, creator of Java http://www.adam- bien.com/roller/abien/entry/java_net_javaone_which_programming My tip though for the long term replacement of javac is Scala. I'm very impressed with it! I can honestly say if someone had shown me the Programming in Scala book […] back in 2003 I'd probably have never created Groovy. – James Strachan, creator of Groovy http://macstrac.blogspot.com/2009/04/scala-as-long-term-replacement-for.html Scala, it must be stated, is the current heir apparent to the Java throne. No other language on the JVM seems as capable of being a "replacement for Java" as Scala, and the momentum behind Scala is now unquestionable. 21 – Charlies Nutter, JRuby lead http://blog.headius.com/2009/04/future-part-one.html
  • 22. “If Java programmers want to use features that aren't present in the language, I think they're probably best off using another language that targets the JVM, such as Scala and Groovy“ Joshua Bloch 22
  • 23. 23
  • 24. SCALA ● OO + FP ● Java compatible ● Compiles to Java bytecode ● Existing libraries/frameworks ● Simple ● Objet Pure ● Statiquement typé 24
  • 25. 25
  • 26. public class Person { private int age; private String name; public Person(int age, String name) { this.age = age; this.name = name; } public int getAge() { return this.age; } public void setAge(int age) { this.age = age; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } } 26
  • 27. public class Person { private int age private String name public Person(int age, String name) { this.age = age this.name = name } public int getAge() { return this.age } public void setAge(int age) { this.age = age } public String getName() { return this.name } public void setName(String name) { this.name = name } } 27
  • 28. VARIABLES var i: Int = 42 28
  • 29. VARIABLES var i = 42 i = 3 i = "Hello world!" // erreur de compilation 29
  • 30. VALEURS val i = 42 i = 3 // erreur de compilation 30
  • 31. MÉTHODES def sum(a: Int, b: Int): Int = { return a + b } 31
  • 32. MÉTHODES def sum(a: Int, b: Int): Int = { a + b } 32
  • 33. MÉTHODES def sum(a: Int, b: Int) = { a + b } 33
  • 34. MÉTHODES def sum(a: Int, b: Int) = a + b 34
  • 35. METHODS def sayHello(name: String) { println("Hello, " + name) } 35
  • 36. METHODS "apple".charAt(0) 1 .+(2) "apple" charAt 0 1 + 2 36
  • 37. COLLECTIONS val list = List("apple", "orange", "banana") val map = Map(1 -> "one", 2 -> "two") val array = Array(1, 2, 3, 4, 5) list(1) // orange map(2) // two array(3) // 4 37
  • 38. FONCTIONS Google collections: Predicate<Integer> even = new Predicate<Integer>() { @Override public boolean apply(Integer i) { return i % 2 == 0; } }; List<Integer> numbers = … // 1, 2, 3, 4 Iterable<Integer> evenNums = Iterables.filter(numbers, even); => [2, 4] 38
  • 39. FONCTIONS Scala collections: val even = (i: Int) => i % 2 == 0 val numbers = List(1, 2, 3, 4) val evenNums = numbers.filter(even) => List(2, 4) 39
  • 40. FONCTIONS Scala collections: val numbers = List(1, 2, 3, 4) val evenNums = numbers.filter((i: Int) => i % 2 == 0) => List(2, 4) 40
  • 41. FONCTIONS Scala collections: val numbers = List(1, 2, 3, 4) val evenNums = numbers.filter(i => i % 2 == 0) => List(2, 4) 41
  • 42. FONCTIONS Scala collections: val numbers = List(1, 2, 3, 4) val evenNums = numbers.filter(_ % 2 == 0) => List(2, 4) 42
  • 43. FONCTIONS Scala collections: Predicate<Integer> even = new Predicate<Integer>() { @Override public boolean apply(Integer i) { return i % 2 == 0; } }; val numbers = List(1, 2, 3, 4) val evenNums = numbers.filter(_ % 2 == 0) => List(2, 4) 43
  • 44. CLASSES AND CONSTRUCTORS class Person(val age: Int) 44
  • 45. CLASSES AND CONSTRUCTORS class Person(val age: Int) { def this() = this(42) var name: String = _ override def toString = "My name is " + name } 45
  • 46. CASE CLASSES case class Person(firstName: String, lastName: String) val me = Person("slim", "ouertani") val first = me.firstName val last = me.lastName if (me == Person(first, last)) { println("Found myself!") println(me) } Found myself! Person(slim,ouertani) 46
  • 47. PATTERN MATCHING myObject match { case 1 => println("First") case 2 => println("Second") case _ => println("Unknown") } 47
  • 48. PATTERN MATCHING myObject match { case i: Int => println("Found number " + i) case s: String => println("Found text " + s) case _ => println("Unknown") } 48
  • 49. PATTERN MATCHING val email = """(.+)@(.+)""".r "scala@java.no" match { case email(name, domain) => println("User " + name + " at " + domain) case x => println(x + " is not an email") } 49
  • 52. OPTION def div(a:Int)(b:Int):Option[Int] = if (b <= 0) None else if (a < b) Some(0) else Some(1 + div(a - b)(b).get) div(25)(5) // => Some(5) div(13)(0) // => None div(25)(-5) // => None div(13)(0) match { case Some(x) => println(x) case None => println("Problems") } // => prints "Problems" div(25)(5) match { case Some(x) => println(x) case None => println("Problems") 52 } // => prints "5"
  • 53. HIGHER-ORDER FUNCTIONS def apply(f: Int => String, v: Int) => f(v) class Decorator(left: String, right: String) { def layout[A](x: A) = left + x.toString() + right } object FunTest extends Application { def apply(f: Int => String, v: Int) = f(v) val decorator = new Decorator("[", "]") Console.println(apply(decorator.layout, 7)) } [7] 53
  • 54. NESTED FUNCTIONS object FilterTest extends Application { def filter(xs: List[Int], threshold: Int) = { def process(ys: List[Int]): List[Int] = if (ys.isEmpty) ys else if (ys.head < threshold) ys.head :: process(ys.tail) else process(ys.tail) process(xs) } Console.println(filter(List(1, 9, 2, 8, 3, 7, 4), 5)) } List(1,2,3,4) 54
  • 55. CURRYING object CurryTest extends Application { def filter(xs: List[Int], p: Int => Boolean): List[Int] = if (xs.isEmpty) xs else if (p(xs.head)) xs.head :: filter(xs.tail, p) else filter(xs.tail, p) def modN(n: Int)(x: Int) = ((x % n) == 0) val nums = List(1, 2, 3, 4, 5, 6, 7, 8) println(filter(nums, modN(2))) println(filter(nums, modN(3))) } List(2,4,6,8) List(3,6) 55
  • 56. AUTOMATIC TYPE-DEPENDENT CLOSURE CONSTRUCTION object TargetTest1 extends Application { def whileLoop(cond: => Boolean)(body: => Unit): Unit = if (cond) { body whileLoop(cond)(body) } var i = 10 whileLoop (i > 0) { Console.println(i) i=i-1 } } 56
  • 58. 58
  • 59. 59
  • 60. 60
  • 61. 61
  • 62. Q&A 62