CSC/ECE 517 Fall 2010/ch1 1e AE: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
Line 25: Line 25:


   m = map(lambda i : i*i , numbers)
   m = map(lambda i : i*i , numbers)
where ''numbers'' is an array of numbers and ''lambda'' is closure. A closure is a block of code which can be accessed from whereever it is defined. The lambda here takes i as input and returns i*i as output.
where ''numbers'' is an array of numbers and ''[[lambda]]'' is closure. The lambda here 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.
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.

Revision as of 01:21, 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,

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. The lambda here 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 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)

Clojure

(doto (new Java.util.HashMap)(.put “a” 1)(.put “b” 2))



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.

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)


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