CSC/ECE 517 Fall 2010/ch1 1e AE

From Expertiza_Wiki
Jump to navigation Jump to search

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