You are on page 1of 27

Polyglot and Functional Programming on the Java Virtual Machine

Mohan Kumar Muddana


InfoStretch Pvt. Ltd.

Languages on JVM

JVM
2

Why so many languages


JVM has grown over the years and is becoming more mature. Very wide industry adoption. Availability of large developer community. Plethora of Tools and Technologies invokedynamic (making JVM more functional J2SE 7 onwards)

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

Functional Programming
Derives from mathematics, Lambda Calculus Everything is functions First class functions Immutability and Concurrency Higher Order Functions Dynamic language constructs Lesser code with fewer language constructs.

History of Functional Programming


Alonzo Church

Language timelines Resurgence of functional languages with the advent of Multi-Core processors. Need to have easier Domain Specific constructs.
6

Scala Language aka Scalable


Why Scala How it is scalable Getting Started

Scala Object World


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

Scala Classes and Objects


Everything is objects. No primitives wandering around your objects. Java like classes definitions. 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)
9

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. Several classes may want to have different common traits.
trait PolyglotProgrammer { def polyProg() { println("Polyglot Programmer") } }

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

10

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

Scala Type Safety and Erasure


Scala entails static type safety
Scala compilor ensures type safety.

Type Erasure

12

Scala Functional
Functions without side effects Functions inside Functions Anonymous Functions or Function Literals Higher Order Functions

13

Scala Functions
Currying

Closures:
The function value thats created at runtime from this function Literal is called a closure. The name arises from the act of closing the function Literal by capturing the bindings of its free variables.
val add(a: Int) => a + xyz
14

Scala Collections
Immutable Collections Filtering and Combinators

15

Scala Collections
Recursion gives a powerful way of processing data structures without looping syntax Tail Recursion
Functions which call themselves as their last action in their function definition, are called tail recursive Compiler optimizes tail calls by calling in single frame

16

Interop Scala to Java


Scala code complies into bytecode similar to Java classes, methods, exceptions and strings. Scala features map directly onto the equivalent Java features. Cons:

Values (Wrapper Classes and primitives) Singleton objects (Scala hierarchy is different from Java) Traits as interfaces

Stateless

17

Scala Case Study

Stateless

18

Clojure a Lisp on JVM


Why Clojure
Pure functional language Stateless Homoiconicity (Un)digestive Syntax Which you might fall in love later Persistent data structures STM Atom and Agents

19

Clojure Functional
Functional language
(defn name doc-string? attr-map? [params*] body) (defn helloworld [username] (str Hello, username))

Dynamic Language
Resolves types at runtime

20

Clojure Homoiconicity
Representation of its own data structures and atomic values or more casually code-as-data.
(defn average [numbers] (/ (apply + numbers) (count numbers))) /* List Data Structure This definition is a list of data structure containing symbols, values, vectors and another list consists of function body
Stateless

21

Clojure STM
Software Transactional Manager is the way to handle concurrency of mutable data in Clojure.

Using refs, dosync, deref, ref-set, alter and commute


Like database transactions, STM transactions guarantee some important properties:
Updates are atomic. If you update more than one ref in a transaction, the Stateless 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.
22

Clojure STM
Atoms
Atoms provide a way to manage shared, synchronous, independent state. Atoms are an efficient way to represent some state that will never need to be coordinated with any other, and for which you wish to make synchronous changes
Stateless

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.

23

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

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

Sources and Resources


Programming in Scala (Martin Odersky, Lex Spoon, Bill Venners) Clojure Programming (Chas Emerick, Brian Carper, Christophe Grand) Typesafe Scala IDE (typesafe.com) Clojure CounterClockwise (Eclipse plugin, Eclipse marketplace) Wikipedia.org
Stateless

26

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

27

You might also like