[swift-evolution] Reduce with inout
Freak Show
freakshow42 at mac.com
Tue Jan 24 11:25:12 CST 2017
Am I the only one who finds this incredibly ugly and hard to read?
This is more or less solved by inject:into: idiom. There is no reason for inout for this particular problem.
> On Jan 24, 2017, at 06:43, Gwendal Roué via swift-evolution <swift-evolution at swift.org> wrote:
>
> But what if we stop fighting? Isn't the following code the correct version of Chris's vision ?
>
> extension Sequence {
> func reduce<A>(mutating result: inout A, _ combine: (inout A, Iterator.Element) -> ()) {
> for element in self {
> combine(&result, element)
> }
> }
> }
>
> extension Sequence where Iterator.Element: Equatable {
> func uniq() -> [Iterator.Element] {
> var result: [Iterator.Element] = [] // meh
> reduce(mutating: &result) { (result: inout [Iterator.Element], element) in
> if result.last != element {
> result.append(element)
> }
> }
> return result
> }
> }
>
> let x = [1, 1, 2, 3]
> x.uniq() // [1, 2, 3]
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170124/b3f0a19a/attachment.html>
More information about the swift-evolution
mailing list