Loop Patterns
cs.duke.edu
cs.duke.edu
Everyone spends all their time worrying about object oriented this and design pattern that and test driven agile the other thing, yet they don't grok the basics of procedural programming.
LOOP is a form of crack.
;; Linear Search
(defun find-a-grade (grades)
(loop for grade in grades
when (char= grade #\a)
return grade))
;; Guarded Linear Search
; should use condition system to signal exhaustion
(defun surely-find-a-grade (grades)
(loop for grade in grades
when (char= grade #\a)
return grade
finally (return "not found")))
;; Definate process all items
; fn is a unary function that gets applied to each element in sequence
(defmethod search-all ((objects sequence) fn)
(loop for item in objects do
(funcall fn item)))
;fn is a BINARY function that gets applied to each key/value pair
(defmethod search-all ((objects hash-table) fn)
(maphash fn objects))
;; Polling loop
(defun amy-poller (eof question)
(loop for answer = (yes-or-no-p question)
when answer
return "bye"))
;; extreme values
(defun maximum (values)
(loop for val in values
maximize val))
(defun minimum (values)
(loop for val in values
minimize val))Of course, one needs to consider the loop constructs the language has. I would be annoyed if someone wrote the first loop in java, instead of using a for-each loop.
I just have some patterns differntly. For example, by now, I use a method to implement the guarded linear search, as it requires less branches and allows to hide the handling of the not-found-case:
for (i = 0; i < students.size(); i++)
if (student[i].hasGoodGrade()) return student[i];
return noStudentFound;
For the polling loop, I'd just extract a conditional.
do { readValue(); } while(!valueValid());But yes, I recognize that these are minor stylistic quibbles :)
void findMinMax(istream & input, double & min, double & max)
// postcondition: min is the minimal value in stream input,
// max is the maximal value in stream input
{
double min = DBL_MAX; // #include <float.h> for DBL_MAX
double max = DBL_MIN;
double current;
while (input >> current) {
if (current <= min) min = current;
if (current >= max) max = current;
}
}
The DBL_MIN should be -DBL_MAX if non-positive numbers should be found, as DBL_MIN is the positive double value closest to zero, not the most-negative double value.http://www.cs.duke.edu/~ola/patterns/plopd/loops.html#loop-a...
(Link seen at http://eli.thegreenplace.net/2010/06/30/python-internals-add... .)