This is actually how the arithmetic of natural numbers is determined from first principles; see http://en.wikipedia.org/wiki/Peano_axioms
Let's do it from scratch, why not?
- Zero is a natural
- Zero has no predecessor
- Every natural has a successor
Easy done:
sealed class Natural { private Natural predecessor; private Natural(Natural predecessor) { this.predecessor = predecessor; }
Well, we can represent any integer like this. Now how do we make an addition? We define the addition as:
a + 0
So, let's add an operator
public static Natural operator+(Natural a, Natural b) { if (b == Zero) return a; else return (a + b.Predecessor()).Successor(); } }
Well, let him try.
Natural n0 = Natural.Zero; Natural n1 = n0.Successor(); Natural n2 = n1.Successor(); Console.WriteLine(n0 + n0); Console.WriteLine(n0 + n1); Console.WriteLine(n0 + n2); Console.WriteLine(n1 + n0); Console.WriteLine(n1 + n1); Console.WriteLine(n1 + n2); Console.WriteLine(n2 + n0); Console.WriteLine(n2 + n1); Console.WriteLine(n2 + n2);
And there you go, two plus two are actually four.
If this topic interests you, I am currently launching a long series on my blog that I get natural and whole arithmetic from scratch, although I use a binary representation rather than a unary representation. Cm.
http://ericlippert.com/2013/09/16/math-from-scratch-part-one/
More generally: the question is intended to verify whether you know the basic structure of a recursive method; perhaps you will not let me lay it out for you. Recursive methods in C # all follow this pattern:
- Do we already know the solution to the problem without recursion? If so, solve the problem and return the result.
- We do not know the solution to the problem. Divide the problem into one or more smaller problems. Reduction should create problems that are actually smaller, which is closer to a problem that has a known solution. Otherwise, the recursion does not end.
- Solve each problem recursively.
- Combine solutions to these problems to create a solution to a larger problem.
- Return the result.
This is what we do in the add statement. First we check if we know the solution to the problem; a + 0 is a. If we do not know the solution to the problem, we make the smaller problem; if we take the predecessor of the second term, then we are one step closer to the problem that we know how to solve.
Eric Lippert
source share