CSC/ECE 517 Fall 2010/ch1 1e AE: Difference between revisions
Line 86: | Line 86: | ||
== Mixing Functional & OO Code - Best of both the worlds == | == Mixing Functional & OO Code - Best of both the worlds == | ||
== Languages Supporting Functional and OO code == | == Languages Supporting Functional and OO code == | ||
OCaml and F# are some of the languages. OCaml is as fast as C language and | OCaml and F# are some of the languages which support both functional and Object Oriented programming. OCaml is as fast as C language and 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.F# 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. F# supports lambda functions and closures as well. 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. | ||
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. | 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. | ||
Revision as of 23:29, 8 September 2010
Mixing Functional & O-O code
Programming Paradigms
Different approaches of solving a particular task pro grammatically leads to different programming paradigms.Imperative Programming, Functional programming, Object Oriented programming,Logical programming are the different 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 of Python:
m= map(lambda i : i*i , numbers)
where
numbers is the array of numbers
lambda is called as closure i.e. it is a block of code which can be accessed from where it is defined.
This lambda takes i as input and returns i*i as output.
Python has some functions like map, filter, reduce to support functional programming style. Here map function takes a function and array of numbers as input. Lambda takes it input from numbers array ,calculates and returns the result. Every result returned is appended to a list and produced as output. Map is a high order function. 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 This ability of objects to hide visiblity of their attributes and behaviour, thereby providing service independent of implementation, is called encapsulation. Polymorphism Identical operations can behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable you to address operations with the same name in different objects. Inheritance You can use an existing type to derive a new type. Derived types inherit the data and operations of the super-type. However, 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
[1]Functional programming solves the problem with limited lines of code rather than the OO programming style.
[2]There is no side effect and hence there is no change in the state of variables,immutable data structures and hence program dont have to depend on history.
[3]There is no limit in the numeric types used as opposed to OO languages which mainly depend on data types.
[4]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.
OO Approach over Functional Approach
[1]Everything can be represented in an object and it has the attributes associated with it and hence can get the state of the object at any time.
[2]A complex system can be subdivided into modules of objects where as in functional many functions interoperate to form complex system.
[3]Reusability (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.
[4]Debugging in Object Oriented environment is easy compared with functional where a small error in one function makes the whole system (i.e. all the functions) to fail.
[5]Best for making application oriented softwares whereas functional approach is suitable for calculation intensive programs.
Mixing Functional & OO Code - Best of both the worlds
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 language and 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.F# 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. F# supports lambda functions and closures as well. 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. 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.
Clojure
Clojure is a functional programming language and it is a dialect of Lisp. Just like Java it runs on JVM platform. But the syntax of it differs quite from Java. The syntax represented as : (functions arguments...). Function followed by the arguments for that function all of which enclosed in paranthesis. It has feature of immutable data structure, high-order functions and recursion, easy,fast java interoperability.It involves only few lines of code rather then 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))
Starting from innermost function Character/isWhiteSpace checks the first argument % for any whitespace and returns true if it is. every? invoke the above function for all elements in the collection s.Thus 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; } }
Clojure is not a pure functional language and it is a dynamically typed language. Clojure gives clean,simple,direct access to java and can call Java API directly.Clojure provides syntax for accessing Java code:classes,instances,constructors,methods, fields and 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) |
new Java.util.HashMap.put(“a”,1); | (doto (new Java.util.HashMap)(.put “a” 1)(.put “b” 2)) |
Clojure pass functions as arguments to other functions. But this will not work with Java methods. 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”])
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.The performance of JVM and the richness of both the core APIs and the numerous third-party libraries written in the Java language are all powerful tools that save from reinventing and hence Clojure is built around these ideas.
Scala
Conclusion
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