Misliding Array.max definition

Is it just me or Array.max definition is counter intuitive for someone else?

Context: Today while coding I needed to get the greater integer in a list, so first thing I think is "Hey I now there is a max() function that return the greater number, so should be one for a list". That's where the confusion started. First thing I write is:

let max = [1,2,3].max(by: >)
print(max)

And the printed result is... 1... wait... what?
Next try

let max = [1,2,3].max(by: <)
print(max)

which printed 3

Tha's when started doubting my mind. In what world the max between 1 and 3 is 1. This looks inverted!

At further inspection at the documentation I stated the "why" of my confusion. The predicate should return true if the left element should come before the righ element in an incresing ordered list.

In my opintion an easier implementation/documentation would be: Return true if the left element is gretaer than the second element, otherwise false.

What I take from it:

  • Thats a really confusing and misliding method name;
  • Read the docs first... always...

What you guys think about it?

ps: English is not my main language, so maybe the max and Array.max have created the wrong correlation to me.
ps2: Array.min has the same "problem"

You can just call max or min directly in this case, without specifying a comparison predicate.

2 Likes

The actual interface of that function is:

func max(by areInIncreasingOrder: (Element, Element) throws -> Bool) rethrows -> Element?

The predicate argument defines what "increasing order" is for the purposes of the function. When you use > as the predicate, you're saying that a > b implies that a is before b in the order you want to use. Since 3 > 2 and 2 > 1, 1 is the "maximum" according to the predicate that you provided.

As @suyashsrijan notes, you can use .max() if you want the "natural" ordering.

3 Likes