0
About Functional Programming(Robust Programming)<br />AapoKyrölä, 23.3.2011<br />Sulake<br />
Contents<br />Motivation: some issues with OOP and Java<br />Introduction to Functional Programming<br />Functional Progra...
Motivation: Problems with Object-Oriented Programming and Java<br />
Fundamental Design Problem of Java<br />Not well-typed => Nullpointers<br />Programmer should handle two cases explicitly:...
In Standard ML<br />
OOP: criticism<br />Class/Object structure cumbersome to change.<br />a class hierarchy might be natural from some point o...
Object-relational mapping<br />Always hated…<br />a) Intuitively, object should have an identity<br />But when you have ma...
ORM (continues)<br />c) Even bigger problem with relations<br />Identity of the objects in collection?<br />Cumbersome to ...
Side effects<br />When you call a method, it can change the state, even if it is named getX().<br />At least previously in...
Who manages an object?<br />Java does not have immutable objects<br />Need to “wrap” them by hand (Collections.unmodifiabl...
Key to more robust code	<br />Compiler and type-system should do more!<br />Generics are even worse…<br />End of rant.<br />
Quick introduction to Functional Programming Languages<br />
Contents<br />Some history<br />Functional vs. imperative languages<br />Declarative programming.<br />Functions as values...
History<br />Lambda calculus (30s-40s): mathematical theory for computing with functions (Church).<br />LISP (50s): motiva...
History (cont.)<br />Functional programming has (so far) mostly been favored in the academia<br />Mathematically consisten...
FP: new coming?<br />Functional languages compatible with mainstream languages:<br />Microsoft’s F#, based on OCaML<br />S...
What is Functional Programming?<br />Imperative program executes sequence of commands to compute a value and modifies the ...
More function declarations<br />> fun      factorial 1 = 1<br />#        | factorial n = n * factorial(n-1);<br />“factori...
More function declarations<br />More pattern matching for types:<br />
Functional programming (cont.)<br />Imperative program executes commands, functional program evaluates expressions.<br />F...
Functional programming (cont.)<br />Functions are values, and can be passed as parameters (anonymous or named):<br />Examp...
FP (cont.): Functionals<br />map<br />> valmylist = [1,2,3,4,5,6,7,8,9,10];<br />valmylist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1...
Referential Transparency<br />= expression can be safely replaced by its values<br />= no side-effects.<br />Enables reaso...
Type system<br />Very powerful feature of ML (and Haskell):<br />use it for your benefit. Compiler can detect many errors ...
Type system: algebraic datatypes<br />Product types (records=structs) and sum-types (union of types, such as: user|pet|fur...
ADT (cont.)<br />
ADT (cont.)<br />Let’s now add a new room object type, “wallitem”.<br />But we forget to add a case to<br />“blocks_coordi...
ADT (cont.)<br />But compiler warns us about this!<br />
ADT (cont.)<br />Compiler also warns about redundant cases<br />typical error.<br />Consider this in Java<br />perhaps you...
Parametric Polymorphism	<br />Close to C++ templates<br />unlike Java generics, first-class types (compile-time).<br />Rec...
Miscellanious<br />In practice, it is easy to very also inefficient code in SML (like it is with Java).<br />Garbage colle...
Functional Style with Java<br />Some ideas<br />
Functional Languages for JDK<br />Scala<br />gaining popularity.<br />compiles into Java bytecode, compatible with Java.<b...
1) Pattern: Immutable objects<br />If a “manager” returns an object, usually it should be immutable – and a copy:<br />cre...
2) Fail fast<br />Java does not do much sanity checking in compilation time, so try to make incorrect code fail quickly in...
3) Instead of modifying an object, create new ones<br />Avoids race conditions.<br />Java GC is really fast, and likes sho...
4) Assertions and Declarations<br />Functional:  @MessageHandler(id=.., need_session=true), @Moderator<br />Use conservati...
Do not switch assertions off!<br />“… it is absurd to make elaborate security checks on debugging runs, when no trust is p...
5) Poor man’s Closures	<br />Closures = anonymous/lambda functions<br />example from Groovy:<br />Unfortunately Java (not ...
Closure example<br />
6) Compute, do not store<br />If computing a value is reasonably light-weight, it is better to do that than store a precom...
Example<br />
Discussion<br />
Questions<br />Do you have experience on functional programming?<br />Opinion on using Hibernate vs. using explicit querie...
Resources<br />PolyML: http://www.polyml.org/<br />Google: “ocaml jane street cmu”<br />good video introduction to FP<br /...
Upcoming SlideShare
Loading in...5
×

About Functional Programming

2,339

Published on

My presentation at Sulake (www.sulake.com) about functional programming languages and how to adopt a functional-style in Java development. I argue that functional programs are more robust than imperative ones.

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
2,339
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
56
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide
  • Havent been here for two years speaking. Currently Ph.D. student in Carnegie Mellon: working on intersection of machine learning and distributed systems. Will study more parallel algorithms etc. further – this topic is very relevant for that. QUESTION: who has experience with Haskell, Scala, Standard ML, LISP?
  • Start with some provocation. A fundamental design flaw in Java, which contributes to unrobust code tremendously.What is wrong with this?What if userToBan is null? Either: compiler should never let banUser to be called with NULL, or one should make a case analysis:
  • In Standard ML: need to use type parameter “option” if type is nullable. In that case, each function must define cases for both non-null user (SOME) or null-user (NONE).If option is not set, value can never have null assignment.
  • There is a lot of criticism about OOP, but it is what people learn in school. Especailly “old school” OOP that uses inheritance heavily is very hard to manage. Of course there are good sides of OOP as well .
  • Disclaimers!
  • Has anyone used Scala, is it used? Sorry that I am not very well aware.
  • Point: functional languages have been there from the beginning. And by original computer scientist, functional programming was the proper way to study computation. Anyway, FP is not a new thing!
  • QUESTION: does Univ of Helsinki or HUT/Aalto teach functional languages? Lambda-calculus theory?
  • Note: this definition of sumlist is quite inefficient, since the recursion blows up. But we will see better version of this later. This is just to illustrate how functions are declarative.
  • Familiar from python, scala
  • This can be extremely useful.
  • are we using these?Especially for payments etc., recommend trying.
  • .. otherwise, the code gets bloated with wide try-catches and the session state can get screwed up. It is better to fail and close the session if a programmer bug is encountered.
  • It is quite bloated, but of course the map/MapClosure, etc. must be done only once.
  • Transcript of "About Functional Programming"

    1. 1. About Functional Programming(Robust Programming)<br />AapoKyrölä, 23.3.2011<br />Sulake<br />
    2. 2. Contents<br />Motivation: some issues with OOP and Java<br />Introduction to Functional Programming<br />Functional Programming –style in Java<br />
    3. 3. Motivation: Problems with Object-Oriented Programming and Java<br />
    4. 4. Fundamental Design Problem of Java<br />Not well-typed => Nullpointers<br />Programmer should handle two cases explicitly: userToBan is either null or not null.<br />OR, compiler should not allow assigning NULL to a reference (like in C++ &obj).<br />By proper typing, compiler would prevent null-pointers…<br />
    5. 5. In Standard ML<br />
    6. 6. OOP: criticism<br />Class/Object structure cumbersome to change.<br />a class hierarchy might be natural from some point of view, but for other (future) uses cumbersome.<br />Problems with Inheritance<br />much functionality hidden in superclasses.<br />Hard to manage: if behavior of superclass is changed, how does it affect all subclasses?<br />Especially in UI: subclass may depend on a not-intended behavior of a superclass.<br />Delegation usually better than inheritance (Spring)<br />better modularity with IOP than with object hierarchies.<br />API dependencies.<br />Makes refactoring hard.<br />
    7. 7. Object-relational mapping<br />Always hated…<br />a) Intuitively, object should have an identity<br />But when you have many copies of the object…<br />b) Queries with criteria-objects or example objects just stink.<br />Select * from sale where date>? and date<? order by date limit 10;<br />
    8. 8. ORM (continues)<br />c) Even bigger problem with relations<br />Identity of the objects in collection?<br />Cumbersome to control when you want the collections loaded (all that hibernate session stuff).<br />d) SQL is great, easy and powerful. Why switch away? Declarative programming is powerful.<br />
    9. 9. Side effects<br />When you call a method, it can change the state, even if it is named getX().<br />At least previously in Habbo: effects on database object cache.<br />Or : calling a collection method in hibernate object, user.getFriends().<br />You need to know if users were loaded in order to reason what happens.<br />
    10. 10. Who manages an object?<br />Java does not have immutable objects<br />Need to “wrap” them by hand (Collections.unmodifiableList()).<br />Error only on run-time. How do you handle such error? Should be compile-time.<br />Concurrency issues<br />Who manages multi-threaded access to an object? Read-only objects do not have this problem…<br />Easy to get deadlocks. <br />
    11. 11. Key to more robust code <br />Compiler and type-system should do more!<br />Generics are even worse…<br />End of rant.<br />
    12. 12. Quick introduction to Functional Programming Languages<br />
    13. 13. Contents<br />Some history<br />Functional vs. imperative languages<br />Declarative programming.<br />Functions as values.<br />High-order functions.<br />Referential transparency.<br />Power of the Type system in Standard ML.<br />All examples in Standard ML.<br />Next: how to program “functionally in Java”.<br />
    14. 14. History<br />Lambda calculus (30s-40s): mathematical theory for computing with functions (Church).<br />LISP (50s): motivated by artificial intelligence. Introduced high level data structures such as lists and trees. <br />Scheme, Clojure<br />Meta-language: ML (70s): for writing proof checkers.<br />Standard ML, OCaML, F#<br />Haskell (80s-90s) <br />
    15. 15. History (cont.)<br />Functional programming has (so far) mostly been favored in the academia<br />Mathematically consistent (no pointer-arithmetic).<br />Clear semantics: define functions, not manipulate state.<br />Focus on computation, not on memory addressing, low-level issues.<br />Carnegie Mellon uses ML as teaching language on data structures and algorithms<br />Many other universities use Scheme or Haskell.<br />Learn the data structures & algorithms, not fight with segfaults or nullpointers.<br />
    16. 16. FP: new coming?<br />Functional languages compatible with mainstream languages:<br />Microsoft’s F#, based on OCaML<br />Scala, Clojure for Java (hybrids)<br />Python and other script languages adopt many functional ideas, such as list.map() and lambda-functions.<br />Focus on correctness, not performance<br />Especially important in finance.<br />Compilers have improved.<br />But,<br />Completely different way of programming: hard to change.<br />Performance (and memory consumption) has been a big issue.<br />Lack of good tools; cumbersome to program “stateful” code such as UI.<br />However, Scala/Clojure/F# will help bridging the gap as they are compatible with Java/C#.<br />
    17. 17. What is Functional Programming?<br />Imperative program executes sequence of commands to compute a value and modifies the state in the process:<br />Functional program is declarativeand uses pattern matching:<br /> fun sumlist [] = 0<br /> | (x::xs) = x + sumlist(xs);<br />“sum of numbers in list is the value of head of the list plus the sum of the rest of the list. Sum of an empty list is zero.”<br />Functions are usually defined recursively.<br />
    18. 18. More function declarations<br />> fun factorial 1 = 1<br /># | factorial n = n * factorial(n-1);<br />“factorial of n is n multiplied by the factorial of n-1, if n is larger than 1.<br />Otherwise, factorial for 1 is 1.”<br />fun gcd(a : int, 0) = a<br /> | gcd(a : int, b : int) = <br /> if (a < b) then gcd(a, b mod a) else gcd(b, a mod b)<br />
    19. 19. More function declarations<br />More pattern matching for types:<br />
    20. 20. Functional programming (cont.)<br />Imperative program executes commands, functional program evaluates expressions.<br />Functions have no side-effects – there is no state.<br />“Monads” used for input/output etc. (not part of this talk)<br />Values are bound to symbols – but they cannot be changed!<br />Definition of variable is different: it is not an address in memory.<br />
    21. 21. Functional programming (cont.)<br />Functions are values, and can be passed as parameters (anonymous or named):<br />Example :<br />(* Create new functions that return square of the original function *)<br />fun sqrfun (f : real->real) = <br />let <br /> fun F2 (x:real) = f(x)*f(x) <br />in F2 end;<br />valdblsin = sqrfun(Math.sin);<br />> dblsin(2.0);<br />val it = 0.8268218104: real<br />
    22. 22. FP (cont.): Functionals<br />map<br />> valmylist = [1,2,3,4,5,6,7,8,9,10];<br />valmylist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: int list<br />> List.map(fn x=>x*x) mylist;<br />val it = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]: int list<br />foldl / foldr<br />> List.foldl(fn (x,n)=>x+n) 0 mylist;<br />val it = 55: int<br />> List.foldlop+ 0 mylist;<br />val it = 55: int<br />> vallistsummer= List.foldl op+ 0;<br />vallistsummer = fn: int list -> int<br />> listsummer(mylist);<br />val it = 55: int<br />filter<br />> valevenfilter =<br />List.filter(fn (x)=> if (x mod 2 = 0) then true else false);<br />valevenfilter = fn: int list -> int list<br /> > evenfilter(mylist);<br />val it = [2, 4, 6, 8, 10]: int list<br />Extremely consistent and clear code! <br />
    23. 23. Referential Transparency<br />= expression can be safely replaced by its values<br />= no side-effects.<br />Enables reasoning about semantics of programs. <br />Lazy evaluation.<br />Automatic parallel evaluation: order of execution does not matter.<br />Imperative programs are close to machine code, hard to read. Meaning of functional program is “as it is written”.<br />
    24. 24. Type system<br />Very powerful feature of ML (and Haskell):<br />use it for your benefit. Compiler can detect many errors that Java compiler could not.<br />(You can ignore the type system and use wildcards extensively, but then you lose much of the power of Functional Programming).<br />Parametric polymorphism and algebraic data types<br />instead of inheritance.<br />Example…<br />
    25. 25. Type system: algebraic datatypes<br />Product types (records=structs) and sum-types (union of types, such as: user|pet|furniture)<br />
    26. 26. ADT (cont.)<br />
    27. 27. ADT (cont.)<br />Let’s now add a new room object type, “wallitem”.<br />But we forget to add a case to<br />“blocks_coordinate”!<br />
    28. 28. ADT (cont.)<br />But compiler warns us about this!<br />
    29. 29. ADT (cont.)<br />Compiler also warns about redundant cases<br />typical error.<br />Consider this in Java<br />perhaps you have blocksCoordinate() for each room object class – example may not be best.<br />but, maybe in Catalog code we have special price for each item for Moderators:<br />This will be implemented as a if/case in Catalog code, not as a method in User object.<br />Easy to forget cases when new user types are added.<br />
    30. 30. Parametric Polymorphism <br />Close to C++ templates<br />unlike Java generics, first-class types (compile-time).<br />Recursive types<br />- definition of a tree with node type a’:<br />datatype ’a tree = <br /> Empty |<br /> Node of ’a tree * ’a * ’a tree<br />
    31. 31. Miscellanious<br />In practice, it is easy to very also inefficient code in SML (like it is with Java).<br />Garbage collection.<br />Standard ML has a sophisticated module system that neatly separates API and implementation.<br />Lazy ML<br />Haskell is lazily evaluated.<br />Laziness is problematic for parallelism or reasoning about costs.<br />OCaML brings objects to ML. <br />(but no-one uses them…)<br />
    32. 32. Functional Style with Java<br />Some ideas<br />
    33. 33. Functional Languages for JDK<br />Scala<br />gaining popularity.<br />compiles into Java bytecode, compatible with Java.<br />parallel computation features.<br />Erlang-type concurrent messaging style programming also supported.<br />Clojure<br />LISP dialect.<br />
    34. 34. 1) Pattern: Immutable objects<br />If a “manager” returns an object, usually it should be immutable – and a copy:<br />create special immutable classes: ImmutableUser, ImmutableRoom, etc. => Makes ownership of the object clear.<br />better to make own classes that do not have methods to modify the object than throw an exception!<br />Collections.unmodifiableList(…)<br />do not cache objects – only manager caches.<br />makes thread-safe programming easier.<br />Favor tiny carrier objects instead of huge monstrous objects<br />instead of User, favor UserId, UserAppearance.<br />make it clear by naming, that the object does not represent the “actual object”, buti s a “view” of it.<br />especially important with DAOs!! Should be evident what data has been loaded to the data-object.<br />
    35. 35. 2) Fail fast<br />Java does not do much sanity checking in compilation time, so try to make incorrect code fail quickly in test time. Use runtime exceptions – and you should not prepare to handle these kind of errors.<br />
    36. 36. 3) Instead of modifying an object, create new ones<br />Avoids race conditions.<br />Java GC is really fast, and likes short-lived objects.<br />Particulary: avoid recycling objects. It is very error-prone!<br />
    37. 37. 4) Assertions and Declarations<br />Functional: @MessageHandler(id=.., need_session=true), @Moderator<br />Use conservative default values for parameters!<br />This is much better than expecting programmers to check all cases.<br />Assertive: @NotNull, @NoSideEffect, @Slow etc.<br />not great, but better than nothing.<br />Intuitive naming: don’t use getXX, if method has a side-effect!<br />Long method-names that explain what method does are good:<br />user = loginUserWithPassword(user, pass);<br />user = loginUserWithToke(token);<br />instead of user = login(user,pass); <br />user = login(token);<br />
    38. 38. Do not switch assertions off!<br />“… it is absurd to make elaborate security checks on debugging runs, when no trust is put into results, and then remove them in production runs, when an errorenous result could be expensive or disastrous. What would we think of a sailing enthusiast who wears his life-jacket when training on dry land but takes it off as soon as he goes to sea?”<br />C.A.R Hoare (1989)<br />
    39. 39. 5) Poor man’s Closures <br />Closures = anonymous/lambda functions<br />example from Groovy:<br />Unfortunately Java (not even 7) will support Closures.<br />BUT, anonymous classes can be used for the same purpose – although with much boilerplate.<br />
    40. 40. Closure example<br />
    41. 41. 6) Compute, do not store<br />If computing a value is reasonably light-weight, it is better to do that than store a precomputed value.<br />Avoids many errors of forgetting to update all fields of an object.<br />(example on next slide)<br />
    42. 42. Example<br />
    43. 43. Discussion<br />
    44. 44. Questions<br />Do you have experience on functional programming?<br />Opinion on using Hibernate vs. using explicit queries?<br />Where is Java going?<br />why is it so difficult to do simple things, like a simple web service, with Java?<br />Convention vs. Configuration?<br />
    45. 45. Resources<br />PolyML: http://www.polyml.org/<br />Google: “ocaml jane street cmu”<br />good video introduction to FP<br />scala-lang.org<br />
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.

    ×