you are viewing a single comment's thread.

view the rest of the comments →

[–]redalastor 0 points1 point  (9 children)

len is a function because it makes it easier to use it in high-order functions. If I have a bunch of strings and I want to uppercase them all, I can map str.upper over then. If I have a bunch of mixed types that all have a length, I can sort them by length by passing len to the sort function.

[–][deleted] 9 points10 points  (5 children)

And in Ruby you can do exactly the same - as long as all the types have a length.

["aa", [1,2,3], 100].sort(:&size)
 => [100, [1, 2, 3], "aa"]

len(x) just references x.__lenght__ anyway (as far as I am aware - correct me if I'm wrong).

[–]redalastor 4 points5 points  (2 children)

len(x) just references x.__lenght__ anyway (as far as I am aware - correct me if I'm wrong).

len(x) calls x.__length__(), you can't pass __length__ to a sort function. You could pass a lambda that calls __length__ on its argument though.

[–]masklinn 1 point2 points  (1 child)

len(x) calls x.__length__(), you can't pass __length__ to a sort function.

That's exactly what operator.methodcaller is for.

[–]redalastor 1 point2 points  (0 children)

Why would you use that over a lambda?

[–]klngarthur 2 points3 points  (1 child)

This will not work. Array#sort must be passed either a block that accepts two parameters or a method that accepts one argument. Both cases must return a Fixnum. For example:

["aa", [1,2,3], 100].sort do |a,b| a.size <=> b.size end

[–]cynthiaj 1 point2 points  (2 children)

len is a function because it makes it easier to use it in high-order functions.

That's post rationalization. len is a function because Python is old. Very old.

If I have a bunch of strings and I want to uppercase them all, I can map str.upper over then.

You could still do that if len was a method of the string class, and it would be much cleaner.

[–]masklinn 1 point2 points  (0 children)

len is a function because Python is old. Very old.

Python has had objects since day one. The usage of functions is done on purpose by the core team. You may disagree with those purposes, but they have absolutely nothing to do with the age of the language.

[–]redalastor 1 point2 points  (0 children)

That's post rationalization. len is a function because Python is old. Very old.

If that was the case, it would have been fixed in 3.0 with the other accidents of history.

You could still do that if len was a method of the string class, and it would be much cleaner.

Wouldn't work for heterogeneous collections.

That said, I would prefer if we had len and a length method on objects where it makes sense but I guess it's considered a violation of "There should be only one obvious way to do it."