6.8: Encapsulation and Generalization
- Page ID
As a script, this program has the side effect of assigning values to
c, which would be bad if any of those names were in use. By wrapping the code in a function, we can avoid name collisions; this process is called encapsulation because it isolates this program from the workspace.
The first draft of the function takes no input variables:
function res = find_triples() for a=1:3 for b=a:4 for c=b:a+b if is_pythagorean(a, b, c) disp([a,b,c]) end end end end end
The empty parentheses in the signature are not necessary, but they make it apparent that there are no input variables. Similarly, it’s a good idea when calling the new function to use parentheses as a reminder that it’s a function, not a script:
The output variable isn’t necessary, either; it never gets assigned a value. But I put it there as a matter of habit and so my function signatures all have the same structure.
The next step is to generalize this function by adding input variables. The natural generalization is to replace the constant values
4 with a variable so we can search an arbitrarily large range of values.
function res = find_triples(n) for a=1:n for b=a:n for c=b:a+b if is_pythagorean(a, b, c) disp([a,b,c]) end end end end end
Here are the results for the range from 1 to 15:
>> find_triples(15) 3 4 5 5 12 13 6 8 10 8 15 17 9 12 15
The triples \(5,12,13\) and \(8,15,17\) are new, but the others are just multiples of the \(3,4,5\) triangle.