• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Indic threads pune12-polyglot & functional programming on jvm
 

Indic threads pune12-polyglot & functional programming on jvm

on

  • 691 views

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

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

Statistics

Views

Total Views
691
Views on SlideShare
691
Embed Views
0

Actions

Likes
0
Downloads
3
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • Imperative, Interpreted, Java Scripting, Dynamic, Language ports, Functional languages. P - built for the electronic arts and visual design GOSU – General Purpose Fantom – General Purpose
  • Language experts target JVM because of all of the above reasons. You might think since JVM is built for Objects how it handles Functions (Focus on invokedynamic)
  • Till now being a Java Developer we have several tools and frameworks to choose from. Now we have wider choice with languages itself. Disadvantage- More choice means confusion. A person who has got a flavor of functional language can pick the other one with some ease.
  • JVM as such doesn’t know anything about Java Language, only a particular format of .class file. The new languages which are targeted makes sure the bytcode generated is as close as Java objects. These languages also have their runtime( supporting libraries) supporting JVM. Some are static type and some are dynamic languages.
  • Any language with functionality that can be expressed in terms of valid class file can be hosted by the Virtual Machine. Similar revolution is happening around in the Microsoft world and with CLR (Common Language Runtime) and DLR (Dynamic Language Runtime). If anyone has any little affinity with .Net this would be interesting. Around 55 languages are listed in the Wikipedia which run on CLR. And in fact .Net has opened its doors much earlier than the JVM.
  • Lambda calculus is much older than modern day digital computers. A function is a rule of correspondence by which when anything is given (as argument) another thing (the value of the function for that argument) may be obtained.
  • Lambda calculus is much older than modern day digital computers. A function is a rule of correspondence by which when anything is given (as argument) another thing (the value of the function for that argument) may be obtained.
  • Major paradigm shift from OOPs to Functional Initially difficult to grasp. Functional programming is the way to go. One cant ignore it. Being a Java developer it is going to knock at your door with Lambda expressions with the release of Java 8.
  • These languages have their own runtime.
  • There are older Functional languages like Lisp, Haskel, Erlang Scala is both OO and Functional. It’s a nice blend between the two. Martin wanted to take the niceties of both the worlds (Imperative and Functional) Scala has very little language constructs. What you feel like built in methods or constructs are not part of the core language but provided by Scala library. you can design and implement abstractions in Scala that address radically new application domains, yet still feel like native language support.
  • Arguments for Pure Object Oriented Language
  • No primitives wandering around your objects. Java like classes definitions.
  • Traits: How does it help Unlike Abstract classes in Java where you can’t extend more than one abstract class, neither you can have implement several Interfaces implementations. Moving the different features to different Traits makes lot of sense. Several classes may want to have different common traits.
  • toString, hashCode and equals will print, hash, and compare a whole tree consisting of the class and (recursively) all its arguments. Case pattern is also applicable to Constants, Sequence, Tuple etc. Almost solves Visitor pattern easily without any if and else. To avoid a MatchError exception add a default case which does nothing.
  • toString, hashCode and equals will print, hash, and compare a whole tree consisting of the class and (recursively) all its arguments. Case pattern is also applicable to Constants, Sequence, Tuple etc. Almost solves Visitor pattern easily without any if and else. To avoid a MatchError exception add a default case which does nothing.
  • Performance of Groovy has been questioned it is mostly scripting. With the invodedynamic coming with java7 would considerably increase its speed.
  • Performance of Groovy has been questioned it is mostly scripting. With the invodedynamic coming with java7 would considerably increase its speed.
  • Performance of Groovy has been questioned it is mostly scripting. With the invodedynamic coming with java7 would considerably increase its speed.
  • So, what is so special about it. Groovy can shorten this because it coerces types to boolean values as needed, such as in conditional checks like if statements. In the preceding code snippet, Groovy coerces the String into a boolean; assuming the String was null, it will convert to the Boolean value of false, so you can omit the null check. You can then write the previous snippet as follows:
  • Performance of Groovy has been questioned it is mostly scripting. With the invodedynamic coming with java7 would considerably increase its speed.
  • Duck typing is aided by habitually not testing for the type of arguments in method and function bodies, relying on documentation, clear code and testing to ensure correct use.
  • Most languages parse the textual code into abstract syntax tree (AST). Clojure programs are written using data structures that represent that AST directly. This becomes basis for macros, meta programming features. Though Clojure code is in text format, those texts are in fact Clojure data structures.
  • (inventors :Clojure) ) "Hickey" (:Clojure inventors) ) "Hickey" Report
  • If a large set of variables need to be applied the same operation, the repetition of the operator is avoided. Clojure gives a function ‘let’ to store independent
  • [ Clojure does this in a very efficient manner where new versions share memory with old versions .]
  • A thread completes modifications to shared memory without regard for what other threads might be doing, recording every read and write that it is performing in a log. it is placed on the reader, who after completing an entire transaction verifies that other threads have not concurrently made changes to memory that it accessed in the past. This final operation, in which the changes of a transaction are validated and, if validation is successful, made permanent, is called a commit . A transaction may also abort at any time, causing all of its prior changes to be rolled back or undone. If a transaction cannot be committed due to conflicting changes, it is typically aborted and re-executed from the beginning until it succeeds.
  • Databases provide the additional guarantee that updates are durable . Because Clojure’s transactions are in-memory transactions, Clojure does not guarantee that updates are durable. If you want a durable transaction in Clojure, you should use a databases
  • Databases provide the additional guarantee that updates are durable . Because Clojure’s transactions are in-memory transactions, Clojure does not guarantee that updates are durable. If you want a durable transaction in Clojure, you should use a databases
  • Databases provide the additional guarantee that updates are durable . Because Clojure’s transactions are in-memory transactions, Clojure does not guarantee that updates are durable. If you want a durable transaction in Clojure, you should use a databases
  • Load the Clojure script -- as a side effect this initializes the runtime. Get a reference to the foo function. Call it!

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

  • Polyglot and Functional Programmingon the Java Virtual MachineMohan Kumar MuddanaInfoStretch Pvt. Ltd.
  • Some of the languages on JVM 2
  • 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 PlatformJVM 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/) 5
  • How JVM incorporates and consumesJava 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. 6
  • History of Functional Programming Alonzo Church Creator of λ-Calculus – 1940 λ-Calculus is the basis of all functional programming languages 7
  • 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. 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 ScalableWhy 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 scalableGetting 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 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”) 13
  • Scala – TraitsIt 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 MatchCase 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
  • GroovyGroovy 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 – 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) } 21
  • Clojure a Lisp dialect on JVMWhy 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 – HomoiconicityData 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 – FunctionalFirst 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 – CollectionsAll 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 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. 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 { public static void main(String[] args) throws Exception { Stateless 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.comtwitter @mohanjune Stateless 38