We want to perform an operation (e.g., a sum) between all elements of an inductively defined structure (e.g., a file of integers). A recursive method to do so has the following structure:
where neutral-element-for-op is the neutral element for the operation we want to perform (e.g., 0 for the sum, 1 for the product, "" for string concatenation, etc.).read an element;
if (element is not valid)
return neutral-element-for-op;
else
return value-of-element op result-of-the-recursive-call;
Example: Sum of integers read from a file, one per line.
public static int sum(BufferedReader br) throws IOException { String s = br.readLine(); if (s == null) return 0; else return Integer.parseInt(s) + sum(br); }
Example: Verifying the presence of a certain value in a file of integers, stored one per line.
public static boolean present(int val, BufferedReader br) throws IOException { String s = br.readLine(); if (s == null) return false; else return (Integer.parseInt(s) == val) || present(val, br); }