First-class functions

From Rosetta Code
Revision as of 15:40, 24 February 2009 by rosettacode>Paddy3118 (task)
Task
First-class functions
You are encouraged to solve this task according to the task description, using any language you may know.

According to wp:First-class functions, a language has first class functions if:

  • New functions can be created from others at run time
  • Functions can be stored in other collection types of the language
  • Functions can be used as arguments to other functions
  • Functions can be returned as the value of functions.

The above to be accomplished without invoking a compiler or eval/exec or metaprogramming from the main program.

Write a program to create an ordered collection of a mixture of built-in and user defined functions of a real number, together with another ordered collection of their inverses. Try and use sin, asin, cos, acos, and cube, cube-root as the functions. Create a function compose, that given two functions as arguments returns a new function that applys first the second argument to compose to its argument, then the the first argument to compose to the result, i.e:

 composed_function = compose(f,g)
 where composed_function(x) == compose(f,g)(x) == f(g(x))

Applying the compose of a function and its inverse from the two ordered collections of functions in pairs, show that the result in each case is the original value.

The Python example conforms to the above.

Python

Python 2.X <lang python>>>> #some built in functions and their inverses >>> from math import sin, cos, acos, asin >>> # Add a user defined function and its inverse >>> cube = lambda x: x * x * x >>> croot = lambda x: x ** (1/3.0) >>> # First class functions allow run-time creation of functions from functions >>> # return function compose(f,g)(x) == f(g(x)) >>> compose = lambda f1, f2: ( lambda x: f1(f2(x)) ) >>> # first class functions should be able to be members of collection types >>> funclist = [sin, cos, cube] >>> funclisti = [asin, acos, croot] >>> # Apply functions from lists as easily as integers >>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)] [0.5, 0.49999999999999989, 0.5] >>> </lang>