SlideShare ist ein Scribd-Unternehmen logo
1 von 55
Three languages
                        in thirty minutes or so...



                                               Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Three languages


    Who are we?
              • Fabio   Marinelli
                        •   Project manager @ Poste Italiane
                        •   twitter @fmarinelli
              • Sergio      Bossa
                        •   Senior Software Engineer @ Bwin Italy
                        •   (Micro-)Blogger @sbtourist
              • Massimiliano         Dessí
                        •   Architect/Developer @ Pronetics/Sourcesense
                        •   twitter @desmax74

                                                                      Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Three languages


    Why this challenge?
              More languages means:
                      • Right tool for your problems
                      • Different mindsets improve your problem solving
                           skills
                      • ... and it’s cool!




                                                                Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Three languages


    How we do this? Let us talk about ...
                                                Variables
                       Data structures
                                         Objects and Functions

                                Flow control

                        Concurrency




                                                             Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Javascript
                              Fabio Marinelli



                                          Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Javascript - Variables

    • Loosely typed language

    • Types: number, string, boolean, function and object

    • Everything is an Object

    • Function scoped!!




                                                            Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Javascript - Variables


    Declare and initialize:
    var a;

    var a = 1; //number

    var a = “string”;

    var a = ‘string’;

    var a = true || false;

    var a = {name:{first:”Fabio”, last:”M.”}, age:33};

    var a = function (text) { alert(text);};




                                                         Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Javascript - Variables


      False values:
              • false
              •   null
              •   undefined
              •   empty string
              •   0
              •   NaN


                                                  Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Javascript - Flow control


                      Is this C?
                      if (expression) { ... } else { ... }

                      while (expression) { ... }

                      do { ... } while (expression);

                      for (initialization; condition; increment) { ... }

                      for (name in object) { ... }

                      try { ... } catch (variable) { ... }




                                                 9                    Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Javascript - Data structures


                      Javascript object is a mutable key-value map.
                      var object = {
                           “name”: value,
                           “other”: function (text) {
                               alert(text);
                           }
                      };

                      Values can be also a function. Everything is an object.


                                                    10                      Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Javascript - Objects and functions

                      Functions are first class objects
                      var numbers = [1,5,2,12,7,9];
                      numbers.sort(function(a, b) {
                        return a-b;
                      });
                      //Output a sorted array
                      //1,2,5,7,9,12
                      numbers.sort(function(a, b) {
                        return b-a;
                      });
                      //Output a sorted array
                      //12,9,7,5,2,1




                                                11              Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Javascript - Objects and functions

                      Functions have access to context in which they are created
                      var counter = function (value) {
                           return {
                                getAndInc : function () { return value++; }
                           };
                      };
                      var myCounter = counter(1);
                      alert(myCounter.getAndInc()); // Output 1
                      alert(myCounter.getAndInc()); // Output 2

                                              This is called closure


                                                     12                       Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Javascript - Objects and functions

                      Let’s use the closure.
                      var Foo = function() {
                         var value = 1; //private to the function
                         this.inc = function() { ++value; };
                         this.print = function() { alert(value); };
                         return this;
                      };

                      var b = new Foo();
                      b.print(); //Output 1
                      b.inc();
                      b.print(); //Output 2

                      alert(b.value); //undefined




                                                13                    Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Javascript - Objects and functions

                      Javascript is a prototypal language
                      var Foo = function() {
                         this.value = 1; //public value
                         return this;
                      };
                      Foo.prototype.inc = function() {
                         ++this.value;
                      };
                      Foo.prototype.print = function() {
                         alert(this.value);
                      };
                      var b = new Foo();
                      b.print(); //Output 1
                      b.inc();
                      b.print(); //Output 2


                                                14              Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Javascript - Objects and functions

                      Developer can add responsibilities to any object
                      var b = 1;
                      Number.prototype.inc = function() {
                         return new Number(this+1);
                      };
                      Number.prototype.print = function() {
                         alert(this);
                      };
                      b.print();
                      //Output 1
                      b.inc().print();
                      //Output 2

                      Again, everything is an object.

                                                15                       Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Javascript - Concurrency



                      • Specification says nothing about concurrency
                      • Browser engine is single threaded
                      • Node.js offers event model concurrency




                                               16                      Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Javascript - Concurrency



                                            Node.js
                      var sys = require("sys");
                      setTimeout(function () {
                        sys.puts("world");
                      }, 1000);
                      sys.puts("hello");


                          Evented model with non blocking I/O


                                              17            Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Javascript - Concurrency



                                           ...output
                      hello

                                        after 1 second
                      world




                                              18         Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Clojure
                           Sergio Bossa



                                    Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Clojure - Three Words


                                   Homoiconic
                                    Functional
                                     Dynamic



                                                 Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Clojure - Basics


                      From “Programming Clojure”, by Stuart Halloway:
                           Form              Example(s)
                           Boolean           true, false
                           Character         a
                           Keyword           :tag, :doc
                           List              (1 2 3), (println “foo”)
                           Map               (:name “Bill”, :age 42)
                           Nil               nil
                           Number            1, 4.2
                           Set               #(:snap :crackle :pop)
                           String            “hello”
                           Symbol            user/foo, java.lang.String
                           Vector            [1 2 3]




                                                                          Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Clojure - Functions (Definition)


                                        Standard
                      (defn my-fun [name] (println “Hello, ” name “!”))

                                       Anonymous I
                          (fn [name] (println “Hello, ” name “!”))

                                       Anonymous II
                                 #(println “Hello, ” %1 “!”)

                                                                          Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Clojure - Functions (Invocation)


                                          Standard
                                      (my-fun “Sergio”)

                                         Anonymous I
                      ((fn [name] (println “Hello, ” name “!”)) “Sergio”)

                                        Anonymous II
                            (#(println “Hello, ” %1 “!”) “Sergio”)

                                                                            Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Clojure - Variables (Basics)


                                  Namespace-scoped
                               (def my-variable “value”)

                                    Locally-scoped
                              (let [my-variable “value”])

                                          Use
                                 (println my-variable)

                                                            Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Clojure - Variables (Destructuring)


                                            Definition
                      (defn my-fun [{name:name}] (println “Hello, ” name “!”))

                                           Invocation
                              (my-fun {:name “Sergio” :city “Rome”})

                                             Result
                                         => Hello, Sergio!

                                                                          Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Clojure - Control Structures (Conditionals)


                                    Single choice
                                (when (= n 0) “zero!”)

                                     Double choice
                            (if (= n 0) “zero!” “not zero!”)

                                  Multiple choice
      (cond (< n 0) ‘less than zero!’ (= n 0) ‘zero!’ :else ‘greater than zero!’)

                                                                      Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Clojure - Control Structures (Loops)


                                              NO FOR LOOPS
                                                (almost)

                                            Explicit recursion
          (defn sum-a [array] (loop [a array s 0] (if (empty? a) s (recur (rest a) (+ s (first a))))))




                                                                                           Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Clojure - Data Structures (Concepts)


                        Everything is (treated as) a Sequence

                                      Immutable

                                   (Possibly) Lazy




                                                                Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Clojure - Data structures (Basics)


                                               Essentials
                                      first, rest, cons, conj, into

                                          Comprehension
                                (for [m [1 2 3] n [4 5 6]] (+ m n))

                                              Map/Reduce
               (reduce #(merge-with + %1 %2) (map #(hash-map %1 1) [‘pippo’ ‘pluto’ ‘pluto’]))


                                                                                       Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Clojure - Concurrency (Concepts)


                                   Explicit support

                                     Coordinated

                                    Uncoordinated

                                    Asynchronous



                                                         Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Clojure - Concurrency (Coordinated)


                                    References (aka STM)
                      (def person (ref {:name ‘Sergio Bossa’ :age 28}))

                                            Get
                                          @person

                                           Update
                           (dosync (alter person conj {:age 29}))

                                                                          Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Clojure - Concurrency (Uncoordinated)


                                            Atoms
                      (def person (atom {:name ‘Sergio Bossa’ :age 28}))

                                            Get
                                          @person

                                           Update
                                (swap! person conj {:age 29})

                                                                       Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Clojure - Concurrency (Asynchronous)


                                            Agents
                      (def person (agent {:name ‘Sergio Bossa’ :age 28}))

                                             Get
                                           @person

                                           Update
                                 (send person conj {:age 29})

                                                                        Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Clojure - Final Words


                                        KISS
                                     Powerful
                                   Concurrent


                                                Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Scala
                         Massimiliano Dessì



                                        Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Scala variables


                      Scala is a hybrid functional/object-oriented language.
             Scala runs on the JVM and in- teroperates with all Java libraries.
                             Scala is statically typed with inference
                Powerful language for designing internal DSLs (DSL In Action)
                      Good for Event Driven Architecture/CQRS (Akka actors)



                                                                          Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Scala variables


    In functional programming, variables' values are immutable, as
        consequence of the mathematical orientation
    Immutability = no side effect
    No side effect = no shared state, better concurrency


    Scala allows you to decide whether a variable is immutable or not.


                                                                 Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Variable declaration


    An immutable “variable” it's declared with val keyword (Value Object),
       the reference can not be changed, but the object itself can be
       modified.
    val myArray[String]:Array= new Array(3)
    array: Array[String] = Array(null, null, null)

    A mutable “variable” it's declared with var keyword, You can assign a
       new value to a var as often as you want
    var price: Double = 100
    price = 10


                                                                 Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Control structures
     Function and     if, while, for, try, match          in the base syntax, higher-level control
     structure other than these in the libraries

    •Function
    Functional programming is based on the behavior of functions in the mathematical sense, with
        all the implications that starting point implies.
    (x: Int) => x + 1

    functions have no side effects
    When a function takes other functions as arguments or returns a function, it is called a higher-
       order function.
    List(1, 2, 3, 4, 5) reduceLeft { _ * _ }



                                                                                       Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Control structures
    • Closure
       var factor = 3
       val multiplier = (i:Int) => i * factor

    • For Comphresion
       val dogs = List("Lassie", "Rex", "Rin tin tin")
       for (dog <- dogs) println(dog)

    • Currying
       def add(x:Int) = (y:Int) => x + y
       println(add(2)(3))
       val addCurried = curried(add _)



                                                         Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Control structures
    • Composition
       val f = (x: Int) => x + 1
       val g = (x: Int) => x * 3.3
       val h = (x: Double) => x + 0.1
       val result = h compose g compose f



    • Pattern matching
       def factorial(i: BigInt): BigInt = i match {
            case _ if i == 1 => i
            case _ => i * factorial(i - 1)
       }




                                                      Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Control structures
    • Precondition
       class Rational(n: Int, d: Int) {
            require(d != 0) ….
       }

    • Filtering
       for (file <- filesHere if file.getName.endsWith(".scala"))

    • Folding and reducing
       List(1,2,3,4,5,6) reduceLeft(_ + _)
       List(1,2,3,4,5,6).foldLeft(10)(_ * _)




                                                              Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Specification
    class ElementSpec extends FlatSpec with ShouldMatchers {
         "A UniformElement" should
         "have a width equal to the passed value" in {
                 val ele = elem('x', 2, 3)
                 ele.width should be (2)
         }
         it should "have a height equal to the passed value" in {
                 val ele = elem('x', 2, 3)
                 ele.height should be (3)
         }
         it should "throw an IAE if passed a negative width" in {
                 evaluating {
                      elem('x', -2, 3) } should produce [IllegalArgumentException]
             }
    }


                                                                         Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Collection


    • Sequences (List, Array, ListBuffer) Immutable and mutable
    • Set and Maps Immutable and mutable
    • Tuples,         a tuple combines a fixed number of items together
            (1, "hello", Console)




                                                                          Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Concurrency
    • Actor and messages
    class McQueen extends Actor {
             loop {
                      react {
                                case "how many?" => {
                                    println("I've got " + mailboxSize.toString
                                    + " messages in my mailbox.")
                      }
         }
    }


    Every Actor has a mailbox in which messages sent to that Actor are
    queued
                                                                           Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Concurrency
    Actors can receive any sort of object as a message
    val fussyActor = actor {
         loop {
              receive {
                      case s: String => println("I got a String: " + s)
                      case i: Int => println("I got an Int: " + i.toString)
                      case _ => println("I have no idea what I just got.")
              }
         }
    }
    fussyActor ! "hi there"
    fussyActor ! 23
    fussyActor ! 3.33



                                                                          Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Concurrency
    A strategy to keep your Actor-based code asynchronous is the use of futures
    A future is a placeholder object for a value that hasn’t yet been returned from an asyn-
        chronous process
    the double-bang (!!) on Actor causes operation to return a future
    /**
           * Asynchronous message send. Send-and-receive eventually. Waits
           on a Future for the reply message.
           * If recevied within the Actor default timeout interval then it
           returns Some(result) and
            *         if a timeout
            * has occured None.
            */
         def !!(message: T): Box[R]




                                                                                       Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Trait
    Traits are like interfaces in Java, but they can also have method
       implementations and even fields.
    Objects are constructed by mixin composition
    class Animal trait HasLegs
    class Frog extends Animal with Philosophical with HasLegs {
         override def toString = "green"
    }




                                                                   Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Now ... what?!?!
                           Quick (really!) start



                                             Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Quickstart - Javascript


    • Download and install Nodejs.
    • Write your first example.js
        var sys = require("sys");
        setTimeout(function () { sys.puts("world"); }, 1000);
        sys.puts("hello");

    • Run example
        % node example.js

    • Or easily start node console by running
        % node-repl



                                                                Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Quickstart - Clojure

                                    Download JDK >= 5.x and Clojure jars
                 http://www.sun.com http://www.oracle.com http://clojure.org/downloads
                                 Download and install Leiningen build tool
                               http://github.com/technomancy/leiningen
                                            $> lein self-install
                                            Start new project
                                         $> lein new my-project
                                            Start project REPL
                                               $> lein repl

                                                                                    Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Quickstart - Scala

              The SBT can be used for Scala projects as Maven for Java Projects. SBT enable
              Dependency management. It support multiple project/subproject, and mixed project
              Scala/Java. It also has built-in support for generating Scaladocs and for testing with
              ScalaTest, Specs, and ScalaCheck.
              class Project(info: ProjectInfo) extends DefaultWebProject(info) with IdeaProject {

                  lazy val scalaTest = "org.scalatest" % "scalatest" % "1.3" % "test"

                  lazy val scalateCore = "org.fusesource.scalate" % "scalate-core" % "1.4.0"

                  lazy val casbah = "com.mongodb.casbah" %% "casbah" % "2.0.3"

                  lazy val salat = "com.novus" %% "salat" % "0.0.5"

                  lazy val junit = "junit" % "junit" % "4.8.2" % "test"

                  lazy val sfl4japi = "org.slf4j" % "slf4j-api" % "1.6.1" % "runtime"

                  lazy val logback = "ch.qos.logback" % "logback-classic" % "0.9.27"

                val scalaTools = "Scala Tools Repository snapshot" at "http://nexus.scala-tools.org/content/
              repositories/public/"

              }




                                                                                                        Bossa - Dessì - Marinelli
sabato 5 marzo 2011
Quickstart - Scala

              1) Download JDK >= 5.x (and set the env vars) http://www.oracle.com
              2) Download Scala installer jar http://www.scala-lang.org/downloads
              and set the environment $SCALA_HOME (ie: /usr/local/share/scala) and
              $PATH:$SCALA_HOME/bin
              3) Use scala with
              -shell
              -Intellij idea community with scala plugin
              - eclipse with scala plugin



                                                                                     Bossa - Dessì - Marinelli
sabato 5 marzo 2011
References

                              Bossa - Dessì - Marinelli
sabato 5 marzo 2011
References

              • Javascript
              •   Douglas Crockford (Javascript the good parts) http://www.crockford.com/
              •   Nodejs http://nodejs.org/
              •   John Resig (JQuery, Pro Javascript and Javascript secrets books) http://ejohn.org/


              • Clojure
              •   Clojure Web Site: http://clojure.org
              •   Clojure Online Docs: http://clojuredocs.org/
              •   Programming Clojure Book: http://pragprog.com/titles/shcloj/programming-clojure


              • Scala
              •   Scala site : http://www.scala-lang.org
              •   Scala docs: http://www.scala-lang.org/node/197
              •   Scala Books : http://www.scala-lang.org/node/959




                                                                                                       Bossa - Dessì - Marinelli
sabato 5 marzo 2011

Weitere ähnliche Inhalte

Mehr von Codemotion

Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...Codemotion
 
Pompili - From hero to_zero: The FatalNoise neverending story
Pompili - From hero to_zero: The FatalNoise neverending storyPompili - From hero to_zero: The FatalNoise neverending story
Pompili - From hero to_zero: The FatalNoise neverending storyCodemotion
 
Pastore - Commodore 65 - La storia
Pastore - Commodore 65 - La storiaPastore - Commodore 65 - La storia
Pastore - Commodore 65 - La storiaCodemotion
 
Pennisi - Essere Richard Altwasser
Pennisi - Essere Richard AltwasserPennisi - Essere Richard Altwasser
Pennisi - Essere Richard AltwasserCodemotion
 
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...Codemotion
 
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019Codemotion
 
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019Codemotion
 
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Francesco Baldassarri  - Deliver Data at Scale - Codemotion Amsterdam 2019 - Francesco Baldassarri  - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 - Codemotion
 
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...Codemotion
 
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...Codemotion
 
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...Codemotion
 
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...Codemotion
 
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019Codemotion
 
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019Codemotion
 
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019Codemotion
 
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...Codemotion
 
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...Codemotion
 
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019Codemotion
 
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019Codemotion
 
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019Codemotion
 

Mehr von Codemotion (20)

Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
 
Pompili - From hero to_zero: The FatalNoise neverending story
Pompili - From hero to_zero: The FatalNoise neverending storyPompili - From hero to_zero: The FatalNoise neverending story
Pompili - From hero to_zero: The FatalNoise neverending story
 
Pastore - Commodore 65 - La storia
Pastore - Commodore 65 - La storiaPastore - Commodore 65 - La storia
Pastore - Commodore 65 - La storia
 
Pennisi - Essere Richard Altwasser
Pennisi - Essere Richard AltwasserPennisi - Essere Richard Altwasser
Pennisi - Essere Richard Altwasser
 
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
 
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
 
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
 
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Francesco Baldassarri  - Deliver Data at Scale - Codemotion Amsterdam 2019 - Francesco Baldassarri  - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 -
 
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
 
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
 
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
 
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
 
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
 
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
 
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
 
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
 
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
 
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
 
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
 
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
 

Kürzlich hochgeladen

08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdfChristopherTHyatt
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 

Kürzlich hochgeladen (20)

08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 

Three Languages in Thirty Minutes (or so)

  • 1. Three languages in thirty minutes or so... Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 2. Three languages Who are we? • Fabio Marinelli • Project manager @ Poste Italiane • twitter @fmarinelli • Sergio Bossa • Senior Software Engineer @ Bwin Italy • (Micro-)Blogger @sbtourist • Massimiliano Dessí • Architect/Developer @ Pronetics/Sourcesense • twitter @desmax74 Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 3. Three languages Why this challenge? More languages means: • Right tool for your problems • Different mindsets improve your problem solving skills • ... and it’s cool! Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 4. Three languages How we do this? Let us talk about ... Variables Data structures Objects and Functions Flow control Concurrency Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 5. Javascript Fabio Marinelli Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 6. Javascript - Variables • Loosely typed language • Types: number, string, boolean, function and object • Everything is an Object • Function scoped!! Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 7. Javascript - Variables Declare and initialize: var a; var a = 1; //number var a = “string”; var a = ‘string’; var a = true || false; var a = {name:{first:”Fabio”, last:”M.”}, age:33}; var a = function (text) { alert(text);}; Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 8. Javascript - Variables False values: • false • null • undefined • empty string • 0 • NaN Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 9. Javascript - Flow control Is this C? if (expression) { ... } else { ... } while (expression) { ... } do { ... } while (expression); for (initialization; condition; increment) { ... } for (name in object) { ... } try { ... } catch (variable) { ... } 9 Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 10. Javascript - Data structures Javascript object is a mutable key-value map. var object = { “name”: value, “other”: function (text) { alert(text); } }; Values can be also a function. Everything is an object. 10 Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 11. Javascript - Objects and functions Functions are first class objects var numbers = [1,5,2,12,7,9]; numbers.sort(function(a, b) { return a-b; }); //Output a sorted array //1,2,5,7,9,12 numbers.sort(function(a, b) { return b-a; }); //Output a sorted array //12,9,7,5,2,1 11 Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 12. Javascript - Objects and functions Functions have access to context in which they are created var counter = function (value) { return { getAndInc : function () { return value++; } }; }; var myCounter = counter(1); alert(myCounter.getAndInc()); // Output 1 alert(myCounter.getAndInc()); // Output 2 This is called closure 12 Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 13. Javascript - Objects and functions Let’s use the closure. var Foo = function() { var value = 1; //private to the function this.inc = function() { ++value; }; this.print = function() { alert(value); }; return this; }; var b = new Foo(); b.print(); //Output 1 b.inc(); b.print(); //Output 2 alert(b.value); //undefined 13 Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 14. Javascript - Objects and functions Javascript is a prototypal language var Foo = function() { this.value = 1; //public value return this; }; Foo.prototype.inc = function() { ++this.value; }; Foo.prototype.print = function() { alert(this.value); }; var b = new Foo(); b.print(); //Output 1 b.inc(); b.print(); //Output 2 14 Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 15. Javascript - Objects and functions Developer can add responsibilities to any object var b = 1; Number.prototype.inc = function() { return new Number(this+1); }; Number.prototype.print = function() { alert(this); }; b.print(); //Output 1 b.inc().print(); //Output 2 Again, everything is an object. 15 Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 16. Javascript - Concurrency • Specification says nothing about concurrency • Browser engine is single threaded • Node.js offers event model concurrency 16 Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 17. Javascript - Concurrency Node.js var sys = require("sys"); setTimeout(function () { sys.puts("world"); }, 1000); sys.puts("hello"); Evented model with non blocking I/O 17 Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 18. Javascript - Concurrency ...output hello after 1 second world 18 Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 19. Clojure Sergio Bossa Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 20. Clojure - Three Words Homoiconic Functional Dynamic Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 21. Clojure - Basics From “Programming Clojure”, by Stuart Halloway: Form Example(s) Boolean true, false Character a Keyword :tag, :doc List (1 2 3), (println “foo”) Map (:name “Bill”, :age 42) Nil nil Number 1, 4.2 Set #(:snap :crackle :pop) String “hello” Symbol user/foo, java.lang.String Vector [1 2 3] Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 22. Clojure - Functions (Definition) Standard (defn my-fun [name] (println “Hello, ” name “!”)) Anonymous I (fn [name] (println “Hello, ” name “!”)) Anonymous II #(println “Hello, ” %1 “!”) Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 23. Clojure - Functions (Invocation) Standard (my-fun “Sergio”) Anonymous I ((fn [name] (println “Hello, ” name “!”)) “Sergio”) Anonymous II (#(println “Hello, ” %1 “!”) “Sergio”) Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 24. Clojure - Variables (Basics) Namespace-scoped (def my-variable “value”) Locally-scoped (let [my-variable “value”]) Use (println my-variable) Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 25. Clojure - Variables (Destructuring) Definition (defn my-fun [{name:name}] (println “Hello, ” name “!”)) Invocation (my-fun {:name “Sergio” :city “Rome”}) Result => Hello, Sergio! Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 26. Clojure - Control Structures (Conditionals) Single choice (when (= n 0) “zero!”) Double choice (if (= n 0) “zero!” “not zero!”) Multiple choice (cond (< n 0) ‘less than zero!’ (= n 0) ‘zero!’ :else ‘greater than zero!’) Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 27. Clojure - Control Structures (Loops) NO FOR LOOPS (almost) Explicit recursion (defn sum-a [array] (loop [a array s 0] (if (empty? a) s (recur (rest a) (+ s (first a)))))) Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 28. Clojure - Data Structures (Concepts) Everything is (treated as) a Sequence Immutable (Possibly) Lazy Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 29. Clojure - Data structures (Basics) Essentials first, rest, cons, conj, into Comprehension (for [m [1 2 3] n [4 5 6]] (+ m n)) Map/Reduce (reduce #(merge-with + %1 %2) (map #(hash-map %1 1) [‘pippo’ ‘pluto’ ‘pluto’])) Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 30. Clojure - Concurrency (Concepts) Explicit support Coordinated Uncoordinated Asynchronous Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 31. Clojure - Concurrency (Coordinated) References (aka STM) (def person (ref {:name ‘Sergio Bossa’ :age 28})) Get @person Update (dosync (alter person conj {:age 29})) Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 32. Clojure - Concurrency (Uncoordinated) Atoms (def person (atom {:name ‘Sergio Bossa’ :age 28})) Get @person Update (swap! person conj {:age 29}) Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 33. Clojure - Concurrency (Asynchronous) Agents (def person (agent {:name ‘Sergio Bossa’ :age 28})) Get @person Update (send person conj {:age 29}) Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 34. Clojure - Final Words KISS Powerful Concurrent Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 35. Scala Massimiliano Dessì Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 36. Scala variables Scala is a hybrid functional/object-oriented language. Scala runs on the JVM and in- teroperates with all Java libraries. Scala is statically typed with inference Powerful language for designing internal DSLs (DSL In Action) Good for Event Driven Architecture/CQRS (Akka actors) Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 37. Scala variables In functional programming, variables' values are immutable, as consequence of the mathematical orientation Immutability = no side effect No side effect = no shared state, better concurrency Scala allows you to decide whether a variable is immutable or not. Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 38. Variable declaration An immutable “variable” it's declared with val keyword (Value Object), the reference can not be changed, but the object itself can be modified. val myArray[String]:Array= new Array(3) array: Array[String] = Array(null, null, null) A mutable “variable” it's declared with var keyword, You can assign a new value to a var as often as you want var price: Double = 100 price = 10 Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 39. Control structures Function and if, while, for, try, match in the base syntax, higher-level control structure other than these in the libraries •Function Functional programming is based on the behavior of functions in the mathematical sense, with all the implications that starting point implies. (x: Int) => x + 1 functions have no side effects When a function takes other functions as arguments or returns a function, it is called a higher- order function. List(1, 2, 3, 4, 5) reduceLeft { _ * _ } Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 40. Control structures • Closure var factor = 3 val multiplier = (i:Int) => i * factor • For Comphresion val dogs = List("Lassie", "Rex", "Rin tin tin") for (dog <- dogs) println(dog) • Currying def add(x:Int) = (y:Int) => x + y println(add(2)(3)) val addCurried = curried(add _) Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 41. Control structures • Composition val f = (x: Int) => x + 1 val g = (x: Int) => x * 3.3 val h = (x: Double) => x + 0.1 val result = h compose g compose f • Pattern matching def factorial(i: BigInt): BigInt = i match { case _ if i == 1 => i case _ => i * factorial(i - 1) } Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 42. Control structures • Precondition class Rational(n: Int, d: Int) { require(d != 0) …. } • Filtering for (file <- filesHere if file.getName.endsWith(".scala")) • Folding and reducing List(1,2,3,4,5,6) reduceLeft(_ + _) List(1,2,3,4,5,6).foldLeft(10)(_ * _) Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 43. Specification class ElementSpec extends FlatSpec with ShouldMatchers { "A UniformElement" should "have a width equal to the passed value" in { val ele = elem('x', 2, 3) ele.width should be (2) } it should "have a height equal to the passed value" in { val ele = elem('x', 2, 3) ele.height should be (3) } it should "throw an IAE if passed a negative width" in { evaluating { elem('x', -2, 3) } should produce [IllegalArgumentException] } } Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 44. Collection • Sequences (List, Array, ListBuffer) Immutable and mutable • Set and Maps Immutable and mutable • Tuples, a tuple combines a fixed number of items together (1, "hello", Console) Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 45. Concurrency • Actor and messages class McQueen extends Actor { loop { react { case "how many?" => { println("I've got " + mailboxSize.toString + " messages in my mailbox.") } } } Every Actor has a mailbox in which messages sent to that Actor are queued Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 46. Concurrency Actors can receive any sort of object as a message val fussyActor = actor { loop { receive { case s: String => println("I got a String: " + s) case i: Int => println("I got an Int: " + i.toString) case _ => println("I have no idea what I just got.") } } } fussyActor ! "hi there" fussyActor ! 23 fussyActor ! 3.33 Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 47. Concurrency A strategy to keep your Actor-based code asynchronous is the use of futures A future is a placeholder object for a value that hasn’t yet been returned from an asyn- chronous process the double-bang (!!) on Actor causes operation to return a future /** * Asynchronous message send. Send-and-receive eventually. Waits on a Future for the reply message. * If recevied within the Actor default timeout interval then it returns Some(result) and * if a timeout * has occured None. */ def !!(message: T): Box[R] Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 48. Trait Traits are like interfaces in Java, but they can also have method implementations and even fields. Objects are constructed by mixin composition class Animal trait HasLegs class Frog extends Animal with Philosophical with HasLegs { override def toString = "green" } Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 49. Now ... what?!?! Quick (really!) start Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 50. Quickstart - Javascript • Download and install Nodejs. • Write your first example.js var sys = require("sys"); setTimeout(function () { sys.puts("world"); }, 1000); sys.puts("hello"); • Run example % node example.js • Or easily start node console by running % node-repl Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 51. Quickstart - Clojure Download JDK >= 5.x and Clojure jars http://www.sun.com http://www.oracle.com http://clojure.org/downloads Download and install Leiningen build tool http://github.com/technomancy/leiningen $> lein self-install Start new project $> lein new my-project Start project REPL $> lein repl Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 52. Quickstart - Scala The SBT can be used for Scala projects as Maven for Java Projects. SBT enable Dependency management. It support multiple project/subproject, and mixed project Scala/Java. It also has built-in support for generating Scaladocs and for testing with ScalaTest, Specs, and ScalaCheck. class Project(info: ProjectInfo) extends DefaultWebProject(info) with IdeaProject { lazy val scalaTest = "org.scalatest" % "scalatest" % "1.3" % "test" lazy val scalateCore = "org.fusesource.scalate" % "scalate-core" % "1.4.0" lazy val casbah = "com.mongodb.casbah" %% "casbah" % "2.0.3" lazy val salat = "com.novus" %% "salat" % "0.0.5" lazy val junit = "junit" % "junit" % "4.8.2" % "test" lazy val sfl4japi = "org.slf4j" % "slf4j-api" % "1.6.1" % "runtime" lazy val logback = "ch.qos.logback" % "logback-classic" % "0.9.27" val scalaTools = "Scala Tools Repository snapshot" at "http://nexus.scala-tools.org/content/ repositories/public/" } Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 53. Quickstart - Scala 1) Download JDK >= 5.x (and set the env vars) http://www.oracle.com 2) Download Scala installer jar http://www.scala-lang.org/downloads and set the environment $SCALA_HOME (ie: /usr/local/share/scala) and $PATH:$SCALA_HOME/bin 3) Use scala with -shell -Intellij idea community with scala plugin - eclipse with scala plugin Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 54. References Bossa - Dessì - Marinelli sabato 5 marzo 2011
  • 55. References • Javascript • Douglas Crockford (Javascript the good parts) http://www.crockford.com/ • Nodejs http://nodejs.org/ • John Resig (JQuery, Pro Javascript and Javascript secrets books) http://ejohn.org/ • Clojure • Clojure Web Site: http://clojure.org • Clojure Online Docs: http://clojuredocs.org/ • Programming Clojure Book: http://pragprog.com/titles/shcloj/programming-clojure • Scala • Scala site : http://www.scala-lang.org • Scala docs: http://www.scala-lang.org/node/197 • Scala Books : http://www.scala-lang.org/node/959 Bossa - Dessì - Marinelli sabato 5 marzo 2011