indic threads pune12-polyglot & functional programming on jvm

Post on 10-May-2015

538 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

The 7th Annual IndicThreads Pune Conference was held on 14-15 December 2012. http://pune12.indicthreads.com/

TRANSCRIPT

Polyglot and Functional Programming on the Java Virtual MachineMohan Kumar MuddanaInfoStretch Pvt. Ltd.

2

Some of the languages on JVM

3

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

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.

5

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

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 on the JavaTM Platform

MLVM – Multi Language Virtual Machine.

7

History of Functional Programming

Alonzo Church Creator of λ-Calculus – 1940

λ-Calculus is the basis of all functional programming languages

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 identity function. That is, (Hx) is I for whatever x may be.

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.

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

• Scheme, ML, OCAML etc.

• And many others

11

Scala Language aka Scalable

Why ScalaOrdersky 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

12

Scala – Object World

• Scala is Pure Object Oriented Language

• Traits

• Case Classes and Pattern Matching

• Type safety and Type Erasure

13

Scala – Classes and ObjectsEverything 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”)

14

Scala – Traits

trait PolyglotProgrammer {def polyProg() {

println("Polyglot Programmer")}

}

class Person extends PolyglotProgrammer with PolyglotSpeaker {}val person = new Person println(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.

15

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)

16

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.

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

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();

<person id='2'>

<name>Gweneth</name>

<age>1</age>

</person>

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

20

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

21

Groovy – DSLDSL 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)

}

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

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

24

Clojure – HomoiconicityRepresentation 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

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

26

Clojure – Parenthesis and Prefix Notation

A method in general of most of the languagesmethodName(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])

27

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.

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 are preserved when new versions are created.

Very rich data structures as well functions to operate on.

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 viewed as a sequence

• (first {"Rich" "Hickey" "Martin" "Odersky"})• (rest {"Rich" "Hickey" "Martin" "Odersky"})• (cons [“James" “Gosling“] {"Rich" "Hickey" "Martin"

"Odersky"})

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

31

Clojure – STMMutable 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

32

Clojure – STM

STM provides similar transaction properties of a Database

But STM handles in memory, so can’t 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.

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

Stateless

33

Clojure – STMAgents

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.

34

Interop – Clojure to JavaClojure is complied and generates BytecodeClojure embraces Java and its libraries. IdiomaticClojure 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

35

Interop – Java to ClojureClojure 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

36

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.

37

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

38

Thank you !

gmail mohanjune@gmail.com

twitter @mohanjune Stateless

top related