3 ms·
There's no language in which you would be able to write a function for arbitrary data structures using sum(), and get a reasonable outcome. The problem with Py
by tgv 6y ago
There's no language in which you would be able to write a function for arbitrary data structures using sum(), and get a reasonable outcome.
The problem with Python is that it doesn't have typing that can express "I can sum".
- anentropic 6y agoActually, I believe this is expressible in Python's type system: # Python 3.8 from typing import Protocol, TypeVar T = TypeVar('T') class Summable(Protocol[T]): def __add__(self, other: T) -> T: ... In Python 3.4-3.7 you'd need to install typing-extensions library: from typing_extensions import Protocol
- still_grokking 6y agoInteresting. It seems that "every second language" gets "type-classes" these days… C++ added such feature, this above looks like a Python version, Rust has it, Scala had them as one of the first "OOP" languages. It's nice to see that Haskell pioneered a very useful and now spreading language feature!
- sacado2 6y agoAda had them before Haskell, and I'm not even sure it was the first language with them.
- naasking 6y ago> There's no language in which you would be able to write a function for arbitrary data structures using sum(), and get a reasonable outcome. Computing the number of bytes used by a data type seems perfectly reasonable use of sum in that context. This is also achievable in many languages. All 'sum' needs is a map from a value to a number, which can have many sensible meanings even for arbitrary data types.
- dragonwriter 6y agoAnd that works in python to, even if the source type is strings: sum(map(mappingFunction, iterable)) works fine as long as mappingFunction maps the elements of an iterable to numbers.