Functional Programming
          on the JVM with
          Scala and Clojure
            What they are and why you should care


      Cristiano Breuel                         Thadeu Russo
Advisory Software Engineer              Advisory Software Engineer
   (cbreuel@br.ibm.com)                   (thadeurc@br.ibm.com)
Y = λf.(λx.f (x x)) (λx.f (x x))
Y = λf.(λx.f (x x)) (λx.f (x x))
What is functional programming
            about?
Lambda calculus (a.k.a λ-calculus)

  function definition

  function application

  recursion
Referential Integrity

  Avoids state and mutable data

Higher-Order functions:

  Functions can receive and return other
  functions

Lazy Evaluation:

  Evaluate an expression only when
  necessary
FP has been around since the 1950’s

   Why it is becoming more important now?
FP has been around since the 1950’s

   Why it is becoming more important now?
FP has been around since the 1950’s

   Why it is becoming more important now?




                Why should I care?
Because of them...
Because of them...



... the multi-core processors
Because of them...



... the multi-core processors

    (also, to become a smarter
             developer!)
On the other side...
On the other side...


 The JVM is cool!
JVM -> Java Language

Huge investment already on the JVM
(libraries, middleware, performance, GC,
remote communication, etc..)

JVM executes byte-code
The question is:
The question is:


    Why not create new (functional)
     languages on top of the JVM?
(not Closure)
Clojure has...
Clojure has...
... tight integration with the JVM and Java
Clojure has...
... tight integration with the JVM and Java

... compilation for performance
Clojure has...
... tight integration with the JVM and Java

... compilation for performance

... dynamic evaluation
Clojure has...
... tight integration with the JVM and Java

... compilation for performance

... dynamic evaluation

... memory-efficient immutable collections
Clojure has...
... tight integration with the JVM and Java

... compilation for performance

... dynamic evaluation

... memory-efficient immutable collections

... lazy sequences
Clojure has...
... tight integration with the JVM and Java

... compilation for performance

... dynamic evaluation

... memory-efficient immutable collections

... lazy sequences

... primitives for concurrency (STM, agents)
Clojure is a LISP
Clojure is a LISP


  (Lots of (Irritating
(Stupid (Parentheses))))
Clojure is a LISP


  (Lots of (Irritating
(Stupid (Parentheses))))



    a.k.a. List Processing
LISP
LISP


Homoiconicity - code is data
LISP


Homoiconicity - code is data

Macros
LISP


Homoiconicity - code is data

Macros

Multiple dispatch (multi-methods)
Syntax
              Operands
Operator     (arguments)


(str "Hello" "World")

           Expression
           delimiters
Syntax

["red" "green" "blue"]               Array

{:color "blue" :length 2}              Map

:color                             Keyword

#(even? %)               Anonymous function
Higher-Order Functions
Efficient Immutable
    Collections
Lazy Sequences
import java.util.HashMap;
import java.util.Map;



public class ColorMapper {

	   private static String[] COLORS = {"white", "blue"};
	
	   public static Map<String, String> mapLineColors(String[] values) {
	   	   Map<String, String> retVal = new HashMap<String, String>();
	   	   int i = 0;
	   	   for (String value: values) {
	   	   	    retVal.put(value, COLORS[i % COLORS.length]);
	   	   	    i++;
	   	   }
	   	   return retVal;
	   }
	
	   public static void main(String[] args) {
	   	
	   	   String[] values = {"Clojure", "Java", "Scala", "Visual Basic"};
	   	
	   	   System.out.println(mapLineColors(values));
	   }
	
}
Java Integration

(def now (new java.util.Date))

(def now (java.util.Date.))

(. now getTime)

(doto (JFrame.)
  (. add (JLabel. "Hello, Clojure!"))
  (. pack)
  (. show))
sample
Scala
Fast

Functional

Expressive

Statically typed (with type inference)

Concurrent
every value is an object

vals / vars

traits

companion objects

currying

closures / high order functions

pattern matching / case classes

XML literals

Lazy evaluation, and much more...
sample
To sum up...
We cannot choose our problems....

  .... but we can choose our tools.

It is our responsibility to figure out
           the “right” tool.
Even if you can't use
these languages in your
  day job yet, learning
 them will make you a
  better programmer!
References



http://clojure.org/

http://www.scala-lang.org/
Scala clojure techday_2011
Scala clojure techday_2011

Scala clojure techday_2011

Editor's Notes

  • #2 \n
  • #3 Thadeu e Cristiano: Apresenta&amp;#xE7;&amp;#xE3;o dos palestrantes\n
  • #4 Thadeu: Apenas assustar o pessoal - dizer que precisamos antes entender o combinador Y\n
  • #5 Thadeu: slide apenas de passagem, sem muitos comentarios.\n
  • #6 Thadeu: basicamente ler o slide.\n
  • #7 Thadeu: da wikipedia: is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data.\nenfatiza a aplicacao de funcoes ao contrario da mudanca de estado, como eh feito em linguagens interativas\n
  • #8 Thadeu: Parar em visual F# - lembrar de chamar aten&amp;#xE7;&amp;#xE3;o para sql e spredsheets\n
  • #9 Thadeu: Parar em visual F# - lembrar de chamar aten&amp;#xE7;&amp;#xE3;o para sql e spredsheets\n
  • #10 Thadeu: Parar em visual F# - lembrar de chamar aten&amp;#xE7;&amp;#xE3;o para sql e spredsheets\n
  • #11 Thadeu: Parar em visual F# - lembrar de chamar aten&amp;#xE7;&amp;#xE3;o para sql e spredsheets\n
  • #12 Thadeu: Parar em visual F# - lembrar de chamar aten&amp;#xE7;&amp;#xE3;o para sql e spredsheets\n
  • #13 Thadeu: Parar em visual F# - lembrar de chamar aten&amp;#xE7;&amp;#xE3;o para sql e spredsheets\n
  • #14 Thadeu: intrigar a plateia - perguntar se alguem sabe e nao deixar responder - comentar que as linguagens sempre foram vistar como muito teoricas para o mundo n&amp;#xE3;o academico\n
  • #15 Thadeu: intrigar a plateia - perguntar se alguem sabe e nao deixar responder - comentar que as linguagens sempre foram vistar como muito teoricas para o mundo n&amp;#xE3;o academico\n
  • #16 Thadeu: discutir um pouco os detalhes tecnicos do impacto\n
  • #17 Thadeu: discutir um pouco os detalhes tecnicos do impacto\n
  • #18 Thadeu passa para Cristiano.\n
  • #19 Cristiano:\n
  • #20 Cristiano:\n
  • #21 Cristiano:\n
  • #22 Cristiano:\n
  • #23 Cristiano:\n
  • #24 Cristiano:\n
  • #25 Cristiano:\n
  • #26 Cristiano:\n
  • #27 Cristiano:\n
  • #28 Cristiano:\n
  • #29 Cristiano:\n
  • #30 Cristiano:\n
  • #31 Cristiano:\n
  • #32 Cristiano:\n
  • #33 Cristiano:\n
  • #34 Cristiano:\n
  • #35 \n
  • #36 \n
  • #37 \n
  • #38 \n
  • #39 \n
  • #40 Thadeu: Comentar cada um dos itens acima (dizer tbm q eh menos verborragica que java) - veremos exemplo\n
  • #41 Thadeu: ir para o repl e fazer alguns exemplos destes caras\nval\nfunction as objects\nreduceLeft - usar as chaves e fazer o currying\n\n\nsobre a parte de lazy - comentar que nao existem lazy collections assim como em haskell ou closure, porem\nda para criar metodos que fazer conversoes de modo lazy (usando iteradores)\n
  • #42 Thadeu: Converter codigo java para scala\n
  • #43 \n
  • #44 \n
  • #45 \n
  • #46 \n
  • #47 \n
  • #48 \n
  • #49 \n