In this lab, we are going to write a Log class to handle the context of logging changes to values while they are operated upon.
Let’s start with an example. The following recursive function (or method) returns the sum of non-negative integers from 0 to n.
int sum(int n) {
if (n == 0) {
System.out.println(“base case returns 0”);
return 0;
} else {
int ans = sum(n - 1) + n;
System.out.println(“adding ” + n);
return ans;
}
}
Notice that debugging statements are added to show how the computation progresses. For instance,
jshell> sum(5)
base case returns 0
adding 1
adding 2
adding 3
adding 4
adding 5
$.. ⇒ 15
Since debugging output is a side-effect, you are to define a generic Log class that encapsulates a value of type T, as well as a String.
A sample logging session is shown below:
jshell> sum(5)
$.. ⇒ Log[15]
jshell> sum(5).log()
hit base case!
adding 1
adding 2
adding 3
adding 4
adding 5
Task
Your task is to write a Log class that provides the operations of, equals, map and flatMap. You will also be using Log within solutions to classic computation problems. This would allow us to look at the values changes when solving each problem.
Level 1
Define a Log class with two factory methods of(T t) and of(T t, String log). Also include a log() method that would output the log.