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

From Expertiza_Wiki
Jump to navigation Jump to search
No edit summary
Line 99: Line 99:


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.
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.
==Scala ==
==Conclusion ==
== References ==
<br>
[1] http://clojure.org/java_interop
<br>Functional programming<br>
[2]http://www.freenetpages.co.uk/hp/alan.gauld/tutfctnl.htm<br>
[3]http://en.wikipedia.org/wiki/Functional_programming<br>

Revision as of 15:22, 8 September 2010

Mixing Functional & O-O code

Programming Paradigms

Different approaches of solving a particular task 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

Languages Supporting Functional and OO code

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

Scala

Conclusion

References


[1] http://clojure.org/java_interop
Functional programming
[2]http://www.freenetpages.co.uk/hp/alan.gauld/tutfctnl.htm
[3]http://en.wikipedia.org/wiki/Functional_programming