• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
A Sceptical Guide to Functional Programming

A Sceptical Guide to Functional Programming






Total Views
Views on SlideShare
Embed Views



1 Embed 7

http://www.linkedin.com 7



Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
Post Comment
Edit your comment

    A Sceptical Guide to Functional Programming A Sceptical Guide to Functional Programming Presentation Transcript

    • 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 experts who understand thetopic they are presenting on and uninformed dilettanteswho 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...
    • Dont 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 doanything 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 DelphiC++ C Python VB Lua
    • The 2010’s (Part 1) Scala GroovyJRuby Java Clojure Jython Kotlin
    • The 2010’s (Part 2) C# PowerShellF# CLR VB IronRuby IronPython
    • The 2010’s (Part 3) Dart CoffeeScriptGWT JavaScriptClojureScript 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.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);}
    • 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)))
    • @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 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 BowelKnotting 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)
    • ReferentialTransparency
    • Programmera=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; }
    • 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(); } } }
    • 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 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)
    • 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(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
    • RecursionTail 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
    • PatternMatching
    • 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 Thats 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 2012Kevlin Henney A Question of Craftsmanship
    • April/May ??We are speaking to afew exciting people!
    • September 2012Jim Webber Mr NOSQL