You are on page 1of 38

Polyglot and Functional Programming on the Java Virtual Machine

Mohan Kumar Muddana


InfoStretch Pvt. Ltd.

Some of the languages on JVM

Why so many languages on JVM


JVM has grown over the years and has become a mature platform. Very wide industry adoption. Availability of large developer community. Plethora of Tools and Technologies
3

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.
4

JVM The Polyglot Platform


JVM was initially built for (Java) Classes. How does it handles so different kind of language constructs. the Da Vinci Machine Project
(http://openjdk.java.net/projects/mlvm/)

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 on the JavaTM Platform MLVM Multi Language Virtual Machine.

History of Functional Programming

Alonzo Church
Creator of -Calculus 1940

-Calculus is the basis of all functional programming languages

History of Functional Programming


What does it fundamentally sayA 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 identity function. That is, (Hx) is I for whatever x may be.
8

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.
9

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 with requirements on high availability and fault tolerant systems.

Scheme, ML, OCAML etc.


And many others
10

Scala Language aka Scalable


Why Scala
Ordersky says:

"We wanted to make Java more expressive, so people could be more productive" and write at a higher level of abstraction with fewer lines of code, Odersky says.
How it is scalable Getting Started
11

Scala Object World


Scala is Pure Object Oriented Language Traits Case Classes and Pattern Matching

Type safety and Type Erasure


12

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)

13

Scala Traits
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.

trait PolyglotProgrammer { def polyProg() { println("Polyglot Programmer") } }

class Person extends PolyglotProgrammer with PolyglotSpeaker {} val person = new Person println(person.polyProg) println(person.polySpeaker)

14

Scala Case Classes and Pattern Match


Case classes provides pattern matching on objects without large amount of boilerplate code. Case classes are normal classes with a case modifier as prefix.
case Class Rectangle(length: Int, breadth: Int)

15

Scala Case Classes and Pattern Match


Case Classes comes with additional conventions
- The compiler adds a factory method with the name of the class, so no need to create an instance with new operator. - All arguments in the parameter list gets implicit val prefix, so they are maintained as fields. - Compiler adds natural implementations of toString, hashCode and equals.
16

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

17

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(); <person id='2'> <name>Gweneth</name> <age>1</age> </person>
18

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


19

Groovy Elvis Operator ?:


In Java if/else construct would look like this String tradeStatus = "Active"; String status = tradeStatus != null ? tradeStatus : Inactive"; In Groovy String tradeStatus = "Active" String status = tradeStatus ?: "Inactive Groovy coerces the String into a boolean; assuming the String was null, it will convert to the Boolean value of false. No ceremonial Null Pointer check

20

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) }

21

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

22

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

23

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)))
Stateless

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

24

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})
25

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])
26

Clojure Functional
First Class Functions
Functions that always return the same result when passed the same arguments Functions exist as data (function value).

Higher Order Functions Take other functions as arguments or return a function as a result.

27

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 are preserved when new versions are created. Very rich data structures as well functions to operate on.

28

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 viewed as a sequence (first {"Rich" "Hickey" "Martin" "Odersky"}) (rest {"Rich" "Hickey" "Martin" "Odersky"}) (cons [James" Gosling] {"Rich" "Hickey" "Martin" "Odersky"})
29

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 would re-execute the transaction.
30

Clojure STM
Mutable 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
31

Clojure STM
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 a transaction, the cumulative effect of all the updates will appear as a single instantaneous event to anyone not inside your transaction.
Stateless

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 see partially completed results from other transactions.
32

Clojure STM
Agents
Agents provide independent, asynchronous change of individual locations.
Agents are bound to a single storage location for their lifetime, and only allow mutation of that location (to a new state) to occur as a result of an action.

33

Interop Clojure to Java


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: Stateless (def cal (java.util.Calendar/getInstance) (. cal getTime) Code: (import [java.util.Calendar]) (defn cal (.getInstance java.util.Calendar))
34

Interop Java to Clojure


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 { Stateless 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)
35

Polylingualism
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 quite differently.
36

References
Programming in Scala (Martin Odersky, Lex Spoon, Bill Venners) Clojure Programming (Chas Emerick, Brian Carper, Christophe Grand) Programming Clojure (Stuart Halloway) Well Gounded Java Developer (Benjamin Evans, Martin Verburg)

Programming in Groovy (Venkat Subramaniam) Wikipedia.org

37

Thank you !
gmail mohanjune@gmail.com Stateless twitter @mohanjune

38

You might also like