Hi,
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, yet I'm struggling to do this for Sliceble types in Swift.
To start with a simple case using an Array, I have a recursive function that follows this pattern:
func recurseArray(arr: [Int]) -> [Int] {
guard let first = arr.first else {
return []
}
let rest = recurseArray(Array(dropFirst(arr)))
let next = rest.first ?? 0
return [first + next] + rest
}
(Obviously the real code does a lot more than add each number to the next).
Note the call to `Array(dropFirst(seq))`. Converting to an Array is required since dropFirst actually returns an `ArraySlice`, and an `ArraySlice` isn't `Sliceable`, so I can't pass it to my function.
I'm not sure what sort of optimisation the compiler is capable of here, but it seems to me that creating a new array from a slice unnecessarily won't be optimal. Is there a solution to this?
Furthermore, what I'd *really* like to do is create a version of this function that can take any *Sliceable* type:
func recurseSeq<T: Sliceable where T.Generator.Element == Int>(list: T) -> [Int] {
guard let first = list.first else {
return []
}
let rest = recurseSeq(dropFirst(list)) // <- Error - cannot invoke with argument type T.SubSlice
let next = rest.first ?? 0
return [first + next] + rest
}
This time I don't have a solution to the fact that I have a `SubSlice`. How can I achieve my goal?
Thanks,
Tim