SlideShare uma empresa Scribd logo
1 de 35
Why we cannot ignore
functional programming
              Massimiliano Dessì & Mario Fusco
               @desmax74          @mariofusco
speakers

        Max                                          Mario



JugSardegna, SpringFramework UG,              Creator of lambdaj and
Google Technology UG Sardegna,                   hammurabi projects
Senior Software Engineer in               Senior Software Engineer in
Energeya
                                         Red Hat working on the core
Author of Spring 2.5 AOP
                                             of the drools rule engine
                                                      Massimiliano Dessì - Mario Fusco
Moore's law



The number of transistors on
integrated circuits doubles
approximately every two
years




                                     Massimiliano Dessì - Mario Fusco
Amdahl's law


The speedup of a program
using multiple processors
in parallel computing is
limited by the time needed
for the sequential fraction
of the program




                                        Massimiliano Dessì - Mario Fusco
Concurrent programming




Managing concurrent requests




                                   Massimiliano Dessì - Mario Fusco
Parallel programming




         Running multiple tasks at the same
                       time




                               Massimiliano Dessì - Mario Fusco
The root of the problem




      Mutable state       +
         Parallel processing =
    Non-determinism

          Functional
         Programming
                          Massimiliano Dessì - Mario Fusco
… and its effects




Race conditions
                                        Starvation


  Deadlocks                               Livelocks




                                      Massimiliano Dessì - Mario Fusco
Epic data race failure

         Data races is not a multiuser system's feature,
         the Therac-25 was a radiation therapy machine

                http://en.wikipedia.org/wiki/Therac-25
It was involved in at least six accidents between 1985 and 1987,
in which patients were given massive overdoses of radiation,
approximately 100 times the intended dose.
These accidents highlighted the dangers of software control of
safety-critical systems.

    Therac-25 killed three patients and injured several others


                                                      Massimiliano Dessì - Mario Fusco
Epic data race failure

http://en.wikipedia.org/wiki/Northeast_blackout_of_2003

The blackout affected an estimated 10 million people in Ontario and
45 million people in eight U.S. States.

A software bug known as a race condition existed in General Electric
Energy's Unix-based XA/21 energy management system. Once
triggered, the bug stalled FirstEnergy's control room alarm system
for over an hour.
On Thursday, August 14, 2003, just before 4:10 p.m. While some
power was restored by 11 p.m.,
           many did not get power back until two days later
                                                      Massimiliano Dessì - Mario Fusco
Java concurrency model




       Threads             Semaphores           Locks         Synchronization

They are sometimes plain evil …

                    … and sometimes a necessary pain …

                                        … but always the wrong default

                                                                  Massimiliano Dessì - Mario Fusco
Different concurrency
                                 models

                         Shared mutable state
                           (threads + locks)


                                      Isolated mutable state (actors)




Purely immutable (pure functions)
                                                          Massimiliano Dessì - Mario Fusco
Summing attendants ages

class Blackboard {
                                 Threads
    int sum = 0;
    int read() { return sum; }
    void write(int value) {
       sum = value; }        class Attendant implements Runnable {
    }                            int age;
}                                Blackboard blackboard;

                                  public void run() {
                                      synchronized(blackboard) {
                                          int oldSum = blackboard.read();
                                          int newSum = oldSum + age;
                                          blackboard.write(newSum);
                                      }
                                  }
                             }
                                                         Massimiliano Dessì - Mario Fusco
Summing attendants ages

                                    Actors
class Blackboard extends UntypedActors {
    int sum = 0;
    public void onReceive(Object message) {
        if (message instanceof Integer) {
            sum += (Integer)message;
        }
    }
}

  class Attendant {
      int age;
      Blackboard blackboard;

      public void sendAge() {
          blackboard.sendOneWay(age);
      }
  }

                                                   Massimiliano Dessì - Mario Fusco
Summing attendants ages

                                 functional
class Blackboard {
    final int sum;
    Blackboard(int sum) { this.sum = sum; }
}
class Attendant {
    int age;
    Attendant next;

    public Blackboard addMyAge(Blackboard blackboard) {
        final Blackboard b = new Blackboard(blackboard.sum + age);
        return next == null ? b : next.myAge(b);
    }
}

attendants.foldLeft(
     new Blackboard(0),(att, b) -> new Blackboard(b.sum + att.age)
);

                                                              Massimiliano Dessì - Mario Fusco
functional program


              NO




                     Massimiliano Dessì - Mario Fusco
functional program


         Avoidable Side effects

            Reassigning a variable

     Modifying a data structure in place

         Setting a field on an object

Throwing an exception or halting with an error


                                             Massimiliano Dessì - Mario Fusco
functional program


     Deferrable Side effects

       Printing to the console

         Reading user input

   Reading from or writing to a file

       Drawing on the screen


                                       Massimiliano Dessì - Mario Fusco
functional program



   Functional programming
       is a restriction on
               how
 we write programs, but not on
              what
           they can do



                                 Massimiliano Dessì - Mario Fusco
The OOP/FP dualism

class Bird
class Cat {
  def capture(b: Bird): Unit = ...
  def eat(): Unit = ...
}
val cat = new Cat
val bird = new Bird

cat.capture(bird)
cat.eat()
                      class Cat
                      class Bird
                      trait Catch
                      trait FullStomach
                      def capture(prey: Bird, hunter: Cat): Cat with Catch
                      def eat(consumer: Cat with Catch): Cat with FullStomach

                      val story = (capture _) andThen (eat _)
                      story(new Bird, new Cat)

                                                           Massimiliano Dessì - Mario Fusco
Pure function


A function with input type A
    and output type B is a
 computation which relates
  every value a of type A to
exactly one value b of type B
  such that b is determined
   solely by the value of a




                                Massimiliano Dessì - Mario Fusco
Pure function




But, if it really
is a function,
     it will
 do nothing
       else




                             Massimiliano Dessì - Mario Fusco
Referential transparency


             An expression e
     is referentially transparent
          if for all programs p,
       all occurrences of e in p
                  can be
                 replaced
by the result of evaluating e, without
                 affecting
    the observable behavior of p


                                            Massimiliano Dessì - Mario Fusco
Referential transparency




         A function f
            is pure
    if the expression f(x)
is referentially transparent
             for all
referentially transparent x




                                       Massimiliano Dessì - Mario Fusco
Referential transparency

Referencial transparency
String x = "purple";
String r1 = x.replace('p', 't');
String r2 = x.replace('p', 't');

String r1 = "purple".replace('p', 't'); r1: "turtle"
String r2 = "purple".replace('p', 't'); r2: "turtle"




Not Referencial transparency
StringBuilder x = new StringBuilder("Hi");
StringBuilder y = x.append(", mom");
String r1 = y.toString();
String r2 = y.toString();

String r1 = x.append(", mom").toString();    r1: "Hi, mom"
String r2 = x.append(", mom").toString();    r1: "Hi, mom, mom"

                                                                  Massimiliano Dessì - Mario Fusco
Referential transparency

                RT Wins
    Under a developer point of view:


          Easier to reason about
                   since
   effects of evaluation are purely local

Use of the substitution model: it's possible
                 to replace
      a term with an equivalent one



                                               Massimiliano Dessì - Mario Fusco
Referential transparency


                      RT Wins
         Under a performance point of view:


The JVM is free to optimize the code by safely reordering
                     the instructions

     No need to synchronize access to shared data




                                                   Massimiliano Dessì - Mario Fusco
Immutability




    Immutable objects
      can be shared
among many threads exactly
 because none of them can
         modify it




                             Massimiliano Dessì - Mario Fusco
Immutability



          In the same way
      immutable (persistent)
           data structures
            can be shared
               without
any need to synchronize the different
      threads accessing them




                                        Massimiliano Dessì - Mario Fusco
Persistent Collections




                         Massimiliano Dessì - Mario Fusco
Persistent Collections


          Tree with high branching factor (at least 32 per node)
               reduce the time for operations on the tries.
 High branching factor require four levels to hold up a million of elements.


              Phil Bagwell (EPFL)         Rich Hickey (Clojure)

               http://lampwww.epfl.ch/papers/idealhashtrees.pd
               f
       http://infoscience.epfl.ch/record/169879/files/RMTrees.pd
       f
http://infoscience.epfl.ch/record/169879/files/RMTrees.pdf?version=1

                                                             Massimiliano Dessì - Mario Fusco
Modularity
class Player { String name; int score; }
                                                              Separate
public void declareWinner(Player p) {                      computational
    System.out.println(p.name + " wins!");
}
                                                           logic from side
public void winner(Player p1, Player p2) {                     effects
    if (p1.score > p2.score) declareWinner(p1)
    else declareWinner(p2);
}
public Player maxScore(Player p1, Player p2) {
    return p1.score > p2.score ? p1 : p2;
}
public void winner(Player p1, Player p2) {
    declareWinner(maxScore(p1, p2));
}
                                   declareWinner(players.reduceLeft(maxScore))


reuse maxScore to compute the winner among a list of players
                                                             Massimiliano Dessì - Mario Fusco
Functional core

              a thin external layer to handle side-effects




Any function with side-effects can be split into a pure function at the core and a
pair of functions with side-effect. This transformation can be repeated to push
                side-effects to the outer layers of the program.


                                                                Massimiliano Dessì - Mario Fusco
Q&A




      Massimiliano Dessì - Mario Fusco
Thank you for your attention !
                                 Massimiliano Dessì - Mario Fusco

Mais conteúdo relacionado

Destaque

Dessi docker kubernetes paas cloud
Dessi docker kubernetes paas cloudDessi docker kubernetes paas cloud
Dessi docker kubernetes paas cloudMassimiliano Dessì
 
Reactive applications Linux Day 2013
Reactive applications Linux Day 2013Reactive applications Linux Day 2013
Reactive applications Linux Day 2013Massimiliano Dessì
 
Scala Italy 2013 extended Scalatra vs Spring MVC
Scala Italy 2013 extended Scalatra vs Spring MVCScala Italy 2013 extended Scalatra vs Spring MVC
Scala Italy 2013 extended Scalatra vs Spring MVCMassimiliano Dessì
 
Codemotion 2013 scalatra_play_spray
Codemotion 2013 scalatra_play_sprayCodemotion 2013 scalatra_play_spray
Codemotion 2013 scalatra_play_sprayMassimiliano Dessì
 
Vert.X like Node.js but polyglot and reactive on JVM
Vert.X like Node.js but polyglot and reactive on JVMVert.X like Node.js but polyglot and reactive on JVM
Vert.X like Node.js but polyglot and reactive on JVMMassimiliano Dessì
 
Microservices in Go_Dessi_Massimiliano_Codemotion_2017_Rome
Microservices in Go_Dessi_Massimiliano_Codemotion_2017_Rome Microservices in Go_Dessi_Massimiliano_Codemotion_2017_Rome
Microservices in Go_Dessi_Massimiliano_Codemotion_2017_Rome Massimiliano Dessì
 
OOP and FP: become a better programmer - Simone Bordet, Mario Fusco - Codemot...
OOP and FP: become a better programmer - Simone Bordet, Mario Fusco - Codemot...OOP and FP: become a better programmer - Simone Bordet, Mario Fusco - Codemot...
OOP and FP: become a better programmer - Simone Bordet, Mario Fusco - Codemot...Codemotion
 
The hitchhiker's guide to UXing without a UXer - Chrissy Welsh - Codemotion M...
The hitchhiker's guide to UXing without a UXer - Chrissy Welsh - Codemotion M...The hitchhiker's guide to UXing without a UXer - Chrissy Welsh - Codemotion M...
The hitchhiker's guide to UXing without a UXer - Chrissy Welsh - Codemotion M...Codemotion
 
The final words about software estimation
The final words about software estimationThe final words about software estimation
The final words about software estimationAlberto Brandolini
 
The amazing world of Game Design - Emanuele Bolognesi - Codemotion Milan 2016
The amazing world of Game Design - Emanuele Bolognesi - Codemotion Milan 2016The amazing world of Game Design - Emanuele Bolognesi - Codemotion Milan 2016
The amazing world of Game Design - Emanuele Bolognesi - Codemotion Milan 2016Codemotion
 
Event sourcing your React-Redux applications
Event sourcing your React-Redux applicationsEvent sourcing your React-Redux applications
Event sourcing your React-Redux applicationsMaurice De Beijer [MVP]
 

Destaque (17)

Dessi docker kubernetes paas cloud
Dessi docker kubernetes paas cloudDessi docker kubernetes paas cloud
Dessi docker kubernetes paas cloud
 
Reactive applications Linux Day 2013
Reactive applications Linux Day 2013Reactive applications Linux Day 2013
Reactive applications Linux Day 2013
 
Scala Italy 2013 extended Scalatra vs Spring MVC
Scala Italy 2013 extended Scalatra vs Spring MVCScala Italy 2013 extended Scalatra vs Spring MVC
Scala Italy 2013 extended Scalatra vs Spring MVC
 
Codemotion 2013 scalatra_play_spray
Codemotion 2013 scalatra_play_sprayCodemotion 2013 scalatra_play_spray
Codemotion 2013 scalatra_play_spray
 
Docker linuxday 2015
Docker linuxday 2015Docker linuxday 2015
Docker linuxday 2015
 
Openshift linuxday 2014
Openshift linuxday 2014Openshift linuxday 2014
Openshift linuxday 2014
 
Docker dDessi november 2015
Docker dDessi november 2015Docker dDessi november 2015
Docker dDessi november 2015
 
Vert.X like Node.js but polyglot and reactive on JVM
Vert.X like Node.js but polyglot and reactive on JVMVert.X like Node.js but polyglot and reactive on JVM
Vert.X like Node.js but polyglot and reactive on JVM
 
Microservices in Go_Dessi_Massimiliano_Codemotion_2017_Rome
Microservices in Go_Dessi_Massimiliano_Codemotion_2017_Rome Microservices in Go_Dessi_Massimiliano_Codemotion_2017_Rome
Microservices in Go_Dessi_Massimiliano_Codemotion_2017_Rome
 
The busy developer guide to Docker
The busy developer guide to DockerThe busy developer guide to Docker
The busy developer guide to Docker
 
OOP and FP: become a better programmer - Simone Bordet, Mario Fusco - Codemot...
OOP and FP: become a better programmer - Simone Bordet, Mario Fusco - Codemot...OOP and FP: become a better programmer - Simone Bordet, Mario Fusco - Codemot...
OOP and FP: become a better programmer - Simone Bordet, Mario Fusco - Codemot...
 
Scala linux day 2012
Scala linux day 2012 Scala linux day 2012
Scala linux day 2012
 
The hitchhiker's guide to UXing without a UXer - Chrissy Welsh - Codemotion M...
The hitchhiker's guide to UXing without a UXer - Chrissy Welsh - Codemotion M...The hitchhiker's guide to UXing without a UXer - Chrissy Welsh - Codemotion M...
The hitchhiker's guide to UXing without a UXer - Chrissy Welsh - Codemotion M...
 
Event storming recipes
Event storming recipesEvent storming recipes
Event storming recipes
 
The final words about software estimation
The final words about software estimationThe final words about software estimation
The final words about software estimation
 
The amazing world of Game Design - Emanuele Bolognesi - Codemotion Milan 2016
The amazing world of Game Design - Emanuele Bolognesi - Codemotion Milan 2016The amazing world of Game Design - Emanuele Bolognesi - Codemotion Milan 2016
The amazing world of Game Design - Emanuele Bolognesi - Codemotion Milan 2016
 
Event sourcing your React-Redux applications
Event sourcing your React-Redux applicationsEvent sourcing your React-Redux applications
Event sourcing your React-Redux applications
 

Mais de Massimiliano Dessì

When Old Meets New: Turning Maven into a High Scalable, Resource Efficient, C...
When Old Meets New: Turning Maven into a High Scalable, Resource Efficient, C...When Old Meets New: Turning Maven into a High Scalable, Resource Efficient, C...
When Old Meets New: Turning Maven into a High Scalable, Resource Efficient, C...Massimiliano Dessì
 
Web Marketing Training 2014 Community Online
Web Marketing Training 2014 Community OnlineWeb Marketing Training 2014 Community Online
Web Marketing Training 2014 Community OnlineMassimiliano Dessì
 
Three languages in thirty minutes
Three languages in thirty minutesThree languages in thirty minutes
Three languages in thirty minutesMassimiliano Dessì
 
Jaxitalia09 Spring Best Practices
Jaxitalia09 Spring Best PracticesJaxitalia09 Spring Best Practices
Jaxitalia09 Spring Best PracticesMassimiliano Dessì
 
MongoDB Scala Roma SpringFramework Meeting2009
MongoDB Scala Roma SpringFramework Meeting2009MongoDB Scala Roma SpringFramework Meeting2009
MongoDB Scala Roma SpringFramework Meeting2009Massimiliano Dessì
 
Scala Programming Linux Day 2009
Scala Programming Linux Day 2009Scala Programming Linux Day 2009
Scala Programming Linux Day 2009Massimiliano Dessì
 
MongoDB SpringFramework Meeting september 2009
MongoDB SpringFramework Meeting september 2009MongoDB SpringFramework Meeting september 2009
MongoDB SpringFramework Meeting september 2009Massimiliano Dessì
 
The hidden gems of Spring Security
The hidden gems of Spring SecurityThe hidden gems of Spring Security
The hidden gems of Spring SecurityMassimiliano Dessì
 
Aspect Oriented Programming and MVC with Spring Framework
Aspect Oriented Programming and MVC with Spring FrameworkAspect Oriented Programming and MVC with Spring Framework
Aspect Oriented Programming and MVC with Spring FrameworkMassimiliano Dessì
 
Real Spring Aop Recipes For Your Everyday Job
Real Spring Aop Recipes For Your Everyday JobReal Spring Aop Recipes For Your Everyday Job
Real Spring Aop Recipes For Your Everyday JobMassimiliano Dessì
 

Mais de Massimiliano Dessì (20)

Code One 2018 maven
Code One 2018   mavenCode One 2018   maven
Code One 2018 maven
 
When Old Meets New: Turning Maven into a High Scalable, Resource Efficient, C...
When Old Meets New: Turning Maven into a High Scalable, Resource Efficient, C...When Old Meets New: Turning Maven into a High Scalable, Resource Efficient, C...
When Old Meets New: Turning Maven into a High Scalable, Resource Efficient, C...
 
Hacking Maven Linux day 2017
Hacking Maven Linux day 2017Hacking Maven Linux day 2017
Hacking Maven Linux day 2017
 
Web Marketing Training 2014 Community Online
Web Marketing Training 2014 Community OnlineWeb Marketing Training 2014 Community Online
Web Marketing Training 2014 Community Online
 
Three languages in thirty minutes
Three languages in thirty minutesThree languages in thirty minutes
Three languages in thirty minutes
 
MongoDB dessi-codemotion
MongoDB dessi-codemotionMongoDB dessi-codemotion
MongoDB dessi-codemotion
 
MongoDB Webtech conference 2010
MongoDB Webtech conference 2010MongoDB Webtech conference 2010
MongoDB Webtech conference 2010
 
RESTEasy
RESTEasyRESTEasy
RESTEasy
 
Spring Roo Internals Javaday IV
Spring Roo Internals Javaday IVSpring Roo Internals Javaday IV
Spring Roo Internals Javaday IV
 
Spring Roo JaxItalia09
Spring Roo JaxItalia09Spring Roo JaxItalia09
Spring Roo JaxItalia09
 
Jaxitalia09 Spring Best Practices
Jaxitalia09 Spring Best PracticesJaxitalia09 Spring Best Practices
Jaxitalia09 Spring Best Practices
 
Spring3.0 JaxItalia09
Spring3.0 JaxItalia09Spring3.0 JaxItalia09
Spring3.0 JaxItalia09
 
MongoDB Scala Roma SpringFramework Meeting2009
MongoDB Scala Roma SpringFramework Meeting2009MongoDB Scala Roma SpringFramework Meeting2009
MongoDB Scala Roma SpringFramework Meeting2009
 
Scala Programming Linux Day 2009
Scala Programming Linux Day 2009Scala Programming Linux Day 2009
Scala Programming Linux Day 2009
 
MongoDB SpringFramework Meeting september 2009
MongoDB SpringFramework Meeting september 2009MongoDB SpringFramework Meeting september 2009
MongoDB SpringFramework Meeting september 2009
 
The hidden gems of Spring Security
The hidden gems of Spring SecurityThe hidden gems of Spring Security
The hidden gems of Spring Security
 
Spring @Aspect e @Controller
Spring @Aspect e @Controller Spring @Aspect e @Controller
Spring @Aspect e @Controller
 
Aspect Oriented Programming and MVC with Spring Framework
Aspect Oriented Programming and MVC with Spring FrameworkAspect Oriented Programming and MVC with Spring Framework
Aspect Oriented Programming and MVC with Spring Framework
 
Real Spring Aop Recipes For Your Everyday Job
Real Spring Aop Recipes For Your Everyday JobReal Spring Aop Recipes For Your Everyday Job
Real Spring Aop Recipes For Your Everyday Job
 
Dessi Tech Day2008 Cagliari
Dessi Tech Day2008 CagliariDessi Tech Day2008 Cagliari
Dessi Tech Day2008 Cagliari
 

Último

Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 

Último (20)

Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 

Why we cannot ignore functional programming

  • 1. Why we cannot ignore functional programming Massimiliano Dessì & Mario Fusco @desmax74 @mariofusco
  • 2. speakers Max Mario JugSardegna, SpringFramework UG, Creator of lambdaj and Google Technology UG Sardegna, hammurabi projects Senior Software Engineer in Senior Software Engineer in Energeya Red Hat working on the core Author of Spring 2.5 AOP of the drools rule engine Massimiliano Dessì - Mario Fusco
  • 3. Moore's law The number of transistors on integrated circuits doubles approximately every two years Massimiliano Dessì - Mario Fusco
  • 4. Amdahl's law The speedup of a program using multiple processors in parallel computing is limited by the time needed for the sequential fraction of the program Massimiliano Dessì - Mario Fusco
  • 5. Concurrent programming Managing concurrent requests Massimiliano Dessì - Mario Fusco
  • 6. Parallel programming Running multiple tasks at the same time Massimiliano Dessì - Mario Fusco
  • 7. The root of the problem Mutable state + Parallel processing = Non-determinism Functional Programming Massimiliano Dessì - Mario Fusco
  • 8. … and its effects Race conditions Starvation Deadlocks Livelocks Massimiliano Dessì - Mario Fusco
  • 9. Epic data race failure Data races is not a multiuser system's feature, the Therac-25 was a radiation therapy machine http://en.wikipedia.org/wiki/Therac-25 It was involved in at least six accidents between 1985 and 1987, in which patients were given massive overdoses of radiation, approximately 100 times the intended dose. These accidents highlighted the dangers of software control of safety-critical systems. Therac-25 killed three patients and injured several others Massimiliano Dessì - Mario Fusco
  • 10. Epic data race failure http://en.wikipedia.org/wiki/Northeast_blackout_of_2003 The blackout affected an estimated 10 million people in Ontario and 45 million people in eight U.S. States. A software bug known as a race condition existed in General Electric Energy's Unix-based XA/21 energy management system. Once triggered, the bug stalled FirstEnergy's control room alarm system for over an hour. On Thursday, August 14, 2003, just before 4:10 p.m. While some power was restored by 11 p.m., many did not get power back until two days later Massimiliano Dessì - Mario Fusco
  • 11. Java concurrency model Threads Semaphores Locks Synchronization They are sometimes plain evil … … and sometimes a necessary pain … … but always the wrong default Massimiliano Dessì - Mario Fusco
  • 12. Different concurrency models Shared mutable state (threads + locks) Isolated mutable state (actors) Purely immutable (pure functions) Massimiliano Dessì - Mario Fusco
  • 13. Summing attendants ages class Blackboard { Threads int sum = 0; int read() { return sum; } void write(int value) { sum = value; } class Attendant implements Runnable { } int age; } Blackboard blackboard; public void run() { synchronized(blackboard) { int oldSum = blackboard.read(); int newSum = oldSum + age; blackboard.write(newSum); } } } Massimiliano Dessì - Mario Fusco
  • 14. Summing attendants ages Actors class Blackboard extends UntypedActors { int sum = 0; public void onReceive(Object message) { if (message instanceof Integer) { sum += (Integer)message; } } } class Attendant { int age; Blackboard blackboard; public void sendAge() { blackboard.sendOneWay(age); } } Massimiliano Dessì - Mario Fusco
  • 15. Summing attendants ages functional class Blackboard { final int sum; Blackboard(int sum) { this.sum = sum; } } class Attendant { int age; Attendant next; public Blackboard addMyAge(Blackboard blackboard) { final Blackboard b = new Blackboard(blackboard.sum + age); return next == null ? b : next.myAge(b); } } attendants.foldLeft( new Blackboard(0),(att, b) -> new Blackboard(b.sum + att.age) ); Massimiliano Dessì - Mario Fusco
  • 16. functional program NO Massimiliano Dessì - Mario Fusco
  • 17. functional program Avoidable Side effects Reassigning a variable Modifying a data structure in place Setting a field on an object Throwing an exception or halting with an error Massimiliano Dessì - Mario Fusco
  • 18. functional program Deferrable Side effects Printing to the console Reading user input Reading from or writing to a file Drawing on the screen Massimiliano Dessì - Mario Fusco
  • 19. functional program Functional programming is a restriction on how we write programs, but not on what they can do Massimiliano Dessì - Mario Fusco
  • 20. The OOP/FP dualism class Bird class Cat { def capture(b: Bird): Unit = ... def eat(): Unit = ... } val cat = new Cat val bird = new Bird cat.capture(bird) cat.eat() class Cat class Bird trait Catch trait FullStomach def capture(prey: Bird, hunter: Cat): Cat with Catch def eat(consumer: Cat with Catch): Cat with FullStomach val story = (capture _) andThen (eat _) story(new Bird, new Cat) Massimiliano Dessì - Mario Fusco
  • 21. Pure function A function with input type A and output type B is a computation which relates every value a of type A to exactly one value b of type B such that b is determined solely by the value of a Massimiliano Dessì - Mario Fusco
  • 22. Pure function But, if it really is a function, it will do nothing else Massimiliano Dessì - Mario Fusco
  • 23. Referential transparency An expression e is referentially transparent if for all programs p, all occurrences of e in p can be replaced by the result of evaluating e, without affecting the observable behavior of p Massimiliano Dessì - Mario Fusco
  • 24. Referential transparency A function f is pure if the expression f(x) is referentially transparent for all referentially transparent x Massimiliano Dessì - Mario Fusco
  • 25. Referential transparency Referencial transparency String x = "purple"; String r1 = x.replace('p', 't'); String r2 = x.replace('p', 't'); String r1 = "purple".replace('p', 't'); r1: "turtle" String r2 = "purple".replace('p', 't'); r2: "turtle" Not Referencial transparency StringBuilder x = new StringBuilder("Hi"); StringBuilder y = x.append(", mom"); String r1 = y.toString(); String r2 = y.toString(); String r1 = x.append(", mom").toString(); r1: "Hi, mom" String r2 = x.append(", mom").toString(); r1: "Hi, mom, mom" Massimiliano Dessì - Mario Fusco
  • 26. Referential transparency RT Wins Under a developer point of view: Easier to reason about since effects of evaluation are purely local Use of the substitution model: it's possible to replace a term with an equivalent one Massimiliano Dessì - Mario Fusco
  • 27. Referential transparency RT Wins Under a performance point of view: The JVM is free to optimize the code by safely reordering the instructions No need to synchronize access to shared data Massimiliano Dessì - Mario Fusco
  • 28. Immutability Immutable objects can be shared among many threads exactly because none of them can modify it Massimiliano Dessì - Mario Fusco
  • 29. Immutability In the same way immutable (persistent) data structures can be shared without any need to synchronize the different threads accessing them Massimiliano Dessì - Mario Fusco
  • 30. Persistent Collections Massimiliano Dessì - Mario Fusco
  • 31. Persistent Collections Tree with high branching factor (at least 32 per node) reduce the time for operations on the tries. High branching factor require four levels to hold up a million of elements. Phil Bagwell (EPFL) Rich Hickey (Clojure) http://lampwww.epfl.ch/papers/idealhashtrees.pd f http://infoscience.epfl.ch/record/169879/files/RMTrees.pd f http://infoscience.epfl.ch/record/169879/files/RMTrees.pdf?version=1 Massimiliano Dessì - Mario Fusco
  • 32. Modularity class Player { String name; int score; } Separate public void declareWinner(Player p) { computational System.out.println(p.name + " wins!"); } logic from side public void winner(Player p1, Player p2) { effects if (p1.score > p2.score) declareWinner(p1) else declareWinner(p2); } public Player maxScore(Player p1, Player p2) { return p1.score > p2.score ? p1 : p2; } public void winner(Player p1, Player p2) { declareWinner(maxScore(p1, p2)); } declareWinner(players.reduceLeft(maxScore)) reuse maxScore to compute the winner among a list of players Massimiliano Dessì - Mario Fusco
  • 33. Functional core a thin external layer to handle side-effects Any function with side-effects can be split into a pure function at the core and a pair of functions with side-effect. This transformation can be repeated to push side-effects to the outer layers of the program. Massimiliano Dessì - Mario Fusco
  • 34. Q&A Massimiliano Dessì - Mario Fusco
  • 35. Thank you for your attention ! Massimiliano Dessì - Mario Fusco