CSC/ECE 517 Fall 2010/ch1 1e AE: Difference between revisions
Line 144: | Line 144: | ||
} | } | ||
== Java Interoperability == | == Java Interoperability == | ||
Considering Clojure, it gives clean, simple and direct access to java and can access Java API directly. It provides syntax for accessing Java elements like classes, instances, constructors, methods and fields and can also wrap Java API. The “.” dot special form is used for accessing Java. Some Clojure syntax which can access Java API: | Considering Clojure, it gives clean, simple and direct access to java and can access Java API directly. It provides syntax for accessing Java elements like classes, instances, constructors, methods and fields and can also wrap Java API. The “.” dot special form is used for accessing Java. Some Clojure syntax which can access Java API:<br> | ||
{| class="wikitable" border="2" | {| class="wikitable" border="2" | ||
Line 164: | Line 164: | ||
|- | |- | ||
|} | |} | ||
<br> | |||
Clojure pass functions as arguments to other functions. But Java does not support this. So Clojure provides a member function memfn macro to wrap methods or can use anonymous function to wrap a method call. | Clojure pass functions as arguments to other functions. But Java does not support this. So Clojure provides a member function memfn macro to wrap methods or can use anonymous function to wrap a method call. |
Revision as of 01:56, 9 September 2010
Mixing Functional & O-O code
Programming Paradigms Today
Several programmatic approaches to solve a particular task lead to distinct programming paradigms like,
- Imperative Programming
- Functional programming
- Object Oriented programming
- Logical programming, etc.
Lets focus on functional and object oriented programming approaches.
Functional Programming
Functional programming is the task of decomposing a problem into number of functions.Selectively executing these functions results in the solution to the problem.The functions mostly behave as mathematical. For given set of inputs the program should always return the same output. It usually concentrates on what type of problem we are dealing with rather than on the details of how to solve the problem. For example lets say there is a function which calculates area of a square. If we use it six times then we end up with area of a cube. Thus functional programming helps to build complex systems.
Approach
Expressions are the collection of variables and operations resulting in a single value this also deals with the way of solving the problem as expressions.Hence also called Expression related programming. It is structured as expression where each expression can be encapsulated in another yielding the result.Making the change in data structures as the program runs is called side effects.Purely functional language has no side effects. Language like Haskell is a pure functional language . Some languages need many approaches for achieving the desired result. Such languages are multi-paradigm. Examples for such languages are C++, Python,Lisp.Its like evaluating an expression and use the resulting value for something.
Structure of functional programming :
(fn2 ( fn1 ()[input list] ) [])
Functional programming feature (Python) :
m = map(lambda i : i*i , numbers)
where numbers is an array of numbers and lambda is closure.
Python has some functions like map, filter, reduce to support functional programming style. In the example above, the 'map' is a high-order function that takes a function and array of numbers as input. The lambda takes i as input and returns i*i as output. Every result returned is appended to a list and produced as output. In functional programming, the programmer is given a natural framework for developing smaller, simpler, and more general modules, which are then glued together.
Object Oriented Programming
Object oriented programming is a programming technique where everything is defined as an object. Objects are well-defined discrete bundles of data(attributes) and the associated functions(behaviour). They are devised to resemble real-life objects and are uniquely identifiable by a name. The attributes could be of simple datatype(int, String, Boolean) or objects themselves. The behaviour is defined by methods to use and manipulate the attributes. The values of attributes of an object at an instant is the state of the object. OO Programming allows objects to have their state retained throughout the code until manipulated otherwise. Objects are capable of housekeeping their own states, interacting and establishing relationships with other objects,inheriting, etc.
Fundamental concepts
A class is a user-defined datatype that provides implementation details to define the attributes and their properties. It is an abstract representation of an object(i.e.,) like a mould for objects. An instance is an executable copy of a class. They are the actual objects created using the ‘class mould’ on runtime. Methods are a set of procedural statements or functions to define the behaviour of an object, convey the current state, modify values of the attributes, etc.
Example :
An object in Java might look like this:
public class Person {
private String name; public Person() { } public void setName(String name) { this.name = name; } public String getName() { return this.name; }
}
Here, OO Programming allows the programmer to set the name attribute of the class Person and get the name whenever needed in the code. An object of this class Person will remain in memory forever as long as there is a reference to it. As, OO Programming allows objects to have their state retained, the value of the name attribute for a particular Person object remains the same across any part of the code until its set differently.
Features
Three primary characteristics of object oriented programming are Encapsulation, Polymorphism, and Inheritance. Encapsulation is the ability of objects to hide visiblity of their attributes and behaviour, thereby providing service independent of implementation, is called encapsulation. Polymorphism allows identical operations to behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable addressing of operations with the same name in different objects. Inheritance is one where an existing type can be used to derive a new type. Derived types inherit the data and operations of the super-type. And also, they can overwrite existing operations or add new ones.
There are other important features of O-O programming like message passing, abstraction, delegation, etc.
Advantages
Functional Approach over OO Approach
- Functional programming solves the problem with lesser number of lines of code than the OO programming style.
- There is no side effect as they use immutable data structures which will have no change in the state of variables. Hence program dont have to depend on history.
- There is no limit in the numeric types used as opposed to OO languages which mainly depend on primitive data types.
- A programmer is given the freedom to think in terms of what to solve in the problem rather than concentrating on how to solve and the flow of the program.
- Suitable for calculation intensive programs.
OO Approach over Functional Approach
- Everything can be represented in an object and it has the attributes associated with it and hence the state of the object is known at any time.
- A complex system can be subdivided into modules of objects where as in functional approach, many functions inter operate to form a complex system.
- Re-usability (i.e.) OO approach enables programmers to create new objects that inherits many of its features from existing objects. This makes object-oriented programs easier to modify than functional.
- Debugging in Object Oriented environment is easy compared with functional approach where a small error in one function causes the whole system (i.e. all the functions) to fail.
- Suitable for making application-oriented software.
Mixing Functional & OO Code - Best of both the worlds
Languages that are a mix of functional and object oriented approaches(eg. Scala, Clojure) have a bunch of functional approach features, which OO programming languages(like Java) lacks, including closures, and a very malleable syntax that makes it well suited for "domain specific languages" with the benefits of static typing. In object oriented and Functional languages expressions can be compounded.Since there are no instances of objects, and since all data is always passed by value from one function to another, we can have one function call another function and so on without the need to instantiating objects or checking for null values. There are some languages which can add new language constructs in the form of libraries example:Scala,Clojure.Scala supports safe reuse of programming abstractions and for the type-safe extension of software.
Lambda
A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression types .Such kind of anonymous function can be defined and passed around as easily as other data types and can be used to contain functionality that need not be named. Some notable examples include closures and currying.Clojure as a functional language, the creation of a chunk of behavior that can be assigned to a variable (known as a lambda) is trivial. Below are two ways to create a lambda that returns the square of its argument
(def square1 (fn [n] (* n n))) (def square2 #(* % %))
Less Verbosity
In Java each variable should have its type defined beforehand. Whereas in languages like Scala, it is more concise and easier to read than the equivalent Java.
For example, a Map can be created with a simple syntax in Scala, Clojure and in Java:
Java Map<String, Integer> nMap = new HashMap<String, Integer>(); nMap.put("one", 1); nMap.put("two", 2); nMap.put("three", 3); |
Scala var nMap = Map("one" -> 1, "two" -> 2, "three" -> 3) |
Here, Scala compiler knows that nMap uses Strings as keys, and Integers as values. Unlike Java, this need not be specified beforehand. Scala could figure it out itself. Moreover, Scala will give an error if a different key-value pair is tried to insert. This is called "type inference". This prevents a whole class of bugs at runtime just like Java but with less verbosity. In a similar way Clojure also involves only few lines of code compared with the object oriented Java language which takes many lines of code.A simple Clojure example and the associated Java code : Example
(defn blank? [s] (every? #(Character/isWhitespace %) s))
The innermost function Character/isWhiteSpace checks the first argument % for any whitespace and returns true if it is. every? invoke the above inner function for all elements in the collection s.It has no variables, no branches etc.
Java code isBlank() method checks to see whether a string is blank or contains onlt whitespace. public class Stringcheck{
public static boolean isBlank(String str){ int len; if(str==null || (strlen =str.length())==0) return true; for(int i=0; i<strlen;i++) { if((Character.isWhitespace(str.charAt(i))==false)){ return false; } } return true; } }
Java Interoperability
Considering Clojure, it gives clean, simple and direct access to java and can access Java API directly. It provides syntax for accessing Java elements like classes, instances, constructors, methods and fields and can also wrap Java API. The “.” dot special form is used for accessing Java. Some Clojure syntax which can access Java API:
Java | Clojure |
---|---|
new Widget(“red”) | (new Widget “red”) |
Math.PI | (.Math PI) or Math/PI |
System.currentTimeMillis() | (.System currentTimeMillis) or System/currentTimeMillis |
rnd.nextInt() | (.rnd nextInt) or (.nextInt rnd) |
Clojure pass functions as arguments to other functions. But Java does not support this. So Clojure provides a member function memfn macro to wrap methods or can use anonymous function to wrap a method call.
(map (memfn toUpperCase) [“a” ,”short”,”message”])
or
(map #(.toUpperCase %)[“a”,”short”,”message”])
For example,
(def the-digits (map #(Integer. (str %))(filter #(Character/isDigit %) (seq big-num-str))))
where
(def big-num-str (str "123785334434se9088af8309304293872adbcdfd”))
The above code extracts the integers from string and discards the non-numeric characters. Here
#(Character/isDigit) represents the Java method Characgter.isDigit() and #(Integer.(str %)) represents the new java.lang.Integer(str(%))
Many of the Clojure library functions have defined semantics for objects of Java types. contains? and .get work on Java’s Maps, arrays, Strings, count works on Java Strings, Collections and arrays. Clojure is built around these aspects. It avails the performance of JVM and the richness of both the core APIs and the numerous third-party libraries written in the Java language and restrained from reinventing them.
Languages Supporting Functional and OO code
OCaml and F# are some of the languages which support both functional and object oriented programming. OCaml is as fast as C and its featured as Haskell which is a pure functional language. F# is a dynamically typed language which can run on .NET framework and has supported immutable types i.e. tuples, records, discriminated unions and lists to work in Functional programming. It has functions that can either be curried or in uncurried form. As in functional language it can pass functions as arguments to other functions, resulting in higher order functions. It also supports lambda functions and closures. F#, like other .NET languages, can use .NET types and objects, using an imperative object-oriented style of programming. For imperative programming, F# supports for and while loops, arrays and support for creating Object types.
Clojure is also a functional programming language and it is a dialect of Lisp. It is not a pure functional language and it is a dynamically typed language. Just like Java it runs on JVM platform. But its syntax differs from Java. It is represented as :
(functions arguments...)
The function followed by its arguments is enclosed in paranthesis. It has features like immutable data structures, high-order functions and recursion, easy and fast java interoperability.
Python and Ruby are also the programming languages which offer the mix of functional and OO languages. But these languages doesn't support the algebraic data types and pattern matching.
Conclusion
The above views about functional and object oriented techniques discusses some if its merits and demerits and hence mixing the two produces new technology which will lead to a new era in programming. A little has been explored in Clojure and Scala and ofcourse they are not the only languages which supports functional and OO code.The ability for the Clojure and Scala to run in JVM platform makes it the better language as opposed to others in the market. Some of the merits like closure, less verbosity, high order functions along with interoperation with previously written libraries will produce the desired result.
References
http://clojure.org/java_interop
http://www.jot.fm/issues/issue_2009_09/article5.pdf
http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf
Functional programming
http://www.freenetpages.co.uk/hp/alan.gauld/tutfctnl.htm
http://en.wikipedia.org/wiki/Functional_programming
Textbook : Programming Clojure by Stuart Halloway