[swift-evolution] [Proposal draft] Enhanced floating-point protocols

davesweeris at mac.com davesweeris at mac.com
Wed Apr 20 16:23:46 CDT 2016

> On Apr 20, 2016, at 1:15 PM, Dave Abrahams via swift-evolution <swift-evolution at swift.org> wrote:
> on Tue Apr 19 2016, Thorsten Seitz <swift-evolution at swift.org> wrote:
>> I'd like to have something like Summable with 'add', 'adding' and 'zero' being a
>> separate protocol as well as somthing like Multiplicative with 'multiply',
>> 'multiplied' and 'one' being a separate protocol, because these are universally
>> interesting for other cases, e.g. Summable would be useful for defining path
>> lengths in a graph library.
>> Would you mind adding that to the proposal?
> I suspect you may be headed into the realm of
> protocols-as-bags-of-syntax.
You say that like it’s a bad thing… Am I missing the point? (NOT a rhetorical question)

Speaking only for myself, I want stuff broken up into many simpler protocols (which `Arithmetic` and such conform to) because there are many algorithms which only require small parts of the larger protocol. What if I wanted to add a function that sums all the elements in a collection?
extension CollectionType where Generator.Element: Arithmetic {
    func sum() -> Generator.Element {
        var s = Generator.Element()
        for e in self {
        return s

Yeah, it works, but if I want to get the sum of a collection of some custom type, I have to implement *all* of `Arithmetic`, as opposed to just the two parts of it (`init()` and `.add(:)`) that the algorithm actually uses. It’d be both simpler for the users and *more to the point of the function*, if it could be written like this:
extension CollectionType where Generator.Element: Addable { // "Addable" instead of "Arithmetic"
    ... // No change here

Now, if Swift allowed you to add protocol conformance to protocols:
protocol Addable {
    ... // Relevant subset of `Arithmetic`
#for T in Arithmetic { // "#for" because this is clearly macro-ish, and # seems to be what we've settled on for that
    extension T : Addable {} // Don't need anything here since `Arithmetic` already has everything in `Addable`
… then this all becomes a somewhat moot point. If some generic function only needs a subset of a protocol’s functionality, said function’s author could do this “#for T …” song & dance, and their function would be defined with the minimum constraints.

> Look at pages 14 and 24 of
> <http://www.cs.indiana.edu/pub/techreports/TR638.pdf>—which does the job
> right for C++—and you'll see why.
COOL!!! Thanks for posting that, it looks like it’ll be a great read! :-D

- Dave Sweeris
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160420/ee1b8ba6/attachment.html>

More information about the swift-evolution mailing list