3 ms·
Comprehesions are more readable in the sense that they read more like "English" or "natural language". Unfortunately they're inherently non-composable and make
by tome 13y ago
Comprehesions are more readable in the sense that they read more like "English" or "natural language". Unfortunately they're inherently non-composable and make refactoring harder.
d0m's Moka example (https://news.ycombinator.com/item?id=6150944 https://news.ycombinator.com/item?id=6150944) is closer to composable. I would suggest the following modification. Instead of chaining methods, have a function "chain" which composes functions. We could then write
chain(do(string.split, '+'),
keep(lambda x: x != ""),
map(int),
reduce(moka.add))
If I decided that removing blanks and converting to int was a concept that was worth capturing in its own function, all that I need to do is splice out part of the chain as is.
non_blanks_to_int = chain(keep(lambda x: x != ""),
map(int))
chain(do(string.split, '+'),
non_blanks_to_int,
reduce(moka.add))
No modifications were required. It's more complicated with comprehensions. Of course it's still possible, but it's one more unneccessary grain of sand in the mechanism. Doing the same with the imperative version would be nigh-on impossible.
Come to my FP days talk in Cambridge, UK, Thursday 24th October, 2013 if you want to hear more about this!
http://lanyrd.com/2013/fpdays/sckzkz/ http://lanyrd.com/2013/fpdays/sckzkz/
- maxerickson 13y agoIf you take the awful step of naming things, comprehensions are easy enough to chain. That is (in untested python...) parts=s.split('+') keep=(s for s in parts if s) ints=(int(s) for s in keep) sum(ints) Hiding the middle steps there in a function is easy enough. That split returns a list, but the other steps are lazy.
- tome 13y agoBut naming your intermediate variables means it's not possible to splice parts out.
- maxerickson 13y agoYou did call it a grain of sand, but I suppose I'm responding to where you call it complicated. Moving a couple of the names into a separate function means passing in one of them and editing the last line (at least in python with explicit returns). That meets the meaning of more complicated, but (in my opinion) in a sort of hair splitting way.
- tome 13y agoHorses for courses then I guess. If the "easier to refactor" argument doesn't convince you maybe the "easier to read" argument will. Personally I strongly prefer zero-length variable names, but everyone has their own taste.