4 ms·
It's nice for chaining. E.g. in CoffeeScript: list .map (el) -> el * 2 .filter (el) -> el % 2 == 0 I suppose in this case a list compreh
by stdbrouw 12y ago
It's nice for chaining. E.g. in CoffeeScript:
list
.map (el) ->
el * 2
.filter (el) ->
el % 2 == 0
I suppose in this case a list comprehension would work too:
list = [el * 2 for el in list if el % 2 == 0]
... but as these things get more complex, inline functions become really useful.
It's also nice for various DSL purposes, e.g. unit tests with Mocha
it 'should be able to multiply a number', ->
a = 2
b = 3
(product a, b).should.eql 6
Which in Python would become
def test():
a = 2
b = 3
assert product(a, b) == 6
it('should be able to multiply a number', test)
Probably doesn't look that impressive, but once you're used to them from other languages, it gets to be really frustrating to not have them in Python.
You also start noticing that Python has a couple of features that are actually entirely unnecessary if only you'd have multiline inline functions. For example, you could do away with decorators and `with` blocks.
view = authenticate (req, res) ->
res.send 'hello world'
- jerf 12y ago"Which in Python would become ... assert product(a, b) == 6" Python's got a lot more capacity for "DSLs" than it may immediately seem. Writing "it.shouldBeEqual(product(2, 3))(6)" would be quite easy in Python, actually; it's got all sorts of overloads and you can return all sorts of excitingly overloaded values. You don't see it because it isn't considered "Pythonic", not because Python can't do that. (And I'm with Python on this. Those "fluent" APIs spend way too much effort being cutesy and verbose and not enough effort being simple, transparent, and composable. It looks good in the common case but when you write good test code it stops looking so good when you're writing map(it.shouldBe.eq, testTable), and the fact that the cutesy "fluent" style takes even a baby step in the direction of discouraging anything like that is an immediate disqualification in my book. Oh, don't try to defend it by saying you can still do the map I said... I've got enough experience in such things myself to know that it's actually a bigger problem than I'm making it out to be, not a smaller one.)
- stdbrouw 12y agoKind of besides the point though -- that line in particular had nothing to do with blocks/inline functions.