Composing and repeating function objects

The following Java code builds new function objects from existing ones. The method compose returns a function object that first applies g and then applies f to that result, and applyTwice invokes a given function object two times in a row.


Java
interface IntOp { int apply(int x); }

static IntOp compose(IntOp f, IntOp g) {
    return x -> f.apply(g.apply(x));
}

static int applyTwice(IntOp f, int x) {
    return f.apply(f.apply(x));
}

IntOp addThree = x -> x + 3;
IntOp triple = x -> 3 * x;
IntOp h = compose(addThree, triple);
IntOp k = compose(triple, addThree);


Evaluate each of the following expressions and give each answer as an integer: h.apply(4), k.apply(4), applyTwice(h, 2) and applyTwice(k, 1).

Your answers

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Function Objects Questions: