SlideShare a Scribd company logo
A Sceptical Guide to Functional Programming
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 
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
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 Sceptical Guide to Functional Programming
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 ...
A Sceptical Guide to Functional Programming
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 Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
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
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
(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)))
A Sceptical Guide to Functional Programming
@FooBar
public class MyClass {
}
A Sceptical Guide to Functional Programming
Back to the Quiz…
The Puzzle Once Again…
The Puzzle Once Again…
A Sceptical Guide to Functional Programming
What Makes this Functional?

    Functional Composition
    Immutable State
    First Class Functions
    Internal Iteration
    Declarative Feel
    Use of a DSL
Will Look Better in Dart…
A Sceptical Guide to Functional Programming
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
                                              ?
?
A Sceptical Guide to Functional Programming
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
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
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)
}
A Sceptical Guide to Functional Programming
(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)))
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
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
A Sceptical Guide to Functional Programming
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));
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
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)
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
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
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
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
A Sceptical Guide to Functional Programming
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);
            }
        }
    }
A Sceptical Guide to Functional Programming
class Person(val name : String, val address : Address) {
  def findAddress() : Option[Address] = {
    if(address == null) {
      None
    } else {
      Some(address)
    }
  }
}
A Sceptical Guide to Functional Programming
def printPostcodeIfExists(person : Person) {
   println("Working with " + person.name)
   for (
        place <- person findAddress;
        code <- place findPostcode;
        result <- code findValue
      ) println(result)
}
A Sceptical Guide to Functional Programming
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
A Sceptical Guide to Functional Programming
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 (20)

PDF
Workshop Scala
Bert Van Vreckem
 
PDF
Starting with Scala : Frontier Developer's Meetup December 2010
Derek Chen-Becker
 
PPTX
Scala fundamentals
Alfonso Ruzafa
 
PDF
Stepping Up : A Brief Intro to Scala
Derek Chen-Becker
 
ODP
Functional Objects & Function and Closures
Sandip Kumar
 
PDF
Demystifying functional programming with Scala
Denis
 
PDF
Scala
Sven Efftinge
 
PPTX
Scala Intro
Alexey (Mr_Mig) Migutsky
 
PDF
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Sungchul Park
 
KEY
Static or Dynamic Typing? Why not both?
Mario Camou Riveroll
 
PDF
Ankara Jug - Practical Functional Programming with Scala
Ensar Basri Kahveci
 
KEY
Clojure Intro
thnetos
 
PDF
Scala at HUJI PL Seminar 2008
Yardena Meymann
 
PDF
Design Patterns - Compiler Case Study - Hands-on Examples
Ganesh Samarthyam
 
PPTX
Kotlin
YeldosTanikin
 
PDF
Scala for Java programmers
輝 子安
 
PPTX
All about scala
Yardena Meymann
 
PDF
Functional programming in Scala
Damian Jureczko
 
PPT
Scala uma poderosa linguagem para a jvm
Isaias Barroso
 
PPTX
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Andrew Phillips
 
Workshop Scala
Bert Van Vreckem
 
Starting with Scala : Frontier Developer's Meetup December 2010
Derek Chen-Becker
 
Scala fundamentals
Alfonso Ruzafa
 
Stepping Up : A Brief Intro to Scala
Derek Chen-Becker
 
Functional Objects & Function and Closures
Sandip Kumar
 
Demystifying functional programming with Scala
Denis
 
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Sungchul Park
 
Static or Dynamic Typing? Why not both?
Mario Camou Riveroll
 
Ankara Jug - Practical Functional Programming with Scala
Ensar Basri Kahveci
 
Clojure Intro
thnetos
 
Scala at HUJI PL Seminar 2008
Yardena Meymann
 
Design Patterns - Compiler Case Study - Hands-on Examples
Ganesh Samarthyam
 
Scala for Java programmers
輝 子安
 
All about scala
Yardena Meymann
 
Functional programming in Scala
Damian Jureczko
 
Scala uma poderosa linguagem para a jvm
Isaias Barroso
 
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Andrew Phillips
 

Viewers also liked (20)

PDF
Paris Kafka Meetup - Concepts & Architecture
Florian Hussonnois
 
PDF
Paris Kafka Meetup - How to develop with Kafka
Florian Hussonnois
 
PDF
Chicago Hadoop Users Group: Enterprise Data Workflows
Paco Nathan
 
PDF
Spring 3.1 and MVC Testing Support - 4Developers
Sam Brannen
 
PDF
Reactive Programming With Akka - Lessons Learned
Daniel Sawano
 
PDF
The no-framework Scala Dependency Injection Framework
Adam Warski
 
PDF
Actor Based Asyncronous IO in Akka
drewhk
 
PDF
Effective akka scalaio
shinolajla
 
PDF
Efficient HTTP Apis
Adrian Cole
 
PDF
Beginning Haskell, Dive In, Its Not That Scary!
priort
 
PPTX
C*ollege Credit: Creating Your First App in Java with Cassandra
DataStax
 
PDF
Building ‘Bootiful’ microservices cloud
Idan Fridman
 
PDF
Effective Actors
shinolajla
 
KEY
Curator intro
Jordan Zimmerman
 
PDF
Using Apache Solr
pittaya
 
PDF
Effective Scala (SoftShake 2013)
mircodotta
 
PDF
Composable and streamable Play apps
Yevgeniy Brikman
 
PDF
An example of Future composition in a real app
Phil Calçado
 
PDF
Design for developers
Johan Ronsse
 
PPTX
19 challenging thoughts about leadership 2nd edition
TFLI
 
Paris Kafka Meetup - Concepts & Architecture
Florian Hussonnois
 
Paris Kafka Meetup - How to develop with Kafka
Florian Hussonnois
 
Chicago Hadoop Users Group: Enterprise Data Workflows
Paco Nathan
 
Spring 3.1 and MVC Testing Support - 4Developers
Sam Brannen
 
Reactive Programming With Akka - Lessons Learned
Daniel Sawano
 
The no-framework Scala Dependency Injection Framework
Adam Warski
 
Actor Based Asyncronous IO in Akka
drewhk
 
Effective akka scalaio
shinolajla
 
Efficient HTTP Apis
Adrian Cole
 
Beginning Haskell, Dive In, Its Not That Scary!
priort
 
C*ollege Credit: Creating Your First App in Java with Cassandra
DataStax
 
Building ‘Bootiful’ microservices cloud
Idan Fridman
 
Effective Actors
shinolajla
 
Curator intro
Jordan Zimmerman
 
Using Apache Solr
pittaya
 
Effective Scala (SoftShake 2013)
mircodotta
 
Composable and streamable Play apps
Yevgeniy Brikman
 
An example of Future composition in a real app
Phil Calçado
 
Design for developers
Johan Ronsse
 
19 challenging thoughts about leadership 2nd edition
TFLI
 

Similar to A Sceptical Guide to Functional Programming (20)

KEY
Scala clojure techday_2011
Thadeu Russo
 
PPTX
Intro to scala
Joe Zulli
 
PDF
Clojure for Java developers - Stockholm
Jan Kronquist
 
PDF
Programming Android Application in Scala.
Brian Hsu
 
PDF
Introduction to clojure
Abbas Raza
 
PDF
Scala in Places API
Łukasz Bałamut
 
PDF
Object-oriented Basics
Jamie (Taka) Wang
 
PPT
Scala in a nutshell by venkat
Venkateswaran Kandasamy
 
PDF
Kotlin Developer Starter in Android projects
Bartosz Kosarzycki
 
PDF
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
STX Next
 
PPTX
Scala
suraj_atreya
 
PDF
What can be done with Java, but should better be done with Erlang (@pavlobaron)
Pavlo Baron
 
PDF
обзор Python
Yehor Nazarkin
 
PPTX
Clojure And Swing
Skills Matter
 
PDF
Introduction to Scalding and Monoids
Hugo Gävert
 
PDF
The Scala Programming Language
league
 
PPT
Scala Talk at FOSDEM 2009
Martin Odersky
 
PPTX
Scala for curious
Tim (dev-tim) Zadorozhniy
 
PDF
Scala @ TechMeetup Edinburgh
Stuart Roebuck
 
ODP
Scala ntnu
Alf Kristian Støyle
 
Scala clojure techday_2011
Thadeu Russo
 
Intro to scala
Joe Zulli
 
Clojure for Java developers - Stockholm
Jan Kronquist
 
Programming Android Application in Scala.
Brian Hsu
 
Introduction to clojure
Abbas Raza
 
Scala in Places API
Łukasz Bałamut
 
Object-oriented Basics
Jamie (Taka) Wang
 
Scala in a nutshell by venkat
Venkateswaran Kandasamy
 
Kotlin Developer Starter in Android projects
Bartosz Kosarzycki
 
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
STX Next
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
Pavlo Baron
 
обзор Python
Yehor Nazarkin
 
Clojure And Swing
Skills Matter
 
Introduction to Scalding and Monoids
Hugo Gävert
 
The Scala Programming Language
league
 
Scala Talk at FOSDEM 2009
Martin Odersky
 
Scala for curious
Tim (dev-tim) Zadorozhniy
 
Scala @ TechMeetup Edinburgh
Stuart Roebuck
 

More from Garth Gilmour (20)

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

Recently uploaded (20)

PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PDF
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PDF
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 

A Sceptical Guide to Functional Programming

  • 2. Feel free to tweet #devbash
  • 3. A Sceptical Guide to Functional Programming Garth Gilmour ([email protected])
  • 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 
  • 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....
  • 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 ...
  • 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); }
  • 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
  • 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)))
  • 35. Back to the Quiz…
  • 36. The Puzzle Once Again…
  • 37. The Puzzle Once Again…
  • 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…
  • 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 ? ?
  • 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
  • 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) }
  • 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)))
  • 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
  • 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));
  • 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!!!
  • 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)) }
  • 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
  • 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); } } }
  • 100. class Person(val name : String, val address : Address) { def findAddress() : Option[Address] = { if(address == null) { None } else { Some(address) } } }
  • 102. def printPostcodeIfExists(person : Person) { println("Working with " + person.name) for ( place <- person findAddress; code <- place findPostcode; result <- code findValue ) println(result) }
  • 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
  • 109. 21st March 2012 Kevlin Henney A Question of Craftsmanship
  • 110. April/May ?? We are speaking to a few exciting people!