def readcsv(file):
for line in file:
if line:
yield tuple(field.strip() for field in line.split(','))
No explicit class definitions necessary! And you can write the same kind of code. Or, if you want to be a bit too clever for your own good, you can shorten it to this: rows = readcsv(open('data.csv', 'r'))
vals, avgs, stds = zip(*[map(int, row) for row in rows])
At no point here have I used the "class" keyword!In fact, I think that's how generators are implemented in python, the language just hides this fact away from the programmer.
def read_csv(file):
for line in file:
yield parse_csv_line(line)
-or- def read_csv(file):
return (parse_csv_line(line) for line in file)
-or- def read_csv(file):
return map(parse_csv_line, file)
-or- from functools import partial
read_csv = partial(map,parse_csv_line)
None of which involve defining a class.In Python 3 it is (the `map` builtin is lazy, it's essentially `itertools.imap` and the old eager `map` has disappeared)
(let ((reader (csv-reader "data.csv")))
(loop :for row = (reader) :while row
:collect row[0] :into vals
:collect row[1] :into avgs
:collect row[2] :into stds
:finally (list vals avgs stds)))
That's in the bastardized Lisp that I favour, but any language with closures should allow it. The point is, no classes.I don't want to seem fanatical about this - your example is a fine use of objects. But unless I'm missing something, one can do just as fine without them, and with a little less code (since you don't have to define a class).
I (maybe!) have no problem with classes for things that, as you say, are concrete and have clear interfaces. But then, when things are concrete and have clear interfaces, there are a lot of nice ways to do things. Making things well-defined and clear in the first place is the hard part.
I almost invariably find I need more than one closure down the road, outside of simple predicates handed off to algorithms. Even for such simple things as specifying a sink for output (out :: string -> ()), later on I find myself wanting a flush() routine. That's just my experience: problems grow thornier over time, and starting out with something more object-like adapts to that growth more gracefully than a closure does.
I think a lot of the problem comes from the syntactic weight of classes. I've implemented closures in a commercial compiler; the actual implementation, when it uses captured state, is very similar to a class, and in fact the implementation method I chose behind the scenes was a class. So I tend to view closures (rather than simple function literals that don't capture state) as just a concise way of declaring and instantiating an object.
I've had some success with blending the two. For example, a read-only collection facade is often implemented in .NET with ReadOnlyCollection<T>. But the normal way of implementing that thing is to pass off an IList<T>, which you may need to implement wholly if the logical read-only collection is not already a list. I think that's a complete waste of time; instead, I wrote a function that takes two closure arguments, getCount :: () -> int and getItem :: int -> T, and henceforth I can create a new collection with new behaviour without worrying about the "name" of the descendant, but with the benefits of a class for flexibility down the road.
Those are just names for values though, we don't have to create a name for a new general principle just to use one.
Not to mention values often do not need names at all, in an expression oriented style where function calls are composed.
Variables are easier to name than the more general notion of class or type (being specific to what is immediately at hand and thus not a distraction), which I think was the original point.
And even assuming that my structures will be named is assuming too much. Consider common uses of the fold function, e.g. which act on the pair of (accumulated-value, item). It's common that the pair isn't named. It's parts are named usually, but that's beside the point, I wasn't forced to name the structure itself, much less create a "AccumulatedSumWithNextItem" class.
For example, List<Customer> describes both the type and its semantic content. List<Tuple<string,DateTime,int>> just describes a type; it's a lot less self-documenting, and code using it will be cryptic. In a dynamic language it will probably be customer_list or somesuch. Point being, "customer" is a name and it crops up somewhere, whether it's in the variable or the type.
I don't know the ins and outs of the loop macro, only that it has a lot of them, so perhaps this is simply Common Lisp and I need to keep reading my CL books, but the "row[0]" sugar makes me think that there is something else going on.
You may be able to get something close to what I wrote with a function that returns a closure, but I don't think you can get exactly the for x in y syntax. As explained in another post on HN's front page, "A Guide to Python's Magic Methods": http://www.rafekettler.com/magicmethods.html#sequence, you need to define the __iter__(self) method on an object to support that style of iteration. (And that method needs to return an iterator object.)
And that brings us back to the same point I already made, but I think it's so important that I'll say it again: the abstractions you choose to represent concepts in your program will be determined by what is easy in the language you're using.
def fibonacci_sequence():
a, b, c = 0, 0, 1
while True:
a = b; b = c; c = a + b
yield b
>>> fibonacci_sequence()
<generator object fibonacci_sequence at 0x108055550>
>>> list(itertools.islice(fibonacci_sequence(), 0, 10))
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
>>>
for n in fibonacci_sequence():
print n
if n > 13:
break
1
1
2
3
5
8
13
21
>>>
Again, I have to break this reasoning all the time in C++. I try to use free functions as much as possible, but when I want behavior based on runtime values, I often have to represent abstract concepts using classes because those are the tools that C++ gives me.