Your SlideShare is downloading. ×
Feel free to tweet    #devbash
A Sceptical Guide to   Functional ProgrammingGarth Gilmour (garth.gilmour@instil.co)
In the Belfast IT Forum BASH the audience areentertained by two separate and unequal types ofpresenter. World class expert...
This is a Sceptical Roadmap  Personally I really like FP  Not so sure about FP programmers  Some things I’m going to sa...
Dont program  in Java!!                 Why not?Its restrictive – everything   has to be an object!!                What s...
Program in   Lisp!!                    Why?Its brilliant – everything    has to be a list!!!!                   Erm.....
Or better yet    Haskell!!                   Why?  Its brilliant – you cant doanything except pure math!!!!              R...
A Puzzle For You…
A Puzzle For You…
Some FP Languages
Pure Languages Vs. Hybrids       JavaScript       Ruby   Scala   F#      Clojure Haskell                                  ...
The 1990’s                   Perl      DelphiC++            C          Python                   VB      Lua
The 2010’s (Part 1)         Scala            GroovyJRuby             Java             Clojure                         Jyth...
The 2010’s (Part 2)       C#           PowerShellF#          CLR                  VB IronRuby         IronPython
The 2010’s (Part 3)           Dart                 CoffeeScriptGWT               JavaScriptClojureScript                  ...
Does the Language Matter?                       In the Soviet army it                       takes more courage to         ...
Does the Language Matter?
Sometimes Language Helps
I Like Scala...package demos.scala.classes.basicclass Employee(val name : String,               val age : Int,            ...
A Quick Word On Clojure    A LISP with more syntax than ((( )))    Dynamically typed and mostly functional    Integrate...
(defn printRow [rowNum height] (dotimes [n (- height rowNum)] (print " ")) (dotimes [n (- (* rowNum 2) 1)] (print "#")) (p...
@FooBarpublic 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 Iteratio...
Will Look Better in Dart…
You Are Doing FP Already (Kinda)    If you program in:       XSLT (my favourite language)       JavaScript (esp. if you...
Is XSLT a Functional Language?           <xsl:template match="title">              <header>                   <h1><xsl:val...
Is XSLT a Functional Language?     Stylesheet?                               Output Tree     Input Tree                  X...
LINQ is a Functional Technology      Query                  Expression Tree                                    LINQ to SQL...
No Fear(Well Just A Little)Pure BowelKnotting Terror
First-Class Functions
def main(args : Array[String]) { println("---Demo 1---") val limit = 6 (1 to limit).foreach(num => printf("%d ", num)) pri...
(defn times2 [x] (* x 2))(defn greaterThan15 [x] (> x 15))(def myvector [10 12 14 16 18 20 22 24])(def result1 (map times2...
The Road Not Taken... The newest version of the Microsoft Visual J++ development environment supports a language construct...
private void demoTemplatesAndCallbacks(HibernateTemplate template) {    String query = "select delivery.course.title from ...
private void demoTemplatesAndCallbacks(HibernateTemplate template) {    String query = "select delivery.course.title from ...
SwingUtilities.invokeLater(new Runnable() {                                public void run() {                            ...
val originalData = List("ab", "cd", "ef", "gh", "ij", "kl")val newData1 =    originalData.map((str) => new Result(str + "y...
ReferentialTransparency
Programmera=a+1        Mathematician
class Person {    public String toString() {        StringBuilder sb = new StringBuilder();                Person earning ...
Whats The Use?    Code is easier to reason about.    Compilers & VM’s can partition code automatically     into sections...
The Point of Having a VM
What Happens?
Whooops!
Objects   Threads
Another reason that you might be interesting in purity is that itgives you a better handle on parallelism. It doesnt makep...
But all a purely functional programcan do is heat up the CPU - andthats 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(...
Type Inference& Parametric Polymorphism
RecursionTail Recursion
int foo(int a) {               int foo(int a) {     int b = zed();                 int b = zed();     if(b > a) {         ...
PatternMatching
def processItem(item : StockItem) {  item match {    case Book(_,"Crime") => println("Found a crime novel")    case Movie(...
Monads(Sequence Expressions)
Monads By Metaphor   int pthread_create(pthread_t *thread,                 const pthread_attr_t *attr,                 voi...
Monads By Quotation   Monads turn control flow into data   flow, where it can be constrained   by the type system.        ...
Monads By Example    Monads remove the boilerplate involved when     extracting / inserting values from “Amplified Types”...
void printPostcode(Person person) {    String code = person.findAddress().findPostcode().findValue();    System.out.printl...
class Person(val name : String, val address : Address) {  def findAddress() : Option[Address] = {    if(address == null) {...
def printPostcodeIfExists(person : Person) {   println("Working with " + person.name)   for (        place <- person findA...
I Trust Thats All Clear Now 
One Final Thought...    OO makes code understandable by    encapsulating moving parts. FP makes    code understandable by ...
To Summarize...    You can start doing this today       Get familiar with the FP parts of your language       Prefer in...
Coming soon....
21st March 2012Kevlin Henney   A Question of   Craftsmanship
April/May        ??We are speaking to afew exciting people!
September 2012Jim Webber  Mr NOSQL
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
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
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
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
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
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
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
Upcoming SlideShare
Loading in...5
×

A Sceptical Guide to Functional Programming

940

Published on

Published in: Technology
0 Comments
3 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
940
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
0
Comments
0
Likes
3
Embeds 0
No embeds

No notes for slide

Transcript of "A Sceptical Guide to Functional Programming"

  1. 1. Feel free to tweet #devbash
  2. 2. A Sceptical Guide to Functional ProgrammingGarth Gilmour (garth.gilmour@instil.co)
  3. 3. In the Belfast IT Forum BASH the audience areentertained by two separate and unequal types ofpresenter. World class experts who understand thetopic they are presenting on and uninformed dilettanteswho mither on about stuff they barely understand.This is the latter 
  4. 4. 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...
  5. 5. Dont program in Java!! Why not?Its restrictive – everything has to be an object!! What should I use?
  6. 6. Program in Lisp!! Why?Its brilliant – everything has to be a list!!!! Erm.....
  7. 7. Or better yet Haskell!! Why? Its brilliant – you cant doanything except pure math!!!! Right...bye....
  8. 8. A Puzzle For You…
  9. 9. A Puzzle For You…
  10. 10. Some FP Languages
  11. 11. Pure Languages Vs. Hybrids JavaScript Ruby Scala F# Clojure Haskell ClojureScript CoffeeScript Dart Groovy Powershell
  12. 12. The 1990’s Perl DelphiC++ C Python VB Lua
  13. 13. The 2010’s (Part 1) Scala GroovyJRuby Java Clojure Jython Kotlin
  14. 14. The 2010’s (Part 2) C# PowerShellF# CLR VB IronRuby IronPython
  15. 15. The 2010’s (Part 3) Dart CoffeeScriptGWT JavaScriptClojureScript Many more ...
  16. 16. Does the Language Matter? In the Soviet army it takes more courage to retreat than advance. Joseph Stalin Miyamoto Musashi
  17. 17. Does the Language Matter?
  18. 18. Sometimes Language Helps
  19. 19. I Like Scala...package demos.scala.classes.basicclass Employee(val name : String, val age : Int, val salary : Double)$ javap -private demos.scala.classes.basic.EmployeeCompiled 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);}
  20. 20. 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
  21. 21. (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)))
  22. 22. @FooBarpublic class MyClass {}
  23. 23. Back to the Quiz…
  24. 24. The Puzzle Once Again…
  25. 25. The Puzzle Once Again…
  26. 26. What Makes this Functional?  Functional Composition  Immutable State  First Class Functions  Internal Iteration  Declarative Feel  Use of a DSL
  27. 27. Will Look Better in Dart…
  28. 28. 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
  29. 29. 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>
  30. 30. Is XSLT a Functional Language? Stylesheet? Output Tree Input Tree XSLT Engine ??
  31. 31. LINQ is a Functional Technology Query Expression Tree LINQ to SQL C# Compiler Plug-In ?
  32. 32. No Fear(Well Just A Little)Pure BowelKnotting Terror
  33. 33. First-Class Functions
  34. 34. 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)}
  35. 35. (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)))
  36. 36. 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
  37. 37. 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;}
  38. 38. 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));}
  39. 39. SwingUtilities.invokeLater(new Runnable() { public void run() { textField.setText(theResult); } });SwingUtilities.invokeLater(() => textField.setText(theResult));
  40. 40. 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)
  41. 41. ReferentialTransparency
  42. 42. Programmera=a+1 Mathematician
  43. 43. 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; }
  44. 44. Whats 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(); } } }
  45. 45. The Point of Having a VM
  46. 46. What Happens?
  47. 47. Whooops!
  48. 48. Objects Threads
  49. 49. Another reason that you might be interesting in purity is that itgives you a better handle on parallelism. It doesnt makeparallelism easy, but it kinda makes it feel a bit more withinreach....I dont think its parallelism without tears, but it kinda gives youa chance in a way that the imperative by default with sharedmutable state makes things very difficult. Simon Peyton Jones (On SE Radio Ep 108)
  50. 50. But all a purely functional programcan do is heat up the CPU - andthats still a side effect!!!
  51. 51. Higher-Order Functions(inc. Currying & Partial Invoke)
  52. 52. 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)) }
  53. 53. Type Inference& Parametric Polymorphism
  54. 54. RecursionTail Recursion
  55. 55. 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
  56. 56. PatternMatching
  57. 57. 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...") }}
  58. 58. Monads(Sequence Expressions)
  59. 59. Monads By Metaphor int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);
  60. 60. Monads By Quotation Monads turn control flow into data flow, where it can be constrained by the type system. Oleg Kiselyov
  61. 61. 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>
  62. 62. 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); } } }
  63. 63. class Person(val name : String, val address : Address) { def findAddress() : Option[Address] = { if(address == null) { None } else { Some(address) } }}
  64. 64. def printPostcodeIfExists(person : Person) { println("Working with " + person.name) for ( place <- person findAddress; code <- place findPostcode; result <- code findValue ) println(result)}
  65. 65. I Trust Thats All Clear Now 
  66. 66. One Final Thought... OO makes code understandable by encapsulating moving parts. FP makes code understandable by minimizing moving parts. Michael Feathers
  67. 67. 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
  68. 68. Coming soon....
  69. 69. 21st March 2012Kevlin Henney A Question of Craftsmanship
  70. 70. April/May ??We are speaking to afew exciting people!
  71. 71. September 2012Jim Webber Mr NOSQL

×