package username.functions; /** * Functions that represent that composition * E.g., f(x) = g(h(x)) * * @author Samuel A. Rebelsky * @version 1.0 of April 2006 */ public class ComposeUIF implements UnaryIntegerFunction { // +--------+----------------------------------------------- // | Fields | // +--------+ /** The outer function in the composition (g in g(h(x))). */ UnaryIntegerFunction outer; /** The inner function in the composition (h in g(h(x))). */ UnaryIntegerFunction inner; // +--------------+----------------------------------------- // | Constructors | // +--------------+ /** Build a new function that returns f1(f2(x)). */ public ComposeUIF(UnaryIntegerFunction f1, UnaryIntegerFunction f2) { this.outer = f1; this.inner = f2; } // ComposeUIF(UnaryIntegerFunction,UnaryIntegerFunction) // +------------------+------------------------------------- // | Standard Methods | // +------------------+ public String toString() { StringBuffer str1 = new StringBuffer(outer.toString()); String str2 = inner.toString(); int xpos; // Put a special character in for each x to prepare for replacement. // (We're going to put str2 in for each x, but since it may contain // x, we need to do so indirectly.) while ((xpos = str1.indexOf("x")) >= 0) { str1.replace(xpos, xpos+1, "@"); } // while while ((xpos = str1.indexOf("@")) >= 0) { str1.replace(xpos, xpos+1, str2); } // while return str1.toString(); } // toString // +----------------+--------------------------------------- // | Public Methods | // +----------------+ public int apply(int x) { return this.outer.apply(this.inner.apply(x)); } // apply(int) } // ComposeUIF