Homework 2Programming Patterns |
Modified: |
Patterns are a model of something; in our day-to-day experiences, we tend to categorize things by how closely they match some pattern. For example, we enter a classroom and automatically categorize the furniture based on our pattern of chairs and tables. This ability to recognize patterns and form categories allows us to more rapidly make sense of our world. We enter a new classroom and instantaneously we categorize students and chairs correctly, seldom do we mistake a chair for a student.
Programming patterns take advantage of this natural ability to recognize patterns in problems. We use patterns in problem solving in at least two ways: by grouping together distinct cases of a problem, and by abstracting (i.e. reducing) a large number of specific cases to a few general cases. By organizing problems by patterns, our understanding of the problem is generally clearer, the solution simpler and, therefore, more likely to be correct. For an example of abstraction, we could define the positive integer successor for each specific integer case by:
fun successor0 = 1;
fun successor1 = 2;
fun successor2 = 3;
:or in general by:
fun successor n = n+1;
ML further uses our pattern recognition and categorization ability by decomposing a single solution (e.g. function) into separate cases or categories of solutions. The ML pattern syntax is generally an alternative to if-then-else statements, something akin to the switch statement in C or Java. For example, the summation of an integer list of numbers can be defined using patterns, where each patterns solve one specific case of the summation problem. A pattern and non-pattern solution is given below:
fun sum L =
if null L then 0
else if null (tl L) then hd L
else (hd L) + sum (tl L);fun sum [] = 0
| sum [a] = a
| sum (h::t) = h + sum t;The non-pattern solution at left requires that we first read the code to form categories in our mind to understand to the solution. The pattern solution at right defines and organizes the categories visually, avoiding extra effort and reducing the potential for our misunderstanding the solution.
Write and give output from TESTING for the following:
Document last modified: