SlideShare a Scribd company logo
1 of 112
Feel free to tweet


    #devbash
A Sceptical Guide to
   Functional Programming

Garth Gilmour (garth.gilmour@instil.co)
In the Belfast IT Forum BASH the audience are
entertained by two separate and unequal types of
presenter. World class experts who understand the
topic they are presenting on and uninformed dilettantes
who mither on about stuff they barely understand.

This is the latter 
This is a Sceptical Roadmap
  Personally I really like FP
  Not so sure about FP programmers
  Some things I’m going to say will really annoy
   any FP purists out there...
Don't program
  in Java!!


                 Why not?


Its restrictive – everything
   has to be an object!!


                What should
                  I use?
Program in
   Lisp!!


                    Why?


Its brilliant – everything
    has to be a list!!!!


                   Erm.....
Or better yet
    Haskell!!


                   Why?


  Its brilliant – you cant do
anything except pure math!!!!


              Right...bye....
A Puzzle For You…
A Puzzle For You…
Some FP Languages
Pure Languages Vs. Hybrids




       JavaScript       Ruby   Scala   F#      Clojure Haskell
                                            ClojureScript
              CoffeeScript
                  Dart
                Groovy
              Powershell
The 1990’s


                   Perl
      Delphi




C++            C          Python




                   VB
      Lua
The 2010’s (Part 1)


         Scala            Groovy




JRuby             Java             Clojure




                         Jython
         Kotlin
The 2010’s (Part 2)


       C#           PowerShell




F#          CLR                  VB




 IronRuby         IronPython
The 2010’s (Part 3)


           Dart                 CoffeeScript




GWT               JavaScript




ClojureScript                  Many more ...
Does the Language Matter?


                       In the Soviet army it
                       takes more courage to
                       retreat than advance.

                                 Joseph Stalin




    Miyamoto Musashi
Does the Language Matter?
Sometimes Language Helps
I Like Scala...
package demos.scala.classes.basic

class Employee(val name : String,
               val age : Int,
               val salary : Double)

$ javap -private demos.scala.classes.basic.Employee
Compiled from "Employee.scala"
public class demos.scala.classes.basic.Employee
                 extends java.lang.Object
                 implements scala.ScalaObject{
    private final java.lang.String name;
    private final int age;
    private final double salary;
    public java.lang.String name();
    public int age();
    public double salary();
    public demos.scala.classes.basic.Employee(java.lang.String, int, double);
}
A Quick Word On Clojure
    A LISP with more syntax than ((( )))
    Dynamically typed and mostly functional
    Integrates fully with the JVM/CLR
    Extensive support for concurrency
       Via   efficient but immutable collections
(defn printRow [rowNum height]
 (dotimes [n (- height rowNum)] (print " "))
 (dotimes [n (- (* rowNum 2) 1)] (print "#"))
 (println))

(defn printPyramid [height]
 (dotimes [n height] (printRow (+ n 1) height)))

(println "Enter the height of the pyramid...")
(printPyramid (Integer/parseInt (read-line)))
@FooBar
public class MyClass {
}
Back to the Quiz…
The Puzzle Once Again…
The Puzzle Once Again…
What Makes this Functional?

    Functional Composition
    Immutable State
    First Class Functions
    Internal Iteration
    Declarative Feel
    Use of a DSL
Will Look Better in Dart…
You Are Doing FP Already (Kinda)
    If you program in:
       XSLT (my favourite language)
       JavaScript (esp. if you use JQuery, Dojo         etc…)
       C# from VS2008 onwards (esp. LINQ)
       Java (believe it or not…)
          If you use libraries like Guava / Google Collections
          If you follow certain coding conventions / best practises

       Ruby   or Python
    Then you are already using FP techniques
       Even   if you don’t already know it
Is XSLT a Functional Language?

           <xsl:template match="title">
              <header>
                   <h1><xsl:value-of select="text()"/></h1>
              </header>
           </xsl:template>




 <title>Introduction to Java</title>   <header>
                                          <h1>Introduction to Java</h1>
                                       </header>
Is XSLT a Functional Language?

     Stylesheet



?                               Output Tree




     Input Tree
                  XSLT Engine
                                              ?
?
LINQ is a Functional Technology

      Query



                  Expression Tree

                                    LINQ to SQL
    C# Compiler
                                       Plug-In




                                       ?
No Fear
(Well Just A Little)




Pure Bowel
Knotting Terror
First-Class
 Functions
def main(args : Array[String]) {
 println("---Demo 1---")
 val limit = 6
 (1 to limit).foreach(num => printf("%d ", num))
 println
 (1 to limit).foreach(printf("%d ", _))

    println("nn---Demo 2 ---")
    val data = List(10,11,12,13,14,15)
    val result1 = data.foldLeft(1000)((a,b) => a + b)
    val result2 = data.foldLeft(2000)(_ + _)
    println(result1)
    println(result2)

    println("n---Demo 3 ---")
    val text = "abc123def456ghi789"
    val newText = "[a-z]{3}".r.replaceAllIn(text, _.group(0).toUpperCase())
    println(newText)
}
(defn times2 [x] (* x 2))
(defn greaterThan15 [x] (> x 15))

(def myvector [10 12 14 16 18 20 22 24])

(def result1 (map times2 myvector))
(def result2 (map (fn [x] (* x 2)) myvector))
(def result3 (map #(* %1 2) myvector))

(def result4 (filter greaterThan15 myvector))
(def result5 (filter (fn [x] (> x 15)) myvector))
(def result6 (filter #(> %1 15) myvector))

(def result7 (map #(* %1 2) (filter #(> %1 15) myvector)))
The Road Not Taken...
 The newest version of the Microsoft Visual J++ development environment supports a language
 construct called delegates or bound method references…

 It is unlikely that the Java programming language will ever include this construct. Sun already
 carefully considered adopting it in 1996, to the extent of building and discarding working
 prototypes. Our conclusion was that bound method references are unnecessary and detrimental
 to the language…

 We believe bound method references are unnecessary because another design alternative, inner
 classes, provides equal or superior functionality. In particular, inner classes fully support the
 requirements of user-interface event handling, and have been used to implement a user-interface
 API at least as comprehensive as the Windows Foundation Classes.

 We believe bound method references are harmful because they detract from the simplicity of the
 Java programming language and the pervasively object-oriented character of the APIs….


                                                    Extracts From: About Microsoft’s “Delegates"
                                              Whitepaper by the Java language team at JavaSoft
private void demoTemplatesAndCallbacks(HibernateTemplate template) {
    String query = "select delivery.course.title from Delivery delivery";
    List titles = template.executeFind(new QueryCallback(query));
    System.out.println("Courses being delivered are:");
    for(Object title : titles) {
        System.out.printf("t%sn",title);
    }
}

public class QueryCallback implements HibernateCallback {
   public QueryCallback(String query) {
       this.queryStr = query;
   }
   public Object doInHibernate(Session session)
                  throws HibernateException, SQLException {
       Query query = session.createQuery(queryStr);
       return query.list();
   }
   public String queryStr;
}
private void demoTemplatesAndCallbacks(HibernateTemplate template) {
    String query = "select delivery.course.title from Delivery delivery";
    List titles = template.executeFind((s) => s.createQuery(query).list());
    System.out.println("Courses being delivered are:");
    titles.forEach((t) => System.out.printf("t%sn",title));
}
SwingUtilities.invokeLater(new Runnable() {
                                public void run() {
                                   textField.setText(theResult);
                                }
                           });




SwingUtilities.invokeLater(() => textField.setText(theResult));
val originalData = List("ab", "cd", "ef", "gh", "ij", "kl")

val newData1 =
    originalData.map((str) => new Result(str + "yy", Thread.currentThread.getId))

val newData2 =
    originalData.par.map((str) => new Result(str + "zz", Thread.currentThread.getId)
Referential
Transparency
Programmer

a=a+1
        Mathematician
class Person {
    public String toString() {
        StringBuilder sb = new StringBuilder();                Person earning
        sb.append(“Person earning ”);                          5000.0 with tax of
        sb.append(salary.calcMonthlyBasic());                  763 and pension
        sb.append(“ with tax of ”);
                                                               payment of 469.0
        sb.append(salary.monthlyTax());
        sb.append(“ and pension payment of ”);
        sb.append(salary.monthlyPension());
        return sb.toString();
    }                               class Person {
    private Salary salary;              public String toString() {
}                                           StringBuilder sb = new StringBuilder();
                                            sb.append(“Person earning ”);
                                            sb.append(5000.0);
  Person earning                            sb.append(“ with tax of ”);
  5000.0 with tax of                        sb.append(salary.monthlyTax());
                                            sb.append(“ and pension payment of ”);
  0 and pension
                                            sb.append(salary.monthlyPension());
  payment of 0                              return sb.toString();
                                        }
                                        private Salary salary;
                                    }
What's The Use?
    Code is easier to reason about.
    Compilers & VM’s can partition code automatically
     into sections and run them in parallel.
    Lazy Evaluation

       if(foo() && bar()) {   func(foo(), bar());
           zed();             -------------------------------
       }                      void func(a, b) {
                                 if(zed()) {
       if(foo() || bar()) {          c = a + 1; //foo not called till here
          zed();                 }
       }                      }
The Point of Having a VM
What Happens?
Whooops!
Objects   Threads
Another reason that you might be interesting in purity is that it
gives you a better handle on parallelism. It doesn't make
parallelism easy, but it kinda makes it feel a bit more within
reach.

...
I dont think its parallelism without tears, but it kinda gives you
a chance in a way that the imperative by default with shared
mutable state makes things very difficult.

                                              Simon Peyton Jones
                                            (On SE Radio Ep 108)
But all a purely functional program
can do is heat up the CPU - and
that's still a side effect!!!
Higher-Order Functions
(inc. Currying & Partial Invoke)
def joinUp(separator : Char)(data : Array[String]) = {
    val sb = new StringBuilder
    for(str <- data) {
      sb.append(str)
      sb.append(separator)
    }
    sb.substring(0,sb.length - 1)
 }

 def joinUpWithHashes = joinUp('#') _
 def joinUpWithHyphens = joinUp('-') _

 def main(args : Array[String]) {
   val testData = Array("abc","def","ghi","jkl","mno")
   println(joinUp(',')(testData))
   println(joinUpWithHashes(testData))
   println(joinUpWithHyphens(testData))
 }
Type Inference
& Parametric Polymorphism
Recursion
Tail Recursion
int foo(int a) {               int foo(int a) {
     int b = zed();                 int b = zed();
     if(b > a) {                    if(b > a) {
          return a + foo(b);             return foo(a + b);
     } else {                       } else {
          return b;                      return 1;
     }                              }
}                              }

     a
     b

         a
         b
                                        a
             a
                                        b
             b
                 a
                 b
Pattern
Matching
def processItem(item : StockItem) {
  item match {
    case Book(_,"Crime") => println("Found a crime novel")
    case Movie(_,MovieType.DVD) => println("Found a DVD movie")
    case CD(_,_,12) => println("Found a CD with 12 tracks")
    case CD(_,"Soundgarden",_) => println("Found a CD by Soundgarden")
    case Book(_,_) => println("Found some kind of book")
    case _ => println("Found something...")
  }
}
Monads
(Sequence Expressions)
Monads By Metaphor
   int pthread_create(pthread_t *thread,
                 const pthread_attr_t *attr,
                 void *(*start_routine) (void *),
                 void *arg);
Monads By Quotation

   Monads turn control flow into data
   flow, where it can be constrained
   by the type system.

                            Oleg Kiselyov
Monads By Example
    Monads remove the boilerplate involved when
     extracting / inserting values from “Amplified Types”
       Whilst enabling the compiler to perform extra checks
       Kind of like AOP but without the runtime overhead

                  List<T>
                  Map<T,U>
                  Option<T> (aka Maybe<T>)
                  EntityManager<T>
                  Repository<T>
                  ThreadSafe<T>
                  IO<T>
void printPostcode(Person person) {
    String code = person.findAddress().findPostcode().findValue();
    System.out.println(code);
}

    void printPostcode(Person person) {
       Address address = person.findAddress();
        if(address != null) {
            Postcode postcode = address.findPostcode()
            if(postcode != null) {
                String code = postcode.findValue();
                System.out.println(code);
            }
        }
    }
class Person(val name : String, val address : Address) {
  def findAddress() : Option[Address] = {
    if(address == null) {
      None
    } else {
      Some(address)
    }
  }
}
def printPostcodeIfExists(person : Person) {
   println("Working with " + person.name)
   for (
        place <- person findAddress;
        code <- place findPostcode;
        result <- code findValue
      ) println(result)
}
I Trust That's All Clear Now 
One Final Thought...

    OO makes code understandable by
    encapsulating moving parts. FP makes
    code understandable by minimizing
    moving parts.

                        Michael Feathers
To Summarize...
    You can start doing this today
       Get familiar with the FP parts of your language
       Prefer internal iteration to explicit loops
       Play with making sections of code side-effect free
       Experiment with building functional machines
       Use the emerging support for ‘hands-free’   concurrency
       Review, measure, assess, adjust
    Make this years new language an FP one
       Try Scala to extend what you already know into FP
       Try Clojure, F# or Haskell to get a new perspective
Coming soon....
21st March 2012




Kevlin Henney
   A Question of
   Craftsmanship
April/May




        ??
We are speaking to a
few exciting people!
September 2012




Jim Webber
  Mr NOSQL
A Sceptical Guide to Functional Programming

More Related Content

What's hot

Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
Sandip Kumar
 
Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008
Yardena Meymann
 

What's hot (20)

Workshop Scala
Workshop ScalaWorkshop Scala
Workshop Scala
 
Starting with Scala : Frontier Developer's Meetup December 2010
Starting with Scala : Frontier Developer's Meetup December 2010Starting with Scala : Frontier Developer's Meetup December 2010
Starting with Scala : Frontier Developer's Meetup December 2010
 
Scala fundamentals
Scala fundamentalsScala fundamentals
Scala fundamentals
 
Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to Scala
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
 
Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with Scala
 
Scala
ScalaScala
Scala
 
Scala Intro
Scala IntroScala Intro
Scala Intro
 
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Beyond Java: 자바 8을 중심으로 본 자바의 혁신Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
 
Static or Dynamic Typing? Why not both?
Static or Dynamic Typing? Why not both?Static or Dynamic Typing? Why not both?
Static or Dynamic Typing? Why not both?
 
Ankara Jug - Practical Functional Programming with Scala
Ankara Jug - Practical Functional Programming with ScalaAnkara Jug - Practical Functional Programming with Scala
Ankara Jug - Practical Functional Programming with Scala
 
Clojure Intro
Clojure IntroClojure Intro
Clojure Intro
 
Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on Examples
 
Kotlin
KotlinKotlin
Kotlin
 
Scala for Java programmers
Scala for Java programmersScala for Java programmers
Scala for Java programmers
 
All about scala
All about scalaAll about scala
All about scala
 
Functional programming in Scala
Functional programming in ScalaFunctional programming in Scala
Functional programming in Scala
 
Scala uma poderosa linguagem para a jvm
Scala   uma poderosa linguagem para a jvmScala   uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvm
 
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
 

Viewers also liked

Effective akka scalaio
Effective akka scalaioEffective akka scalaio
Effective akka scalaio
shinolajla
 
C*ollege Credit: Creating Your First App in Java with Cassandra
C*ollege Credit: Creating Your First App in Java with CassandraC*ollege Credit: Creating Your First App in Java with Cassandra
C*ollege Credit: Creating Your First App in Java with Cassandra
DataStax
 
Building ‘Bootiful’ microservices cloud
Building ‘Bootiful’ microservices cloudBuilding ‘Bootiful’ microservices cloud
Building ‘Bootiful’ microservices cloud
Idan Fridman
 
Effective Scala (SoftShake 2013)
Effective Scala (SoftShake 2013)Effective Scala (SoftShake 2013)
Effective Scala (SoftShake 2013)
mircodotta
 
An example of Future composition in a real app
An example of Future composition in a real appAn example of Future composition in a real app
An example of Future composition in a real app
Phil Calçado
 

Viewers also liked (20)

Paris Kafka Meetup - Concepts & Architecture
Paris Kafka Meetup - Concepts & ArchitectureParis Kafka Meetup - Concepts & Architecture
Paris Kafka Meetup - Concepts & Architecture
 
Paris Kafka Meetup - How to develop with Kafka
Paris Kafka Meetup - How to develop with KafkaParis Kafka Meetup - How to develop with Kafka
Paris Kafka Meetup - How to develop with Kafka
 
Chicago Hadoop Users Group: Enterprise Data Workflows
Chicago Hadoop Users Group: Enterprise Data WorkflowsChicago Hadoop Users Group: Enterprise Data Workflows
Chicago Hadoop Users Group: Enterprise Data Workflows
 
Spring 3.1 and MVC Testing Support - 4Developers
Spring 3.1 and MVC Testing Support - 4DevelopersSpring 3.1 and MVC Testing Support - 4Developers
Spring 3.1 and MVC Testing Support - 4Developers
 
Reactive Programming With Akka - Lessons Learned
Reactive Programming With Akka - Lessons LearnedReactive Programming With Akka - Lessons Learned
Reactive Programming With Akka - Lessons Learned
 
The no-framework Scala Dependency Injection Framework
The no-framework Scala Dependency Injection FrameworkThe no-framework Scala Dependency Injection Framework
The no-framework Scala Dependency Injection Framework
 
Actor Based Asyncronous IO in Akka
Actor Based Asyncronous IO in AkkaActor Based Asyncronous IO in Akka
Actor Based Asyncronous IO in Akka
 
Effective akka scalaio
Effective akka scalaioEffective akka scalaio
Effective akka scalaio
 
Efficient HTTP Apis
Efficient HTTP ApisEfficient HTTP Apis
Efficient HTTP Apis
 
Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!
 
C*ollege Credit: Creating Your First App in Java with Cassandra
C*ollege Credit: Creating Your First App in Java with CassandraC*ollege Credit: Creating Your First App in Java with Cassandra
C*ollege Credit: Creating Your First App in Java with Cassandra
 
Building ‘Bootiful’ microservices cloud
Building ‘Bootiful’ microservices cloudBuilding ‘Bootiful’ microservices cloud
Building ‘Bootiful’ microservices cloud
 
Effective Actors
Effective ActorsEffective Actors
Effective Actors
 
Curator intro
Curator introCurator intro
Curator intro
 
Using Apache Solr
Using Apache SolrUsing Apache Solr
Using Apache Solr
 
Effective Scala (SoftShake 2013)
Effective Scala (SoftShake 2013)Effective Scala (SoftShake 2013)
Effective Scala (SoftShake 2013)
 
Composable and streamable Play apps
Composable and streamable Play appsComposable and streamable Play apps
Composable and streamable Play apps
 
An example of Future composition in a real app
An example of Future composition in a real appAn example of Future composition in a real app
An example of Future composition in a real app
 
Design for developers
Design for developersDesign for developers
Design for developers
 
19 challenging thoughts about leadership 2nd edition
19 challenging thoughts about leadership   2nd edition19 challenging thoughts about leadership   2nd edition
19 challenging thoughts about leadership 2nd edition
 

Similar to A Sceptical Guide to Functional Programming

Intro to scala
Intro to scalaIntro to scala
Intro to scala
Joe Zulli
 
Clojure for Java developers - Stockholm
Clojure for Java developers - StockholmClojure for Java developers - Stockholm
Clojure for Java developers - Stockholm
Jan Kronquist
 

Similar to A Sceptical Guide to Functional Programming (20)

Scala clojure techday_2011
Scala clojure techday_2011Scala clojure techday_2011
Scala clojure techday_2011
 
Intro to scala
Intro to scalaIntro to scala
Intro to scala
 
Clojure for Java developers - Stockholm
Clojure for Java developers - StockholmClojure for Java developers - Stockholm
Clojure for Java developers - Stockholm
 
Programming Android Application in Scala.
Programming Android Application in Scala.Programming Android Application in Scala.
Programming Android Application in Scala.
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
Object-oriented Basics
Object-oriented BasicsObject-oriented Basics
Object-oriented Basics
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
 
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
 
Scala
ScalaScala
Scala
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
обзор Python
обзор Pythonобзор Python
обзор Python
 
Clojure And Swing
Clojure And SwingClojure And Swing
Clojure And Swing
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and Monoids
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 

More from Garth Gilmour

More from Garth Gilmour (20)

Compose in Theory
Compose in TheoryCompose in Theory
Compose in Theory
 
Kotlin / Android Update
Kotlin / Android UpdateKotlin / Android Update
Kotlin / Android Update
 
TypeScript Vs. KotlinJS
TypeScript Vs. KotlinJSTypeScript Vs. KotlinJS
TypeScript Vs. KotlinJS
 
Shut Up And Eat Your Veg
Shut Up And Eat Your VegShut Up And Eat Your Veg
Shut Up And Eat Your Veg
 
Lies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerLies Told By The Kotlin Compiler
Lies Told By The Kotlin Compiler
 
A TypeScript Fans KotlinJS Adventures
A TypeScript Fans KotlinJS AdventuresA TypeScript Fans KotlinJS Adventures
A TypeScript Fans KotlinJS Adventures
 
The Heat Death Of Enterprise IT
The Heat Death Of Enterprise ITThe Heat Death Of Enterprise IT
The Heat Death Of Enterprise IT
 
Lies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerLies Told By The Kotlin Compiler
Lies Told By The Kotlin Compiler
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScript
 
Generics On The JVM (What you don't know will hurt you)
Generics On The JVM (What you don't know will hurt you)Generics On The JVM (What you don't know will hurt you)
Generics On The JVM (What you don't know will hurt you)
 
Using Kotlin, to Create Kotlin, to Teach Kotlin, in Space
Using Kotlin, to Create Kotlin,to Teach Kotlin,in SpaceUsing Kotlin, to Create Kotlin,to Teach Kotlin,in Space
Using Kotlin, to Create Kotlin, to Teach Kotlin, in Space
 
Is Software Engineering A Profession?
Is Software Engineering A Profession?Is Software Engineering A Profession?
Is Software Engineering A Profession?
 
Social Distancing is not Behaving Distantly
Social Distancing is not Behaving DistantlySocial Distancing is not Behaving Distantly
Social Distancing is not Behaving Distantly
 
The Great Scala Makeover
The Great Scala MakeoverThe Great Scala Makeover
The Great Scala Makeover
 
Transitioning Android Teams Into Kotlin
Transitioning Android Teams Into KotlinTransitioning Android Teams Into Kotlin
Transitioning Android Teams Into Kotlin
 
Simpler and Safer Java Types (via the Vavr and Lambda Libraries)
Simpler and Safer Java Types (via the Vavr and Lambda Libraries)Simpler and Safer Java Types (via the Vavr and Lambda Libraries)
Simpler and Safer Java Types (via the Vavr and Lambda Libraries)
 
The Three Horse Race
The Three Horse RaceThe Three Horse Race
The Three Horse Race
 
The Bestiary of Pure Functional Programming
The Bestiary of Pure Functional Programming The Bestiary of Pure Functional Programming
The Bestiary of Pure Functional Programming
 
BelTech 2019 Presenters Workshop
BelTech 2019 Presenters WorkshopBelTech 2019 Presenters Workshop
BelTech 2019 Presenters Workshop
 
Kotlin The Whole Damn Family
Kotlin The Whole Damn FamilyKotlin The Whole Damn Family
Kotlin The Whole Damn Family
 

Recently uploaded

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
vu2urc
 

Recently uploaded (20)

Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
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
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
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?
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
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
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
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
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
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
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 

A Sceptical Guide to Functional Programming

  • 1.
  • 2. Feel free to tweet #devbash
  • 3. A Sceptical Guide to Functional Programming Garth Gilmour (garth.gilmour@instil.co)
  • 4. In the Belfast IT Forum BASH the audience are entertained by two separate and unequal types of presenter. World class experts who understand the topic they are presenting on and uninformed dilettantes who mither on about stuff they barely understand. This is the latter 
  • 5.
  • 6.
  • 7. This is a Sceptical Roadmap   Personally I really like FP   Not so sure about FP programmers   Some things I’m going to say will really annoy any FP purists out there...
  • 8. Don't program in Java!! Why not? Its restrictive – everything has to be an object!! What should I use?
  • 9. Program in Lisp!! Why? Its brilliant – everything has to be a list!!!! Erm.....
  • 10. Or better yet Haskell!! Why? Its brilliant – you cant do anything except pure math!!!! Right...bye....
  • 11.
  • 12. A Puzzle For You…
  • 13. A Puzzle For You…
  • 15. Pure Languages Vs. Hybrids JavaScript Ruby Scala F# Clojure Haskell ClojureScript CoffeeScript Dart Groovy Powershell
  • 16. The 1990’s Perl Delphi C++ C Python VB Lua
  • 17. The 2010’s (Part 1) Scala Groovy JRuby Java Clojure Jython Kotlin
  • 18. The 2010’s (Part 2) C# PowerShell F# CLR VB IronRuby IronPython
  • 19. The 2010’s (Part 3) Dart CoffeeScript GWT JavaScript ClojureScript Many more ...
  • 20.
  • 21. Does the Language Matter? In the Soviet army it takes more courage to retreat than advance. Joseph Stalin Miyamoto Musashi
  • 22. Does the Language Matter?
  • 24. I Like Scala... package demos.scala.classes.basic class Employee(val name : String, val age : Int, val salary : Double) $ javap -private demos.scala.classes.basic.Employee Compiled from "Employee.scala" public class demos.scala.classes.basic.Employee extends java.lang.Object implements scala.ScalaObject{ private final java.lang.String name; private final int age; private final double salary; public java.lang.String name(); public int age(); public double salary(); public demos.scala.classes.basic.Employee(java.lang.String, int, double); }
  • 25.
  • 26.
  • 27.
  • 28. A Quick Word On Clojure   A LISP with more syntax than ((( )))   Dynamically typed and mostly functional   Integrates fully with the JVM/CLR   Extensive support for concurrency   Via efficient but immutable collections
  • 29.
  • 30.
  • 31. (defn printRow [rowNum height] (dotimes [n (- height rowNum)] (print " ")) (dotimes [n (- (* rowNum 2) 1)] (print "#")) (println)) (defn printPyramid [height] (dotimes [n height] (printRow (+ n 1) height))) (println "Enter the height of the pyramid...") (printPyramid (Integer/parseInt (read-line)))
  • 32.
  • 34.
  • 35. Back to the Quiz…
  • 36. The Puzzle Once Again…
  • 37. The Puzzle Once Again…
  • 38.
  • 39. What Makes this Functional?   Functional Composition   Immutable State   First Class Functions   Internal Iteration   Declarative Feel   Use of a DSL
  • 40. Will Look Better in Dart…
  • 41.
  • 42. You Are Doing FP Already (Kinda)   If you program in:   XSLT (my favourite language)   JavaScript (esp. if you use JQuery, Dojo etc…)   C# from VS2008 onwards (esp. LINQ)   Java (believe it or not…)   If you use libraries like Guava / Google Collections   If you follow certain coding conventions / best practises   Ruby or Python   Then you are already using FP techniques   Even if you don’t already know it
  • 43. Is XSLT a Functional Language? <xsl:template match="title"> <header> <h1><xsl:value-of select="text()"/></h1> </header> </xsl:template> <title>Introduction to Java</title> <header> <h1>Introduction to Java</h1> </header>
  • 44. Is XSLT a Functional Language? Stylesheet ? Output Tree Input Tree XSLT Engine ? ?
  • 45.
  • 46. LINQ is a Functional Technology Query Expression Tree LINQ to SQL C# Compiler Plug-In ?
  • 47. No Fear (Well Just A Little) Pure Bowel Knotting Terror
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55. def main(args : Array[String]) { println("---Demo 1---") val limit = 6 (1 to limit).foreach(num => printf("%d ", num)) println (1 to limit).foreach(printf("%d ", _)) println("nn---Demo 2 ---") val data = List(10,11,12,13,14,15) val result1 = data.foldLeft(1000)((a,b) => a + b) val result2 = data.foldLeft(2000)(_ + _) println(result1) println(result2) println("n---Demo 3 ---") val text = "abc123def456ghi789" val newText = "[a-z]{3}".r.replaceAllIn(text, _.group(0).toUpperCase()) println(newText) }
  • 56.
  • 57. (defn times2 [x] (* x 2)) (defn greaterThan15 [x] (> x 15)) (def myvector [10 12 14 16 18 20 22 24]) (def result1 (map times2 myvector)) (def result2 (map (fn [x] (* x 2)) myvector)) (def result3 (map #(* %1 2) myvector)) (def result4 (filter greaterThan15 myvector)) (def result5 (filter (fn [x] (> x 15)) myvector)) (def result6 (filter #(> %1 15) myvector)) (def result7 (map #(* %1 2) (filter #(> %1 15) myvector)))
  • 58.
  • 59.
  • 60. The Road Not Taken... The newest version of the Microsoft Visual J++ development environment supports a language construct called delegates or bound method references… It is unlikely that the Java programming language will ever include this construct. Sun already carefully considered adopting it in 1996, to the extent of building and discarding working prototypes. Our conclusion was that bound method references are unnecessary and detrimental to the language… We believe bound method references are unnecessary because another design alternative, inner classes, provides equal or superior functionality. In particular, inner classes fully support the requirements of user-interface event handling, and have been used to implement a user-interface API at least as comprehensive as the Windows Foundation Classes. We believe bound method references are harmful because they detract from the simplicity of the Java programming language and the pervasively object-oriented character of the APIs…. Extracts From: About Microsoft’s “Delegates" Whitepaper by the Java language team at JavaSoft
  • 61.
  • 62. private void demoTemplatesAndCallbacks(HibernateTemplate template) { String query = "select delivery.course.title from Delivery delivery"; List titles = template.executeFind(new QueryCallback(query)); System.out.println("Courses being delivered are:"); for(Object title : titles) { System.out.printf("t%sn",title); } } public class QueryCallback implements HibernateCallback { public QueryCallback(String query) { this.queryStr = query; } public Object doInHibernate(Session session) throws HibernateException, SQLException { Query query = session.createQuery(queryStr); return query.list(); } public String queryStr; }
  • 63. private void demoTemplatesAndCallbacks(HibernateTemplate template) { String query = "select delivery.course.title from Delivery delivery"; List titles = template.executeFind((s) => s.createQuery(query).list()); System.out.println("Courses being delivered are:"); titles.forEach((t) => System.out.printf("t%sn",title)); }
  • 64. SwingUtilities.invokeLater(new Runnable() { public void run() { textField.setText(theResult); } }); SwingUtilities.invokeLater(() => textField.setText(theResult));
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70. val originalData = List("ab", "cd", "ef", "gh", "ij", "kl") val newData1 = originalData.map((str) => new Result(str + "yy", Thread.currentThread.getId)) val newData2 = originalData.par.map((str) => new Result(str + "zz", Thread.currentThread.getId)
  • 72. Programmer a=a+1 Mathematician
  • 73. class Person { public String toString() { StringBuilder sb = new StringBuilder(); Person earning sb.append(“Person earning ”); 5000.0 with tax of sb.append(salary.calcMonthlyBasic()); 763 and pension sb.append(“ with tax of ”); payment of 469.0 sb.append(salary.monthlyTax()); sb.append(“ and pension payment of ”); sb.append(salary.monthlyPension()); return sb.toString(); } class Person { private Salary salary; public String toString() { } StringBuilder sb = new StringBuilder(); sb.append(“Person earning ”); sb.append(5000.0); Person earning sb.append(“ with tax of ”); 5000.0 with tax of sb.append(salary.monthlyTax()); sb.append(“ and pension payment of ”); 0 and pension sb.append(salary.monthlyPension()); payment of 0 return sb.toString(); } private Salary salary; }
  • 74. What's The Use?   Code is easier to reason about.   Compilers & VM’s can partition code automatically into sections and run them in parallel.   Lazy Evaluation if(foo() && bar()) { func(foo(), bar()); zed(); ------------------------------- } void func(a, b) { if(zed()) { if(foo() || bar()) { c = a + 1; //foo not called till here zed(); } } }
  • 75. The Point of Having a VM
  • 78. Objects Threads
  • 79. Another reason that you might be interesting in purity is that it gives you a better handle on parallelism. It doesn't make parallelism easy, but it kinda makes it feel a bit more within reach. ... I dont think its parallelism without tears, but it kinda gives you a chance in a way that the imperative by default with shared mutable state makes things very difficult. Simon Peyton Jones (On SE Radio Ep 108)
  • 80. But all a purely functional program can do is heat up the CPU - and that's still a side effect!!!
  • 82.
  • 83.
  • 84.
  • 85. def joinUp(separator : Char)(data : Array[String]) = { val sb = new StringBuilder for(str <- data) { sb.append(str) sb.append(separator) } sb.substring(0,sb.length - 1) } def joinUpWithHashes = joinUp('#') _ def joinUpWithHyphens = joinUp('-') _ def main(args : Array[String]) { val testData = Array("abc","def","ghi","jkl","mno") println(joinUp(',')(testData)) println(joinUpWithHashes(testData)) println(joinUpWithHyphens(testData)) }
  • 87.
  • 88.
  • 90. int foo(int a) { int foo(int a) { int b = zed(); int b = zed(); if(b > a) { if(b > a) { return a + foo(b); return foo(a + b); } else { } else { return b; return 1; } } } } a b a b a a b b a b
  • 92.
  • 93. def processItem(item : StockItem) { item match { case Book(_,"Crime") => println("Found a crime novel") case Movie(_,MovieType.DVD) => println("Found a DVD movie") case CD(_,_,12) => println("Found a CD with 12 tracks") case CD(_,"Soundgarden",_) => println("Found a CD by Soundgarden") case Book(_,_) => println("Found some kind of book") case _ => println("Found something...") } }
  • 95. Monads By Metaphor int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);
  • 96. Monads By Quotation Monads turn control flow into data flow, where it can be constrained by the type system. Oleg Kiselyov
  • 97. Monads By Example   Monads remove the boilerplate involved when extracting / inserting values from “Amplified Types”   Whilst enabling the compiler to perform extra checks   Kind of like AOP but without the runtime overhead List<T> Map<T,U> Option<T> (aka Maybe<T>) EntityManager<T> Repository<T> ThreadSafe<T> IO<T>
  • 98. void printPostcode(Person person) { String code = person.findAddress().findPostcode().findValue(); System.out.println(code); } void printPostcode(Person person) { Address address = person.findAddress(); if(address != null) { Postcode postcode = address.findPostcode() if(postcode != null) { String code = postcode.findValue(); System.out.println(code); } } }
  • 99.
  • 100. class Person(val name : String, val address : Address) { def findAddress() : Option[Address] = { if(address == null) { None } else { Some(address) } } }
  • 101.
  • 102. def printPostcodeIfExists(person : Person) { println("Working with " + person.name) for ( place <- person findAddress; code <- place findPostcode; result <- code findValue ) println(result) }
  • 103.
  • 104. I Trust That's All Clear Now 
  • 105. One Final Thought... OO makes code understandable by encapsulating moving parts. FP makes code understandable by minimizing moving parts. Michael Feathers
  • 106. To Summarize...   You can start doing this today   Get familiar with the FP parts of your language   Prefer internal iteration to explicit loops   Play with making sections of code side-effect free   Experiment with building functional machines   Use the emerging support for ‘hands-free’ concurrency   Review, measure, assess, adjust   Make this years new language an FP one   Try Scala to extend what you already know into FP   Try Clojure, F# or Haskell to get a new perspective
  • 107.
  • 109. 21st March 2012 Kevlin Henney A Question of Craftsmanship
  • 110. April/May ?? We are speaking to a few exciting people!