[swift-users] Simplify chained calls

Aaron Bohannon aaron678 at gmail.com
Tue Jun 28 19:20:21 CDT 2016


I think that's about as simple as you can make it unless you allow yourself
to remove more than one element at a time when the minimum appears more
than once.

Here's the question I find interesting: what's the simplest way to change
that code into a version based on lazy collections?  After all, there would
arguably be some real practical value to a lazy recursive selection sort in
cases where only a relatively small prefix of the resulting collection was
expected to be needed.  I took a stab at making your code lazy but quickly
realized that it wasn't going to be as easy as I thought.



On Tue, Jun 28, 2016 at 8:50 AM, Adriano Ferreira via swift-users <
swift-users at swift.org> wrote:

> Hi everyone!
>
> I’m experimenting with this functional selection sort code and I wonder if
> anyone could help me simplify the portion indicated below.
>
>
> // Swift 3
>
> func selectionSort(_ array: [Int]) -> [Int] {
>
>     guard array.count > 1, let minElement = array.min() else {
>         return array
>     }
>
>     let indexOfMinElement = array.index(of: minElement)!
>
>     // All of this just to filter out the first smallest element and
> return the rest
>     // Also tried ‘suffix(from:)' here, but couldn’t make it work properly
>     let rest = array.enumerated()
>                     .filter({ index, _ in index != indexOfMinElement })
>                     .map({ _, element in element })
>
>     return [minElement] + selectionSort(rest)
> }
>
>
> By the way, it feels really weird to chain method calls like this in Swift
> 3, particularly due to the mixing of terms of art (e.g. “filter” and “map”)
> with other methods that follow the -ed/-ing rules from the API
> guidelines (e.g. enumerated).
>
> Best,
>
> — A
>
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160628/255caf09/attachment.html>


More information about the swift-users mailing list