Indic threads pune12-polyglot & functional programming on jvm

38
Polyglot and Functional Programming on the Java Virtual Machine Mohan Kumar Muddana InfoStretch Pvt. Ltd.

description

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

Transcript of Indic threads pune12-polyglot & functional programming on jvm

Page 1: Indic threads pune12-polyglot & functional programming on jvm

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

Page 2: Indic threads pune12-polyglot & functional programming on jvm

2

Some of the languages on JVM

Page 3: Indic threads pune12-polyglot & functional programming 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

Page 4: Indic threads pune12-polyglot & functional programming on jvm

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.

Page 5: Indic threads pune12-polyglot & functional programming on jvm

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

Page 6: Indic threads pune12-polyglot & functional programming on jvm

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.

Page 7: Indic threads pune12-polyglot & functional programming on jvm

7

History of Functional Programming

Alonzo Church Creator of λ-Calculus – 1940

λ-Calculus is the basis of all functional programming languages

Page 8: Indic threads pune12-polyglot & functional programming on jvm

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.

Page 9: Indic threads pune12-polyglot & functional programming on jvm

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.

Page 10: Indic threads pune12-polyglot & functional programming on jvm

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

Page 11: Indic threads pune12-polyglot & functional programming on jvm

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

Page 12: Indic threads pune12-polyglot & functional programming on jvm

12

Scala – Object World

• Scala is Pure Object Oriented Language

• Traits

• Case Classes and Pattern Matching

• Type safety and Type Erasure

Page 13: Indic threads pune12-polyglot & functional programming on jvm

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

Page 14: Indic threads pune12-polyglot & functional programming on jvm

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.

Page 15: Indic threads pune12-polyglot & functional programming on jvm

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)

Page 16: Indic threads pune12-polyglot & functional programming on jvm

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.

Page 17: Indic threads pune12-polyglot & functional programming on jvm

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

Page 18: Indic threads pune12-polyglot & functional programming on jvm

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>

Page 19: Indic threads pune12-polyglot & functional programming on jvm

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

Page 20: Indic threads pune12-polyglot & functional programming on jvm

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

Page 21: Indic threads pune12-polyglot & functional programming on jvm

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)

}

Page 22: Indic threads pune12-polyglot & functional programming on jvm

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

Page 23: Indic threads pune12-polyglot & functional programming on jvm

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

Page 24: Indic threads pune12-polyglot & functional programming on jvm

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

Page 25: Indic threads pune12-polyglot & functional programming on jvm

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

Page 26: Indic threads pune12-polyglot & functional programming on jvm

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

Page 27: Indic threads pune12-polyglot & functional programming on jvm

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.

Page 28: Indic threads pune12-polyglot & functional programming on jvm

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.

Page 29: Indic threads pune12-polyglot & functional programming on jvm

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

Page 30: Indic threads pune12-polyglot & functional programming on jvm

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.

Page 31: Indic threads pune12-polyglot & functional programming on jvm

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

Page 32: Indic threads pune12-polyglot & functional programming on jvm

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

Page 33: Indic threads pune12-polyglot & functional programming on jvm

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.

Page 34: Indic threads pune12-polyglot & functional programming on jvm

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

Page 35: Indic threads pune12-polyglot & functional programming on jvm

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

Page 36: Indic threads pune12-polyglot & functional programming on jvm

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.

Page 37: Indic threads pune12-polyglot & functional programming on jvm

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

Page 38: Indic threads pune12-polyglot & functional programming on jvm

38

Thank you !

gmail [email protected]

twitter @mohanjune Stateless