12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

16.3. Modifiers 155if sum.second >= 60:sum.second -= 60sum.minute += 1if sum.minute >= 60:sum.minute -= 60sum.hour += 1return sumAlthough thisfunction iscorrect, itisstartingtoget big. We willsee ashorteralternative later.16.3 ModifiersSometimes it is useful for a function to modify the objects it gets as parameters. In that case, thechanges are visibletothe caller. Functions that work thisway arecalled modifiers.increment, which adds a given number of seconds to a Time object, can be written naturally as amodifier. Here isarough draft:def increment(time, seconds):time.second += secondsif time.second >= 60:time.second -= 60time.minute += 1if time.minute >= 60:time.minute -= 60time.hour += 1Thefirstlineperformsthebasicoperation;theremainderdealswiththespecialcaseswesawbefore.Isthisfunction correct? What happens iftheparametersecondsismuch greater than sixty?In that case, it is not enough to carry once; we have to keep doing it until time.second is less thansixty. One solution is to replace the if statements with while statements. That would make thefunction correct, but not very efficient.Exercise 16.3 Writeacorrect version ofincrementthat doesn’t contain any loops.Anything that can be done with modifiers can also be done with pure functions. In fact, someprogramming languages only allow pure functions. There is some evidence that programs that usepure functions are faster to develop and less error-prone than programs that use modifiers. Butmodifiers areconvenient at times,and functional programs tend tobelessefficient.Ingeneral,Irecommendthatyouwritepurefunctionswheneveritisreasonableandresorttomodifiersonlyifthereisacompellingadvantage.Thisapproachmightbecalledafunctionalprogrammingstyle.Exercise 16.4 Write a “pure” version of increment that creates and returns a new Time objectrather than modifying the parameter.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!