[swift-evolution] [Discussion] Sortable Attribute

David Rönnqvist david.ronnqvist at gmail.com
Wed Aug 17 03:12:47 CDT 2016

Haskell also has a `comparing` function

    comparing :: (Ord a) => (b -> a) -> b -> b -> Ordering

which applies a function on both the left hand side and the right hand side to get two values that can be compared/ordered. 
This makes the call site look something like this:

    sortBy (comparing length) names

The same can be done in Swift, resulting in a similar and very English-like calls site:

    names.sort(by: comparing { $0.characters.count })

That said. While this (the `comparing` function) is a fun exercise in higher order functions, a more Swifty syntax for this is probably a separate overload of the sort/ed/ function.

- David

> On 17 Aug 2016, at 02:17, Silvan Mosberger via swift-evolution <swift-evolution at swift.org> wrote:
>> I'd be in favor. We'd need another name, since the current closure predicate is already standardized to `by:`.
> Haskell uses "on" for sorting with a mapping. There are both
> sortOn <> :: Ord <http://hackage.haskell.org/package/base-> b => (a -> b) -> [a] -> [a]
> and
> sortBy <> :: (a -> a -> Ordering <http://hackage.haskell.org/package/base->) -> [a] -> [a]
> in Haskell.
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160817/66617c76/attachment.html>

More information about the swift-evolution mailing list