5 ms·
>I don't know what you mean by "sorting key" in this context. He means the item by which you sort. The "by" in your "SortBy" example.
by batista 14y ago
>I don't know what you mean by "sorting key" in this context.
He means the item by which you sort. The "by" in your "SortBy" example.
- barrkel 14y agoYes, but that reading doesn't make sense given what he also wrote - that apparently this would make things more awkward in a static language.
- batista 14y agoHow do you define the sorting key in a static language? With reflection? e.g if anArray is a Java array of Employee objects, and you want to sort on their salary attribute, how do you specify it? anArray.sortBy(???); In a dynamic language it doesn't matter much, since all attribute access amounts to (and is as slow as) reflection on a static language anyway, so you can do something like, say: anArray.sortBy("salary");
- Peaker 14y agoIn Haskell, sortBy takes a comparison function: sortBy :: (a -> a -> Ordering) -> [a] -> [a] And Ordering is defined as: data Ordering = LT | EQ | GT If you want to provide a "key" function rather than a comparison function, you can use sortOn: sortOn :: Ord b => (a -> b) -> [a] -> [a] Which is basically just a sortBy with a function that applies the key function and then compares as normal.
- eru 14y agoAnd everything is statically typed.
- spullara 14y agoIn JDK8 there are method references that could enable this. For example, you can reference a method in a class like Person::age ( equivalent to (Person person) -> person.age() ) that could then be used to sort the collection since Integer implements Comparable.
- pbz 14y agoAnArray.Sort(e -> e.Salary) and if there's no built-in way to compare two Salary objects (let's say they're complex objects), then you come up with an interface that the sorting function would use and the objects would implement. This way you let the objects compare themselves.