Thursday 4 October 2012

Functional programming in Python

 

Functional Programming


           In Functional programming a problem can be decomposes into a set of functions. The functions take inputs and produce outputs, and don’t have any internal state that affects the output produced.Some of the examples off functional programming languages are Lisp,Scala,Scheme, Haskell, ML, OCAML, Clean, Mercury, or Erlang,etc

Pure Functions: Functions that have no side effects at all are called purely functional. Avoiding side effects means not using data structures that get updated as a program runs; every function’s output must only depend on its input.

First class function

          
        This is an example of first class function.he absence of any special notation; we are manipulating functions as if they were objects like arrays and numbers.    
>>>
>>>def cube(x): return x*x*x
...
>>>def sqr(x): return x*x
...
>>>cube
<function cube at 0xa1fb10c>
>>>a = [cube, sqr]
>>>a[0](2)
>>>def compose(f, g): return f(g(x))
...
>>>compose(cube, sqr, 3)
729
>>>

 

Higher Order Function

    
        A `function' (or a subroutine, subprogram, procedure) is considered to be a mechanism for capturing patterns.The ability to pass functions as arguments to functions greatly broadens the scope of this `pattern capturing' mechanism. Let's examine a simple function, `sum': 
 
                 def sum(a, b):
                    if (a > b): return 0
                    else: return a + sum(a+1, b)
                 def sigma(term, a, next, b):
                    if(a > b): return 0
                       return term(a) + sigma(term, next(a), next, b) 
                 def term(x): return 1.0/(x * (x+2))
                 def next(x): return x + 4
call the Function 
                 sigma(term, 1, next, 1000)
 
  

Using `lambda'

         
          The lambda keyword is used for creating anonymous functions. The body of a lambda should be composed of simple expressions only. In this example, The lambda is used to create a function which accepts an argument and returns it after multiplication.
>>>
>>>lambda y: y*10
<function <lambda;> at  0x9f751b4>
>>>f = lambda y: y*10
>>>f(10)
100
>>>

Closures 

     The main idea of Closures can be explained in this example

>>> def mul3(x): return lambda y: lambda z: x*y*z
>>> mul3(10)(2)(3)
60
>>>
 

No comments:

Post a Comment