[swift-evolution] Reduce with inout

Chris Eidhof chris at eidhof.nl
Wed Jan 18 07:33:36 CST 2017


I think the nice thing about reduce is that you can use it to implement
something in a single line, and directly return it. Making the first
parameter inout would require you to write `var result = ....` and `return
result` (and `result` will be mutable after the call to `reduce`).
Typically, the initial value is some kind of empty value, so copying isn't
a problem. In my usage, making the first parameter inout would make the
code more verbose, decrease readability and not win too much.

I think that making initialValue an inout is a cool idea, but I don't think
it's something for this proposal. (I'm open for good arguments, though).

On Wed, Jan 18, 2017 at 1:48 PM, Georgios Moschovitis via swift-evolution <
swift-evolution at swift.org> wrote:

> the former gives a hint about what someFunction (and the for-loop) is
> doing.
>
> -g.
>
> > On 18 Jan 2017, at 2:32 PM, Jeremy Pereira via swift-evolution <
> swift-evolution at swift.org> wrote:
> >
> >
> >> On 18 Jan 2017, at 12:26, Xiaodi Wu via swift-evolution <
> swift-evolution at swift.org> wrote:
> >>
> >> Thought: if the idea is performance and not drop-in replacement, why
> force the user to incur two copies? If the initial value were inout, this
> function would be more unambiguous even without a new name, and at _worst_
> the user has to declare a variable with var, a worthwhile trade-off to save
> two copies.
> >
> > That’s what I thought also until just now, but then why wouldn’t you
> just use a for …  in loop?
> >
> > i.e. instead of
> >
> >    var foo = 0
> >    let bar: [SomeType] = ...
> >
> >    bar.reduce(mutating: &foo, someFunction)
> >
> > You would write
> >
> >    var foo = 0
> >    let bar: [SomeType] = …
> >
> >    for e in bar {
> >        someFunction(&foo, e)
> >    }
> >
> > which is a bit more readable IMO
> > _______________________________________________
> > swift-evolution mailing list
> > swift-evolution at swift.org
> > https://lists.swift.org/mailman/listinfo/swift-evolution
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>



-- 
Chris Eidhof
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170118/422a26e0/attachment.html>


More information about the swift-evolution mailing list