[swift-users] 2 x lazy collection bugs

Howard Lovatt howard.lovatt at gmail.com
Mon Feb 8 22:56:44 CST 2016


Hi,

I think I have found a couple of bugs in lazy collections; just checking
before filling. The following code is a filter map version of the Sieve of
Eratosthenes:

func lazyFilterMapForEachLoop(limit: Int = 9) -> [Int] {

    var possibles = Array(count: limit + 1, repeatedValue: true)

    return (2 ... limit).lazy.filter { i in // Has to be lazy and
sequential so that `possibles` is updated before it is used

        print("i BF: \(i)")

        return possibles[i]

    }.map { i in

        print("i AF: \(i)")

        (i * i).stride(through: limit, by: i).forEach { j in

            possibles[j] = false

        }

        return i

    }

}


It produces for a limit of 9:

*i BF: 2*

*i BF: 3*

*i BF: 4*

*i BF: 5*

*i BF: 6*

*i BF: 7*

*i BF: 8*

*i BF: 9*

*i BF: 2*

*i AF: 2*

*i BF: 3*

*i AF: 3*

*i BF: 4*

*i BF: 5*

*i AF: 5*

*i BF: 6*

*i BF: 7*

*i AF: 7*

*i BF: 8*

*i BF: 9*

*fatal error: Index out of range*


There are a couple of odd things about this:

   1. The filter closure is called twice per trial integer! First without
   preceding to the map stage at all, i.e. all values are filtered out! Second
   time through the numbers it does proceed to the map stage as you would
   expect.
   2. It produces an "Index out of range" error despite the fact that
   maximum number processed is 9 which is an allowable index of `possibles`.

Is this a couple of bugs or have I misunderstood something?

Thanks in advance,

  -- Howard.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160209/d1ce34de/attachment.html>


More information about the swift-users mailing list