I'm studying the technique for implementing something similar to Rust try_fold()
, which in un-optimised form should be the following. It incurs heavy overhead of copying collection
. I'd like to know what is the way or ways to optimise it?
extension Sequence {
func try_fold<T, C: MutableCollection<T>, E>(
_ initial: C,
_ transform: (inout C, Element) throws -> Result_<C, E>
) rethrows -> Result_<C, E> {
var collection = initial
for element in self {
switch try transform(&collection, element) {
case .Ok(let updatedCollection):
collection = updatedCollection
case .Err(let error):
return .Err(error)
}
}
return .Ok(collection)
}
}
Enum Result_<T, E>
is defined as follows:
public enum Result_<T, E> {
case Ok(T)
case Err(E)
}