Declarative Programming

List comprehensions and generator expressions are strongly tied to operations found in declarative languages. In fact, the origin of these features is loosely derived from ideas in mathematical set theory. For example, when you write a statement such as [x*x for x in a if x > 0] , it's somewhat similar to specifying a set such as { x2 | x £a,x > 0 }.

Instead of writing programs that manually iterate over data, you can use these declarative features to structure programs as a series of computations that simply operate on all of the data all at once. For example, suppose you had a file "portfolio.txt" containing stock portfolio data like this:

# Read lines, strip

# trailing/leading whitespace == '#') # All comments

Was this article helpful?

0 0

Post a comment