3 ms·
Calling [1,2,3].inject(0) {|sum, ii| sum + ii } has a cleaner smell, but it's a lot more typing. I wonder if the solution might be to have all arrays support s
by tjic 18y ago
Calling [1,2,3].inject(0) {|sum, ii| sum + ii } has a cleaner smell, but it's a lot more typing.
I wonder if the solution might be to have all arrays support sum (in the responds_to() sense) only if they can can actually perform the operation.
Thus
[1, 2, 3].respond_to?(:sum)
=> true
[1, [2, 3]].respond_to?(:sum)
=> false
I can come up with an O(1) way to do this where we assume that an array does respond to sum, and degrades to not supporting sum when a non numeric is inserted ... but getting the array to support sum again if/when the non-numeric is removed... I'd have to think for a bit to come up with something better than O(n)...
- raganwald 18y ago[1, [2, 3]].respond_to?(:sum) => false I elided a discussion about this case from the post. For some arrays, a recursive sum is semantically valid. For other arrays a recursive sum is not semantically valid, and it is not a simple case of knowing whether all of the leaf elements respond to :+. So again, trying to implement this in the Array class doesn't work because containers are implementation rather than interface. If you are going to use an Array class, I think the array's client is the one responsible for knowing whether its elements can be summed and if so, whether recursive summing is valid. The other approach is to subclass or otherwise create special-case arrays that know about their semantically valid operations like sum.
- deleted 18y ago[deleted]
- deleted 18y ago[deleted]
- ken 18y agoReminds me of Kent Pitman's article about, among other things, why there's no generic deep-copy in Lisp: http://www.nhplace.com/kent/PS/EQUAL.html http://www.nhplace.com/kent/PS/EQUAL.html His answer is similar: just because you know the structure of something doesn't mean you know anything about its semantics. Because of this, I'm tending to believe that adding more strong-typing to languages is a losing battle, though I admit this raises more questions than answers.
- cbeust 18y ago> Because of this, I'm tending to believe that > adding more strong-typing to languages is a > losing battle, I see this at the opposite. Just because an object says that it responds to a method doesn't guarantee that invoking said method will succeed. I'm not sure why the original poster is so surprised by this finding. Since this observation is valid in both statically and dynamically typed languages, I prefer a statically typed one since at least, I don't need to verify that the object does respond to that method before calling it.
- raganwald 18y agoA question and answer that might be relevant: http://www.reddit.com/r/ruby/comments/8ba5g/my_objection_to_arraysum/c08rcll http://www.reddit.com/r/ruby/comments/8ba5g/my_objection_to_...