News for hackers. Stuff that matters.
Re:Overthinking Fizzbuzz with Monoids by chicago_wade on Thursday September 14, 2017 @03:42PM (#15251824)
By the way, speaking of sum, I find it a bit strange that Python allows

    'hello' + 'world'
but not

    sum(['hello', 'world'])
Intuitively I would have expected the latter to be possible given the former but I guess it comes down to how the + operator and the sum function are implemented in Python, such that counter to my expectation sum is not a function that "applies the + operator" to it's arguments. The notion that this is how it should work stems from my impression that "sum" belongs to the same family as do "map", "reduce" and "apply" -- that these are somehow "functional" in nature in the sense that is observed in the Lisp family of languages.
Re:Overthinking Fizzbuzz with Monoids by blixt on Thursday September 14, 2017 @03:52PM (#15251916)
I guess sum was only implemented to support numeric values. However you can easily roll your own:

    >>> def add(it):
    ...   return reduce(lambda x, y: x + y, it)
    ...
    >>> add(['hello ', 'world'])
    'hello world'
    >>> add(x for x in xrange(10))
    45
Edit: almost forgot a possibly even more Pythonic way:

    >>> import operator
    >>> def add(it):
    ...   return reduce(operator.add, it)
Re:Overthinking Fizzbuzz with Monoids by chicago_wade on Thursday September 14, 2017 @04:02PM (#15251985)

    >>> import operator
    >>> def add(it):
    ...   return reduce(operator.add, it)
Ooh, I like this one. Thanks!
Re:Overthinking Fizzbuzz with Monoids by blixt on Thursday September 14, 2017 @04:26PM (#15252210)
Looping back to why sum doesn't work with strings, it looks like they implemented it like this:

    >>> def sum(it):
    ...   return reduce(operator.add, it, 0)
Basically the first value is always added to 0. This has one important difference which can be a valid compromise if you expect to almost always sum numbers. If you try to call add([]) without the initial 0, you'll get an error because there's no way to know what the zero value is.

In a typed language you could use type inference and use the inferred type's zero value (if the language has such a concept for all types like for example Go does). In Python I guess you could fall back to None, but then you'd have code that doesn't behave consistently for all inputs.

Re:Overthinking Fizzbuzz with Monoids by kazinator on Thursday September 14, 2017 @04:10PM (#15252057)
The notion that that is how it work probably stems from you not having flunked computer science.