Recursion over a Swift Sliceable

前端 未结 3 982
南旧
南旧 2021-01-12 06:38

I feel that I must be missing something obvious. Decomposing a list into the head and tail and then recursing over the tail is a standard functional programming technique, y

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-12 07:03

    Creating an array in every iteration doesn't seem like a good idea. I don't know if the compiler optimizes it somehow, but you could probably find a different solution.

    For example, in this case, you could drop de recursion and use a for loop instead that modifies the array in place.

    func recurseArray2(var a: [Int]) -> [Int] {
        for var i = a.count-1; i > 0; i-- {
            a[i-1] += a[i]
        }
        return a
    }
    

提交回复
热议问题