indicthreads-pune12-polyglot & functional programming on jvm

Upload: indicthreads

Post on 04-Apr-2018

231 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/30/2019 IndicThreads-Pune12-Polyglot & Functional Programming on JVM

    1/38

    Polyglot and Functional Programmingon the Java Virtual Machine

    Mohan Kumar MuddanaInfoStretch Pvt. Ltd.

  • 7/30/2019 IndicThreads-Pune12-Polyglot & Functional Programming on JVM

    2/38

    2

    Some of the languages on JVM

  • 7/30/2019 IndicThreads-Pune12-Polyglot & Functional Programming on JVM

    3/38

    3

    Why so many languages on JVM

    JVM has grown over the years and has become amature platform.

    Very wide industry adoption.

    Availability of large developer community.

    Plethora of Tools and Technologies

  • 7/30/2019 IndicThreads-Pune12-Polyglot & Functional Programming on JVM

    4/38

    4

    Polyglot Programming on the JVM

    Different languages bring in different features.

    Wider choice of availability.

    Better programming features.

    Imperative and Functional

    Interoperability between the languages.

  • 7/30/2019 IndicThreads-Pune12-Polyglot & Functional Programming on JVM

    5/38

    5

    JVM The Polyglot Platform

    JVM was initially built for (Java) Classes.

    How does it handles so different kind of languageconstructs.

    the Da Vinci Machine Project

    (http://openjdk.java.net/projects/mlvm/)

    http://openjdk.java.net/projects/mlvm/http://openjdk.java.net/projects/mlvm/
  • 7/30/2019 IndicThreads-Pune12-Polyglot & Functional Programming on JVM

    6/38

    6

    How JVM incorporates and consumes

    Java 6 : - JSR 223: Scripting for the Java Platform(Groovy, Jython, JRuby)

    Java 7 :- JSR 292: Supporting Dynamically Typed Languages onthe JavaTM Platform

    MLVM Multi Language Virtual Machine.

  • 7/30/2019 IndicThreads-Pune12-Polyglot & Functional Programming on JVM

    7/38

    7

    History of Functional Programming

    Alonzo ChurchCreator of-Calculus 1940

    -Calculus is the basis of all functional programming languages

  • 7/30/2019 IndicThreads-Pune12-Polyglot & Functional Programming on JVM

    8/38

    8

    History of Functional Programming

    What does it fundamentally say-A function is an action that is applied to one thing (the argument) to

    obtain another thing (the value).

    Two Fundamental functions in-Calculus(I, the identity function). I is defined as follows: (Ix) is x, whatever

    x may be.

    (H). H is defined as the function that always returns the identityfunction. That is, (Hx) is I for whatever x may be.

  • 7/30/2019 IndicThreads-Pune12-Polyglot & Functional Programming on JVM

    9/38

    9

    Functional Programming

    Derives from mathematics, Lambda Calculus

    Built on the basis of functions

    Immutability and Concurrency

    Data Structures with strong filtering

    Lesser code with fewer language constructs.

  • 7/30/2019 IndicThreads-Pune12-Polyglot & Functional Programming on JVM

    10/38

    10

    Functional Programming Languages

    Lisp One of t he oldest programming language

    (Lisp is functional language)

    Haskel Pure functional language

    Erlang - Massively scalable soft real-time systems withrequirements on high availability and fault tolerant systems.

    Scheme, ML, OCAML etc.

    And many others

  • 7/30/2019 IndicThreads-Pune12-Polyglot & Functional Programming on JVM

    11/38

    11

    Scala Language aka Scalable

    Why Scala

    Ordersky says:"We wanted to make Java more expressive, so peoplecould be more productive" and write at a higher levelof abstraction with fewer lines of code, Odersky says.

    How it is scalable

    Getting Started

    S l Ob W ld

  • 7/30/2019 IndicThreads-Pune12-Polyglot & Functional Programming on JVM

    12/38

    12

    Scala Object World

    Scala is Pure Object Oriented Language

    Traits

    Case Classes and Pattern Matching

    Type safety and Type Erasure

    S l Cl d Obj

  • 7/30/2019 IndicThreads-Pune12-Polyglot & Functional Programming on JVM

    13/38

    13

    Scala Classes and Objects

    Everything is objects.

    Store objects into a variables.

    class HelloWorld() {

    val welcome: String = Hello World

    def msg(name: String) = println(welcome + name)}

    val h = new HelloWorld()

    h.msg(Your Name)

    S l T i

  • 7/30/2019 IndicThreads-Pune12-Polyglot & Functional Programming on JVM

    14/38

    14

    Scala Traits

    trait PolyglotProgrammer {def polyProg() {

    println("Polyglot Programmer")}

    }

    class Person extends PolyglotProgrammer with

    PolyglotSpeaker {}val person = new Personprintln(person.polyProg)println(person.polySpeaker)

    It is an kind of an Interface with fields and concrete methods.

    Unlike Class inheritance, a class can mix (Mixins) in any number

    of traits.

    S l C Cl d P tt M t h

  • 7/30/2019 IndicThreads-Pune12-Polyglot & Functional Programming on JVM

    15/38

    15

    Scala Case Classes and Pattern Match

    Case classes provides pattern matching on objectswithout large amount of boilerplate code.

    Case classes are normal classes with a case modifier as

    prefix.

    case Class Rectangle(length: Int, breadth: Int)

    S l C Cl d P tt M t h

  • 7/30/2019 IndicThreads-Pune12-Polyglot & Functional Programming on JVM

    16/38

    16

    Scala Case Classes and Pattern Match

    Case Classes comes with additional conventions

    - The compiler adds a factory method with the nameof the class, so no need to create an instance withnew operator.

    - All arguments in the parameter list gets implicit valprefix, so they are maintained as fields.

    - Compiler adds natural implementations of toString,hashCode and equals.

    G

  • 7/30/2019 IndicThreads-Pune12-Polyglot & Functional Programming on JVM

    17/38

    17

    Groovy

    Groovy is the closest to Java language.

    Supports both static and dynamic type binding.

    Powerful XML processing constructs.

    Very good support for regular expressions

    Gr XML Pr ing

  • 7/30/2019 IndicThreads-Pune12-Polyglot & Functional Programming on JVM

    18/38

    18

    Groovy XML Processing

    def writer = new StringWriter();

    def xml = new groovy.xml.MarkupBuilder(writer);xml.person(id:2) {

    name 'Gweneth age 1

    }

    println writer.toString();

    Gweneth

    1

    Groovy Beans Conciseness

  • 7/30/2019 IndicThreads-Pune12-Polyglot & Functional Programming on JVM

    19/38

    19

    Groovy Beans - Conciseness

    class Person {private String name

    private int age

    }

    def p = new Person(name: Ramu, age: 15)

    (No syntactic ceremony)

    @Immutable annotation to make it immutable

  • 7/30/2019 IndicThreads-Pune12-Polyglot & Functional Programming on JVM

    20/38

    Groovy DSL

  • 7/30/2019 IndicThreads-Pune12-Polyglot & Functional Programming on JVM

    21/38

    21

    Groovy DSL

    DSL with the help of identity: The Context Method

    Trade trade = new Trade()

    trade.identity {

    setOrderId(1)

    setOrderStatus(false)setEquityName("Fictious Inc")

    setQuantity(100)

    setPrice(17.25)

    }

    Clojure a Lisp dialect on JVM

  • 7/30/2019 IndicThreads-Pune12-Polyglot & Functional Programming on JVM

    22/38

    22

    Clojure a Lisp dialect on JVM

    Why Clojure

    Predominately functional language Stateless

    Homoiconicity

    (Un)digestive Syntax Which you might fall in love

    later

    Persistent data structures

    STM

    Atom and Agents

    Clojure Functional

  • 7/30/2019 IndicThreads-Pune12-Polyglot & Functional Programming on JVM

    23/38

    23

    Clojure Functional

    Predominately Functional language

    (defn name doc-string? attr-map? [params*] body)

    (defn helloworld [username] returns a String hello message

    (str Hello, username))

    Dynamic Language

    Resolves types at runtime

    Clojure Homoiconicity

  • 7/30/2019 IndicThreads-Pune12-Polyglot & Functional Programming on JVM

    24/38

    24

    Clojure Homoiconicity

    Representation of its own data structures and atomic

    values or more casually code-as-data and data-as-code

    (defn average [numbers]

    (/ (apply + numbers) (count numbers)))

    This definition is a list of data structure containing symbols,

    values, vectors and another list consists of function body

    (+ 7 3) on REPL yields

    => (+ 7 3)

    10

    Stateless

    Clojure Homoiconicity

  • 7/30/2019 IndicThreads-Pune12-Polyglot & Functional Programming on JVM

    25/38

    25

    Clojure Homoiconicity

    Data as Code Consider map

    (def names {"Rich" "Hickey" "Martin" "Odersky"})

    Now use names as function(names Rich) will result in Hickey

    else more verbose get

    (get names Rich None)

    Any Clojure data structure can be a key in a map(def names {:Lisp Rich :Scala Martin})

    Clojure Parenthesis and Prefix Notation

  • 7/30/2019 IndicThreads-Pune12-Polyglot & Functional Programming on JVM

    26/38

    26

    Clojure Parenthesis and Prefix Notation

    A method in general of most of the languages

    methodName(arg1, arg2, arg3);

    A clojure function has prefix notation

    (function-name arg1 arg2 arg3)

    Imagine if you want to operate on a large list of values

    sum (60+80+90+120)

    Whereas in Lisp or Clojure syntax

    (apply + [60 80 90 120])

    Clojure Functional

  • 7/30/2019 IndicThreads-Pune12-Polyglot & Functional Programming on JVM

    27/38

    27

    Clojure Functional

    First Class Functions

    Functions that always return the same result when passed thesame arguments

    Functions exist as data (function value).

    Higher Order Functions

    Take other functions as arguments or return a function as aresult.

    Clojure Collections

  • 7/30/2019 IndicThreads-Pune12-Polyglot & Functional Programming on JVM

    28/38

    28

    Clojure Collections

    All of them are immutable, heterogeneous and persistent.

    Heterogeneous means that they can hold any kind of

    object.

    Being persistent means that old versions of them arepreserved when new versions are created.

    Very rich data structures as well functions to operate on.

    Clojure Sequences

  • 7/30/2019 IndicThreads-Pune12-Polyglot & Functional Programming on JVM

    29/38

    29

    Clojure Sequences In Clojure, all these data structures can be accessed

    through a single abstraction: the sequence (seq)

    Every aggregate data structure in Clojure can be viewedas a sequence

    (first {"Rich" "Hickey" "Martin" "Odersky"})

    (rest {"Rich" "Hickey" "Martin" "Odersky"})

    (cons [James" Gosling] {"Rich" "Hickey" "Martin"

    "Odersky"})

    Clojure STM

  • 7/30/2019 IndicThreads-Pune12-Polyglot & Functional Programming on JVM

    30/38

    30

    Clojure STM

    Software Transactional Manager is the way to handle

    concurrency of mutable data in Clojure.STM is very optimistic.

    Alternative to lock based synchronization.

    Mutual Exclusion

    Every read and write that it is performing is in a log.

    Onus is on reader which will commit to the shared memory in

    case no modifications are done during the time, else wouldre-execute the transaction.

    Clojure STM

  • 7/30/2019 IndicThreads-Pune12-Polyglot & Functional Programming on JVM

    31/38

    31

    jMutable References

    ref, deref or @, ref-set, dosync

    Need to be explicit when mutable data is required.

    (def value (ref 100))

    ref wraps and protects access to its internal state.

    Even to read, it needs to deref

    (deref value) or @value

    As the value is in STM

    Clojure STM

  • 7/30/2019 IndicThreads-Pune12-Polyglot & Functional Programming on JVM

    32/38

    32

    j

    STM provides similar transaction properties of a Database

    But STM handles in memory, so cant guarantee durability.

    Updates are atomic. If you update more than one ref in atransaction, the cumulative effect of all the updates willappear as a single instantaneous event to anyone not inside

    your transaction.

    Updates are consistent. Refs can specify validation functions.If any of these functions fail, the entire transaction will fail.

    Updates are isolated. Running transactions cannot seepartially completed results from other transactions.

    Stateless

    Clojure STM

  • 7/30/2019 IndicThreads-Pune12-Polyglot & Functional Programming on JVM

    33/38

    33

    jAgents

    Agents provide independent, asynchronous change ofindividual locations.

    Agents are bound to a single storage location for their

    lifetime, and only allow mutation of that location (to a newstate) to occur as a result of an action.

    Interop Clojure to Java

  • 7/30/2019 IndicThreads-Pune12-Polyglot & Functional Programming on JVM

    34/38

    34

    p j J

    Clojure is complied and generates Bytecode

    Clojure embraces Java and its libraries. Idiomatic

    Clojure code can call Java libraries directly

    Creating Java instances and accessing its methods.

    In REPL:

    (def cal (java.util.Calendar/getInstance)

    (. cal getTime)

    Code:

    (import [java.util.Calendar])

    (defn cal (.getInstance java.util.Calendar))

    Stateless

    Interop Java to Clojure

  • 7/30/2019 IndicThreads-Pune12-Polyglot & Functional Programming on JVM

    35/38

    35

    p J j

    Clojure is implemented as Java class library.

    Embed Clojure using load code and call functions

    import clojure.lang.RT;

    import clojure.lang.Var;

    public class Foo {

    public static void main(String[] args) throws Exception {

    RT.loadResourceScript("foo.clj"); Var foo = RT.var("user", "foo");

    Object result = foo.invoke("Hi", "there");System.out.println(result);

    }}

    (user being the namespace and foo being the function from Clj)

    Stateless

    Polylingualism

  • 7/30/2019 IndicThreads-Pune12-Polyglot & Functional Programming on JVM

    36/38

    36

    y g

    Sapir-Whorf Hypothesis

    According to the first, linguistic determinism,our thinking is determined by language.

    According to the second, linguistic relativity,people who speak different languages

    perceive and think about the world quitedifferently.

    References

  • 7/30/2019 IndicThreads-Pune12-Polyglot & Functional Programming on JVM

    37/38

    37

    Programming in Scala (Martin Odersky, Lex Spoon, Bill Venners)

    Clojure Programming (Chas Emerick, Brian Carper, ChristopheGrand)

    Programming Clojure (Stuart Halloway)

    Well Gounded Java Developer (Benjamin Evans, Martin Verburg)

    Programming in Groovy (Venkat Subramaniam)

    Wikipedia.org

  • 7/30/2019 IndicThreads-Pune12-Polyglot & Functional Programming on JVM

    38/38

    38

    Thank you !

    gmail [email protected]

    twitter @mohanjune Stateless