FP Library

Some code from a recent session learning about functional programming…

#!/usr/bin/env python
#-*- coding:utf-8 -*-

def sum_terms(term, objIter):
  '''
  sum_terms: function constructor
  Usage: term is a function taking a single argument, objIter is a generator function returning the arguments for term
  Returns: a function to calculate a sum of terms in a series
  '''
  return sum([term(x) for x in objIter])

# sum_triangle returns a function for calculating the nth triangular sum
identity = lambda x: x
inc = lambda n: (identity(x for x in range(1, n + 1)))
sum_triangle = lambda x: sum_terms(identity, inc(x))

# sum_cubes returns a function for calculating the sum of the first n cubes
cube = lambda x: x**3
sum_cubes = lambda x: sum_terms(cube, inc(x))

# pi_sum approximates pi/8
pi_term = lambda x: 1.0/(x*(x + 2))
pi_next = lambda x: range(1, x, 4)
pi_sum = lambda x: sum_terms(pi_term, pi_next(x))

# approximates the definite integral of func between a and b. dx is
# the width of the subinterval
def integral(func, a, b, dx):
    def rng(a, b, dx):
        return ((a + dx/2 + k*dx) for k in range(int((b-a)/dx)))
    return dx*sum_terms(func, rng(a, b, dx))

# uses Simpson's rule to approximate the same definite integral, but
# takes the number of subintervals (n) rather than the width of one
def Simpson(func,  a,  b,  n):
    h = float(b-a)/n
    rng = [(a + k*h) for k in range(n+1)]
    return (h/3)*(func(rng[0])+func(rng[n])+\
                4*sum_terms(func, rng[1:n:2])+\
                2*sum_terms(func, rng[2:n:2]))

if __name__ == '__main__':
    print "sum_triangle(10)=", sum_triangle(10)
    print "sum_cubes(10)=", sum_cubes(10)
    print "8*pi_sum(2000)=", 8*pi_sum(2000)
    print "definite integral of x**3 between 0 and 1:", \
      integral(cube, 0, 1, 0.001)
    print "Simpson approximation of x**3 between 0 and 1:", \
      Simpson(cube, 0, 1, 1000)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s