Re: [swift-evolution] ternary operator ?: suggestion

2015-12-29 Thread James Campbell via swift-evolution
What if you could wrap the existing switch statement in a closure and return a 
value from that closure like so

Let value = { switch (other) {
Case .Some(let value):
Return value // because this is in a closure the closure will return the value 
not the function this is in
Case .None:
Return "hello" 
}}


Sent from my iPhone

> On 29 Dec 2015, at 07:53, Howard Lovatt via swift-evolution 
>  wrote:
> 
> You can replace the proposed statement `which` (another thread), the existing 
> statement `?:` (this thread), and the global function `??` (which is an odd 
> ball) with matching library methods.
> 
> A library method is likely slower than a built in at this stage until the 
> optimiser improves, but a library function:
> 
> Is documented right in the IDE including code completion, statements aren’t 
> (you don’t see quick help for `for`!)
> Having a library function allows the use case to be throughly investigated. 
> Is worth while as a language statement? What exact features are useful? EG 
> should `which` support pattern matching, general boolean expressions, or 
> simply be `Equatable` as shown below?
> It is simpler to implement, maintain, and change a library function that a 
> built-in.
> There is no need for a keyword.
> 
> First `which`:
> 
> // Alternative to introducing `which` statement
> 
> final
> class Which {
> private
> var result: R?
> 
> private
> let which: I
> 
> init(_ which: I) {
> self.which = which
> }
> 
> func match(value: I, @noescape matchResult: () throws -> R) rethrows -> 
> Self {
> if self.result == nil && self.which == value {
> self.result = try matchResult()
> }
> return self
> }
> 
> func matchDefault(@noescape defaultResult: () throws -> R) rethrows -> R {
> switch self.result {
> case .None:
> return try defaultResult()
> case .Some(let value):
> return value
> }
> }
> }
> 
> 
> // Demo
> enum Color {
> case Red, Blue, Green
> }
> 
> // Which with a default value
> let i1 = Which(Color.Red) // i = 16711680
> .match(.Red)   { 0xFF }
> .match(.Green) { 0x00FF00 }
> .match(.Blue)  { 0x0FF }
> .matchDefault  { 0 }
> 
> // Which that throws an error if it defaults
> let i2: Int! = Which(Color.Green) // i = 16711680
> .match(.Red)   { 0xFF }
> .match(.Green) { 0x00FF00 }
> .match(.Blue)  { 0x0FF }
> .matchDefault  { nil }  // Cant type call to fatalError as no return, 
> hence nil and type Int! (note !)
> 
> Note runtime check for default rather than static check via compiler, not as 
> good but not a big deal most of the time. The vast majority of languages 
> don't do a compiler check on `switch`.
> 
> Similarly the `?:` statement can be replaced:
> 
> // Replacement for `?:` operator
> 
> struct IfFalse {
> private
> let result: R?
> 
> func ifFalse(@noescape falseResult: () throws -> R) rethrows -> R {
> switch self.result {
> case .None:
> return try falseResult()
> case .Some(let value):
> return value
> }
> }
> }
> 
> extension Bool {
> func ifTrue(@noescape trueResult: () throws -> R) rethrows -> 
> IfFalse {
> switch self {
> case true:
> return IfFalse(result: try trueResult())
> case false:
> return IfFalse(result: nil)
> }
> }
> }
> 
> 
> // Demo
> let sB = true.ifTrue{"True"}.ifFalse{"False"} // "True" - for some reason 
> needs {} and not () thinks () form throws
> 
> Whilst the `??` operator is already a library function it is difficult to see 
> in an expression, it gets buried, and is inconsistent in style because it is 
> a non-mathematical operator and a symbol rather than a keyword or keyword 
> followed by a symbol. The space either side of the `??` operator also makes 
> it look like both arguments are of equal importance, whereas it is the left 
> hand side that is important and the right hand side is just a catch.
> 
> // Replacement for `??` operator
> 
> extension Optional {
> func ifNil(@noescape nilResult: () throws -> Wrapped) rethrows -> Wrapped 
> {
> switch self {
> case .None:
> return try nilResult()
> case .Some(let value):
> return value
> }
> }
> }
> 
> 
> // Demo
> let o: String? = nil
> let sO = o.ifNil{"Nil"} // "Nil" - for some reason needs {} and not () thinks 
> () form throws
> 
> 
> Sent from my iPad
> 
>> On 29 Dec 2015, at 4:00 AM, Thorsten Seitz via swift-evolution 
>>  wrote:
>> 
>> No exhaustiveness checking is a serious deficiency :-(
>> 
>> -Thorsten
>> 
>>> Am 17.12.2015 um 08:09 schrieb Brent Royal-Gordon via swift-evolution 
>>> :
>>> 
>>> Actually, this *almost* does what you want. No @autoclosure for the values 
>>> and no exhaustiveness checking, but otherwise...
>> _

Re: [swift-evolution] Epic: Typesafe calculations

2015-12-29 Thread Howard Lovatt via swift-evolution
+1 for the ability to unit check expressions. It is harder to do than it sounds 
because there are many equivalent units, for example force N = mass kg * 
acceleration m/s^2. Therefore N, kg m/s^2, m/s^2 kg, etc. are all equal.

Sent from my iPad

> On 28 Dec 2015, at 9:33 AM, Greg Titus via swift-evolution 
>  wrote:
> 
> 
>> On Dec 27, 2015, at 2:56 AM, Tino Heth <2...@gmx.de> wrote:
>> 
>> 
>>> There’s some unfortunate extra boilerplate here, which could be better 
>>> handled with newtype support in the language, but when compiled with 
>>> optimizations the resulting code is nearly identical to using plain Ints.
>> 
>> Cool — have you checked the generated assembler for this conclusion? But I 
>> guess there is some knowledge on how to build an optimizing compiler in the 
>> core team ;-), so I'd expect little to no penalty (I guess the memory 
>> footprint of plain Ints is still better).
> 
> Yes, I have, and actually, the memory footprint is no different! These are 
> value-types that are exactly word-sized, and so get passed around in 
> registers and stored inline in larger structs. 
> 
>- Greg
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Epic: Typesafe calculations

2015-12-29 Thread Austin Zheng via swift-evolution
+1; first-class affordances to make dimensional analysis possible would be 
incredibly useful.

Austin

> On Dec 29, 2015, at 12:11 AM, Howard Lovatt via swift-evolution 
>  wrote:
> 
> +1 for the ability to unit check expressions. It is harder to do than it 
> sounds because there are many equivalent units, for example force N = mass kg 
> * acceleration m/s^2. Therefore N, kg m/s^2, m/s^2 kg, etc. are all equal.
> 
> Sent from my iPad
> 
>> On 28 Dec 2015, at 9:33 AM, Greg Titus via swift-evolution 
>>  wrote:
>> 
>> 
>>> On Dec 27, 2015, at 2:56 AM, Tino Heth <2...@gmx.de> wrote:
>>> 
>>> 
 There’s some unfortunate extra boilerplate here, which could be better 
 handled with newtype support in the language, but when compiled with 
 optimizations the resulting code is nearly identical to using plain Ints.
>>> 
>>> Cool — have you checked the generated assembler for this conclusion? But I 
>>> guess there is some knowledge on how to build an optimizing compiler in the 
>>> core team ;-), so I'd expect little to no penalty (I guess the memory 
>>> footprint of plain Ints is still better).
>> 
>> Yes, I have, and actually, the memory footprint is no different! These are 
>> value-types that are exactly word-sized, and so get passed around in 
>> registers and stored inline in larger structs. 
>> 
>>   - Greg
>> ___
>> swift-evolution mailing list
>> swift-evolution@swift.org
>> https://lists.swift.org/mailman/listinfo/swift-evolution
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Epic: Typesafe calculations

2015-12-29 Thread Árpád Goretity via swift-evolution
@Howard: While we are at implementation details: I think this is the
typical case of what type theorists call "structural equivalence". You can
think of Newton as a typedef (alias) for kg * m / s^2. Hence, if the
compiler can look this info up, it can most definitely determine that they
are the same and so is m * kg / s / s.

Yes, care needs to be taken about the associativity and commutativity of
multiplication of units, but that's not too hard either, it basically
amounts to some pattern matching along with symbolic computations
respecting algebraic identities (think of it as a compile-time "unit
interpreter") and maybe some post-normalization.



On Tue, Dec 29, 2015 at 9:12 AM, Austin Zheng via swift-evolution <
swift-evolution@swift.org> wrote:

> +1; first-class affordances to make dimensional analysis possible would be
> incredibly useful.
>
> Austin
>
> > On Dec 29, 2015, at 12:11 AM, Howard Lovatt via swift-evolution <
> swift-evolution@swift.org> wrote:
> >
> > +1 for the ability to unit check expressions. It is harder to do than it
> sounds because there are many equivalent units, for example force N = mass
> kg * acceleration m/s^2. Therefore N, kg m/s^2, m/s^2 kg, etc. are all
> equal.
> >
> > Sent from my iPad
> >
> >> On 28 Dec 2015, at 9:33 AM, Greg Titus via swift-evolution <
> swift-evolution@swift.org> wrote:
> >>
> >>
> >>> On Dec 27, 2015, at 2:56 AM, Tino Heth <2...@gmx.de> wrote:
> >>>
> >>>
>  There’s some unfortunate extra boilerplate here, which could be
> better handled with newtype support in the language, but when compiled with
> optimizations the resulting code is nearly identical to using plain Ints.
> >>>
> >>> Cool — have you checked the generated assembler for this conclusion?
> But I guess there is some knowledge on how to build an optimizing compiler
> in the core team ;-), so I'd expect little to no penalty (I guess the
> memory footprint of plain Ints is still better).
> >>
> >> Yes, I have, and actually, the memory footprint is no different! These
> are value-types that are exactly word-sized, and so get passed around in
> registers and stored inline in larger structs.
> >>
> >>   - Greg
> >> ___
> >> swift-evolution mailing list
> >> swift-evolution@swift.org
> >> https://lists.swift.org/mailman/listinfo/swift-evolution
> > ___
> > swift-evolution mailing list
> > swift-evolution@swift.org
> > https://lists.swift.org/mailman/listinfo/swift-evolution
>
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>



-- 
Author of the Sparkling language
http://h2co3.org/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Community Proposal: "This Week In Swift" newsletter

2015-12-29 Thread Roopesh Chander via swift-evolution
I'll try to write up a kind of swift-evolution weekly on my site. I'll
however restrict it to cover only the swift-evolution proposals and
some of the discussions in this mailing list.

The first post is here:
http://roopc.net/last-week-in-swift-evolution/2015/swift-evolution-week-of-12-21/

roop.
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Proposal: CollectionType.cycle property for an infinite sequence

2015-12-29 Thread Andrew Bennett via swift-evolution
+1 looks good, I had a go at implementing it and I think it may require
changes not discussed in the proposal.

You've covered the potential issues fairly well, to be a little more
explicit these are the issues I've found:

 1) LazySequenceType's property array cannot be defined without an infinite
sized array.
 2) what should [1,2,3].cycle.suffix(4) return? [3,1,2,3] probably has the
least surprises, but it's like asking what's the number before infinity.

 3) dropLast should return AnySequence(self), but requires specialisation,
this may have to also be a fatalError (see below).


One issue I don't think you've mentioned, and I don't seem to be able to
resolve is this:

let mySequence = [1,2,3].cycle.dropLast(1)

mySequence.suffix(7)


This could have well defined behaviour (see part 2 above), however the
implementation has some issues.

In this case mySequence is an AnySequence, mySequence.suffix(7) uses
AnySequence's specialisation and so tries to iterate over the entire
sequence to find the suffix. AnySequence is type-erased so there's no
way to specialise when the underlying sequence is infinite (to get a valid
implementation of suffix).

Potential solutions:
 * Replace erased Any* types with a more flexible alternative that doesn't
remove type information (higher kinded types perhaps).
 * Replace SequenceType with two protocols FiniteSequenceType and
InfiniteSequenceType, have type erased versions of each, duplicate all the
things.
 * Add a property to SequenceType to indicate if it's definitely finite
(undefined?), AnySequence uses a different backing implementation depending
on this boolean.

Here's the implementation I used in a playground to toy with this:

public struct CycleSequence : LazySequenceType {

private let base: Base

private init(_ collection: Base) {

self.base = collection

}

@warn_unused_result

public func generate() -> CycleGenerator {

return CycleGenerator(base.generate)

}

public var array: [Base.Generator.Element] {

fatalError("This is undefined!")

}

}


public struct CycleGenerator : GeneratorType {

private let generatorProducer: () -> Base.Generator

private var generator: Base.Generator

private init(_ generatorProducer: () -> Base.Generator) {

self.generatorProducer = generatorProducer

self.generator = generatorProducer()

}

@warn_unused_result

public mutating func next() -> Base.Generator.Element? {

if let element = generator.next() {

return element

}

generator = generatorProducer()

return generator.next()

}

}


extension CycleSequence {

@warn_unused_result

public func dropLast(n: Int) -> AnySequence {

return AnySequence(self)

}

@warn_unused_result

public func suffix(maxLength: Int) -> AnySequence
{

let maxCount = base.count.toIntMax()

let sequenceLength = maxCount >= Int.max.toIntMax() ? Int.max : Int
(maxCount)

if maxLength < sequenceLength {

return AnySequence(base.suffix(maxLength))

}

return self.dropFirst(sequenceLength - (maxLength %
sequenceLength)).prefix(maxLength)

}

}


extension CollectionType {

public var cycle: CycleSequence { return CycleSequence(self) }

}



// this produces an infinite loop when evaluating .suffix(7)

let cycle = ["a", "b", "c"].cycle

cycle.dropLast(1).suffix(7).forEach { print("suffix: \($0)") }



On Mon, Dec 28, 2015 at 6:35 PM, Developer via swift-evolution <
swift-evolution@swift.org> wrote:

> +1.  Stream support is long overdue.
>
> ~Robert Widmann
>
> 2015/12/28 2:20、Kevin Ballard via swift-evolution <
> swift-evolution@swift.org> のメッセージ:
>
> > ## Introduction
> >
> > Add a new property `cycle` to CollectionType that returns an infinite
> SequenceType that yields the elements of the collection in a loop.
> >
> > ## Motivation
> >
> > It's sometimes useful to be able to have an infinite sequence. For
> example, `CollectionOfOne(x).cycle` could be used to have an infinite
> sequence of a single element (similar to Repeat but without a count). A
> common use for infinite sequences is zipping with a finite sequence. As far
> as I'm aware, the stdlib does not currently provide any way to create such
> an infinite sequence.
> >
> > ## Proposed solution
> >
> > Extend CollectionType with a new property `cycle` that yields a type
> that conforms to SequenceType. This sequence yields each element of the
> collection in an infinite loop.
> >
> > ## Detailed design
> >
> > 2 new types would be added:
> >
> > struct CycleSequence : LazySequenceType { ... }
> > struct CycleGenerator : GeneratorType { ... }
> >
> > CollectionType would be extended with a property:
> >
> > extension CollectionType {
> >public var cycle: CycleSequence { get }
> > }
> >
> > This is an extension of CollectionType instead of SequenceType because
> it requires a multi-pass sequence (and SequenceType 

[swift-evolution] [Draft Proposal] Require `final` on protocol extension members

2015-12-29 Thread Brent Royal-Gordon via swift-evolution
I've been working on this on-and-off for a few weeks, and I've finished 
drafting a formal proposal. Comments welcome.





# Require `final` on protocol extension members

## Introduction

Protocol extension members which aren't listed in the protocol itself have an 
unusual behavior: a conforming type can implement an identically named member, 
but instances with the protocol's type are always statically dispatched to the 
protocol's implementation. This can lead to the same instance displaying 
different behavior when it's cast to a  protocol it conforms to. In effect, the 
conforming type's member shadows the protocol's, rather than overriding it. 
This behavior is very surprising to some users.

The lack of a warning on this is [currently considered a 
bug](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151207/001861.html),
 but I think we should go further and cause it to be an error. However, we 
should also provide an escape hatch which permits conflicts in cases where 
they're necessary.

## Motivation

Suppose you write a protocol and extension like this:

protocol Turnable {
func turning() -> Self
mutating func turn()
}
extension Turnable {
mutating func turn() {
self = turning()
}

func turningRepeatedly(additionalTurns: Int) -> Self {
var turnedSelf = self
for _ in 1...additionalTurns {
turnedSelf.turn()
}
return turnedSelf
}
}

Now you want to write a conforming type, `SpimsterWicket`. There are three 
different rules about whether your type has to, or can, implement its own 
versions of these methods.

1. `turning()` is a “protocol method”: it is listed in the protocol but is not 
included in the extension. You *must* implement `turning()` to conform to 
`Turnable`.
2. `turn()` is a “defaulted protocol method”: it is listed in the protocol but 
there is also an implementation of it in the extension. You *may* implement 
`turn()`; if you don’t, the protocol extension’s implementation will be used.
3. `turningRepeatedly(_: Int)` is a “protocol extension method”: it is *not* 
listed in the protocol, but only in the protocol extension. This is the case we 
are trying to address.

Currently, in case 3, Swift permits you to implement your own 
`turningRepeatedly(_: Int)`. However, your implementation may not be called in 
every circumstance that you expect. If you call `turningRepeatedly` on a 
variable of type `SpimsterWicket`, you’ll get `SpimsterWicket`’s implementation 
of the method; however, if you call `turningRepeatedly` on a variable of type 
`Turnable`, you’ll get `Turnable`’s implementation of the method.

var wicket: SpimsterWicket = SpimsterWicket()
var turnable: Turnable = wicket

wicket.turn()   // Calls 
SpimsterWicket.turn()
turnable.turn() // Also calls 
SpimsterWicket.turn()

wicket.turningRepeatedly(5) // Calls 
SpimsterWicket.turningRepeatedly(_:)
turnable.turningRepeatedly(5)   // Calls Turnable.turningRepeatedly(_:)

In most parts of Swift, casting an instance or assigning it to a variable of a 
different type doesn’t change which implementation will be called when you put 
it on the left-hand side of a dot. (I’m leaving aside Objective-C bridging, 
like `Int` to `NSNumber`, which is really a different operation being performed 
with the same syntax.) If you put a `UIControl` into a variable of type 
`UIView`, and then call `touchesBegan()` on that variable, Swift will still 
call `UIControl.touchesBegan()`. The same is true of defaulted protocol 
methods—if you call `turn()` on `turnable`, you’ll get `SpimsterWicket.turn()`.

But this is not true of protocol extension methods. There, the static type of 
the variable—the type known at compile time, the type that the variable is 
labeled with—is used. Thus, calling `turningRepeatedly(_:)` on `wicket` gets 
you `SpimsterWicket`’s implementation, but calling it on `turnable`—even though 
it's merely the same instance casted to a different type—gets you `Turnable`’s 
implementation.

This creates what I call an “incoherent” dispatch, and it occurs nowhere else 
in Swift. In most places in Swift, method dispatch is either based on the 
runtime type (reference types, normal protocol members), or the design of the 
language ensures there’s no difference between dispatching on the compile-time 
type and the runtime type (value types, `final` members). But in protocol 
extension members, dispatch is based on the compile-time type even though the 
runtime type might produce different behavior.

## Proposed solution

I propose that we:

1. C

Re: [swift-evolution] ternary operator ?: suggestion

2015-12-29 Thread Craig Cruden via swift-evolution
That looks pretty ugly.  

I think the best we can hope for at this point is maybe another keyword that 
mirrors switch but is expression based (aka match) — leaving the ternary ? : 
expression as is - which is not all that bad since any if else that becomes a 
compound expression or more than two resultant values (chaining) quickly 
becomes a mess.  

I am not sure that even a “match” expression would be accepted at this point 
because there seems to be general resistance to anything more than the existing 
paradigm with a few functional decorations — and the way of doing things is 
good enough.  

Concurrency is also currently off the table at this point -- the fact that 
immutable pure functional code can theoretically be parsed into a dependance 
graph which would allow for out of order [within scope] parallel execution on 
different threads [not sure if the overhead of doing so would outweigh the 
benefits]…. would also not be of sufficient benefit. 

The primary focus of Swift is a language for UI development, not server 
development….


> On 2015-12-29, at 15:07:57, James Campbell via swift-evolution 
>  wrote:
> 
> What if you could wrap the existing switch statement in a closure and return 
> a value from that closure like so
> 
> Let value = { switch (other) {
> Case .Some(let value):
> Return value // because this is in a closure the closure will return the 
> value not the function this is in
> Case .None:
> Return "hello" 
> }}
> 
> 
> Sent from my iPhone
> 
> On 29 Dec 2015, at 07:53, Howard Lovatt via swift-evolution 
> mailto:swift-evolution@swift.org>> wrote:
> 
>> You can replace the proposed statement `which` (another thread), the 
>> existing statement `?:` (this thread), and the global function `??` (which 
>> is an odd ball) with matching library methods.
>> 
>> A library method is likely slower than a built in at this stage until the 
>> optimiser improves, but a library function:
>> 
>> Is documented right in the IDE including code completion, statements aren’t 
>> (you don’t see quick help for `for`!)
>> Having a library function allows the use case to be throughly investigated. 
>> Is worth while as a language statement? What exact features are useful? EG 
>> should `which` support pattern matching, general boolean expressions, or 
>> simply be `Equatable` as shown below?
>> It is simpler to implement, maintain, and change a library function that a 
>> built-in.
>> There is no need for a keyword.
>> 
>> First `which`:
>> 
>> // Alternative to introducing `which` statement
>> 
>> final
>> class Which {
>> private
>> var result: R?
>> 
>> private
>> let which: I
>> 
>> init(_ which: I) {
>> self.which = which
>> }
>> 
>> func match(value: I, @noescape matchResult: () throws -> R) rethrows -> 
>> Self {
>> if self.result == nil && self.which == value {
>> self.result = try matchResult()
>> }
>> return self
>> }
>> 
>> func matchDefault(@noescape defaultResult: () throws -> R) rethrows -> R 
>> {
>> switch self.result {
>> case .None:
>> return try defaultResult()
>> case .Some(let value):
>> return value
>> }
>> }
>> }
>> 
>> 
>> // Demo
>> enum Color {
>> case Red, Blue, Green
>> }
>> 
>> // Which with a default value
>> let i1 = Which(Color.Red) // i = 16711680 
>> .match(.Red)   { 0xFF }
>> .match(.Green) { 0x00FF00 }
>> .match(.Blue)  { 0x0FF }
>> .matchDefault  { 0 }
>> 
>> // Which that throws an error if it defaults
>> let i2: Int! = Which(Color.Green) // i = 16711680 
>> .match(.Red)   { 0xFF }
>> .match(.Green) { 0x00FF00 }
>> .match(.Blue)  { 0x0FF }
>> .matchDefault  { nil }  // Cant type call to fatalError as no return, 
>> hence nil and type Int! (note !)
>> 
>> Note runtime check for default rather than static check via compiler, not as 
>> good but not a big deal most of the time. The vast majority of languages 
>> don't do a compiler check on `switch`.
>> 
>> Similarly the `?:` statement can be replaced:
>> 
>> // Replacement for `?:` operator
>> 
>> struct IfFalse {
>> private
>> let result: R?
>> 
>> func ifFalse(@noescape falseResult: () throws -> R) rethrows -> R {
>> switch self.result {
>> case .None:
>> return try falseResult()
>> case .Some(let value):
>> return value
>> }
>> }
>> }
>> 
>> extension Bool {
>> func ifTrue(@noescape trueResult: () throws -> R) rethrows -> 
>> IfFalse {
>> switch self {
>> case true:
>> return IfFalse(result: try trueResult())
>> case false:
>> return IfFalse(result: nil)
>> }
>> }
>> }
>> 
>> 
>> // Demo
>> let sB = true.ifTrue{"True"}.ifFalse{"False"} // "True" - for some reason 
>> needs {} and not () thinks () form throws
>> 
>> Whilst the `??` operator is already a library function i

Re: [swift-evolution] ternary operator ?: suggestion

2015-12-29 Thread Matthew Johnson via swift-evolution


Sent from my iPad

> On Dec 29, 2015, at 7:28 AM, Craig Cruden via swift-evolution 
>  wrote:
> 
> That looks pretty ugly.  
> 
> I think the best we can hope for at this point is maybe another keyword that 
> mirrors switch but is expression based (aka match) — leaving the ternary ? : 
> expression as is - which is not all that bad since any if else that becomes a 
> compound expression or more than two resultant values (chaining) quickly 
> becomes a mess.  

I agree that this is probably the best path forward at the moment.  There was a 
post early on showing a ternary-like switch expression.  I don't remember 
whether there were any specific problems with that idea or not, but if there 
aren't that might best route forward.

> 
> I am not sure that even a “match” expression would be accepted at this point 
> because there seems to be general resistance to anything more than the 
> existing paradigm with a few functional decorations — and the way of doing 
> things is good enough.  
> 
> Concurrency is also currently off the table at this point -- the fact that 
> immutable pure functional code can theoretically be parsed into a dependance 
> graph which would allow for out of order [within scope] parallel execution on 
> different threads [not sure if the overhead of doing so would outweigh the 
> benefits]…. would also not be of sufficient benefit. 
> 
> The primary focus of Swift is a language for UI development, not server 
> development….
> 
> 
>> On 2015-12-29, at 15:07:57, James Campbell via swift-evolution 
>>  wrote:
>> 
>> What if you could wrap the existing switch statement in a closure and return 
>> a value from that closure like so
>> 
>> Let value = { switch (other) {
>> Case .Some(let value):
>> Return value // because this is in a closure the closure will return the 
>> value not the function this is in
>> Case .None:
>> Return "hello" 
>> }}
>> 
>> 
>> Sent from my iPhone
>> 
>>> On 29 Dec 2015, at 07:53, Howard Lovatt via swift-evolution 
>>>  wrote:
>>> 
>>> You can replace the proposed statement `which` (another thread), the 
>>> existing statement `?:` (this thread), and the global function `??` (which 
>>> is an odd ball) with matching library methods.
>>> 
>>> A library method is likely slower than a built in at this stage until the 
>>> optimiser improves, but a library function:
>>> 
>>> Is documented right in the IDE including code completion, statements aren’t 
>>> (you don’t see quick help for `for`!)
>>> Having a library function allows the use case to be throughly investigated. 
>>> Is worth while as a language statement? What exact features are useful? EG 
>>> should `which` support pattern matching, general boolean expressions, or 
>>> simply be `Equatable` as shown below?
>>> It is simpler to implement, maintain, and change a library function that a 
>>> built-in.
>>> There is no need for a keyword.
>>> 
>>> First `which`:
>>> 
>>> // Alternative to introducing `which` statement
>>> 
>>> final
>>> class Which {
>>> private
>>> var result: R?
>>> 
>>> private
>>> let which: I
>>> 
>>> init(_ which: I) {
>>> self.which = which
>>> }
>>> 
>>> func match(value: I, @noescape matchResult: () throws -> R) rethrows -> 
>>> Self {
>>> if self.result == nil && self.which == value {
>>> self.result = try matchResult()
>>> }
>>> return self
>>> }
>>> 
>>> func matchDefault(@noescape defaultResult: () throws -> R) rethrows -> 
>>> R {
>>> switch self.result {
>>> case .None:
>>> return try defaultResult()
>>> case .Some(let value):
>>> return value
>>> }
>>> }
>>> }
>>> 
>>> 
>>> // Demo
>>> enum Color {
>>> case Red, Blue, Green
>>> }
>>> 
>>> // Which with a default value
>>> let i1 = Which(Color.Red) // i = 16711680
>>> .match(.Red)   { 0xFF }
>>> .match(.Green) { 0x00FF00 }
>>> .match(.Blue)  { 0x0FF }
>>> .matchDefault  { 0 }
>>> 
>>> // Which that throws an error if it defaults
>>> let i2: Int! = Which(Color.Green) // i = 16711680
>>> .match(.Red)   { 0xFF }
>>> .match(.Green) { 0x00FF00 }
>>> .match(.Blue)  { 0x0FF }
>>> .matchDefault  { nil }  // Cant type call to fatalError as no return, 
>>> hence nil and type Int! (note !)
>>> 
>>> Note runtime check for default rather than static check via compiler, not 
>>> as good but not a big deal most of the time. The vast majority of languages 
>>> don't do a compiler check on `switch`.
>>> 
>>> Similarly the `?:` statement can be replaced:
>>> 
>>> // Replacement for `?:` operator
>>> 
>>> struct IfFalse {
>>> private
>>> let result: R?
>>> 
>>> func ifFalse(@noescape falseResult: () throws -> R) rethrows -> R {
>>> switch self.result {
>>> case .None:
>>> return try falseResult()
>>> case .Some(let value):
>>> return value
>>> }
>>> }
>>> }
>>> 
>>>

Re: [swift-evolution] Proposal: Add scan, takeWhile, dropWhile, and iterate to the stdlib

2015-12-29 Thread Susan Cheng via swift-evolution
Consider this:

extension CollectionType where Generator.Element : Equatable {

/// Returns a subsequence, until a element equal to `value`, containing
the
/// initial elements.
///
/// If none of elements equal to `value`, the result contains all
/// the elements of `self`.
///
/// - Complexity: O(`self.count`)
@warn_unused_result
public func prefixUntil(element: Self.Generator.Element) ->
Self.SubSequence {
return self.prefixUpTo(self.indexOf(element) ?? self.endIndex)
}
}


extension CollectionType {

/// Returns a subsequence, until a element satisfying the predicate,
containing the
/// initial elements.
///
/// If none of elements satisfying the predicate, the result contains
all
/// the elements of `self`.
///
/// - Complexity: O(`self.count`)
@warn_unused_result
public func prefixUntil(@noescape predicate: (Self.Generator.Element)
throws -> Bool) rethrows -> Self.SubSequence {
return self.prefixUpTo(try self.indexOf(predicate) ?? self.endIndex)
}
}


extension CollectionType where Generator.Element : Equatable, Index :
BidirectionalIndexType {
/// Returns a subsequence, until a element equal to `value`, containing
the
/// final elements of `self`.
///
/// If none of elements equal to `value`, the result contains all
/// the elements of `self`.
///
/// - Complexity: O(`self.count`)
@warn_unused_result
public func suffixUntil(element: Self.Generator.Element) ->
Self.SubSequence {
return self.suffixFrom(self.reverse().indexOf(element)?.base ??
self.startIndex)
}
}


extension CollectionType where Index : BidirectionalIndexType {
/// Returns a subsequence, until a element satisfying the predicate,
containing the
/// final elements of `self`.
///
/// If none of elements satisfying the predicate, the result contains
all
/// the elements of `self`.
///
/// - Complexity: O(`self.count`)
@warn_unused_result
public func suffixUntil(@noescape predicate: (Self.Generator.Element)
throws -> Bool) rethrows -> Self.SubSequence {
return self.suffixFrom(try self.reverse().indexOf(predicate)?.base
?? self.startIndex)
}
}

and here are my
utilities:https://github.com/SusanDoggie/Doggie/blob/master/Doggie/Foundation.swift


Kevin Ballard  於 2015年12月29日 上午7:59 寫道:

## Introduction

Add a few more functional sequence utilities to the standard library.

## Motivation

We have map, filter, and reduce, but we're missing a bunch of useful
utilities like scan, iterate, takeWhile, and dropWhile. Interestingly, the
stdlib includes an implementation of scan in the doc comment for
LazySequenceType, it just doesn't actually provide it as API.

## Proposed solution

We extend SequenceType with 3 new methods scan, takeWhile, and dropWhile.
We also add a single global function iterate.

## Detailed design

We add the following extension to SequenceType:

extension SequenceType {
   func scan(initial: T, @noescape combine: (T, Self.Generator.Element)
throws -> T) rethrows -> [T]
   func dropWhile(@noescape dropElement: (Self.Generator.Element) throws ->
Bool) rethrows -> [Self.Generator.Element]
   func takeWhile(@noescape takeElement: (Self.Generator.Element) throws ->
Bool) rethrows -> [Self.Generator.Element]
}

These all take functions, so to follow convention they're @noescape and
return arrays. We also provide an extension of CollectionType that
overrides a couple of these methods:

extension CollectionType {
   func dropWhile(@noescape dropElement: (Self.Generator.Element) throws ->
Bool) rethrows -> Self.SubSequence
   func takeWhile(@noescape takeElement: (Self.Generator.Element) throws ->
Bool) rethrows -> Self.SubSequence
}

We also provide lazy versions:

extension LazySequenceType {
   func scan(initial: T, combine: (T, Self.Generator.Element) -> T) ->
LazyScanSequence
   func dropWhile(dropElement: (Self.Generator.Element) -> Bool) ->
LazyDropWhileSequence
   func takeWhile(takeElement: (Self.Generator.Element) -> Bool) ->
LazyTakeWhileSequence
}

extension LazyCollectionType {
   func dropWhile(dropElement: (Self.Generator.Element) -> Bool) ->
LazyDropWhileCollection
   func takeWhile(takeElement: (Self.Generator.Element) -> Bool) ->
LazyTakeWhileCollection
}

No collection variant of scan is provided because that would require
storing the last value in the index itself, which would cause problems if
the combine function isn't pure.

LazyDropWhileCollection would behave similarly to LazyFilterCollection in
that it runs the predicate against the elements to drop when accessing
startIndex; unlike LazyFilterCollection, because there's nothing else to
skip after that point, the index itself can actually be Self.Elements.Index
(just like a slice). LazyTakeWhileCollection also runs the predicate
against the first element when accessing startIndex, but it does need a
unique index type (because endIndex has to be some sentinel value, as it

Re: [swift-evolution] use standard syntax instead of "do" and "repeat"

2015-12-29 Thread Amir Michail via swift-evolution

> On Dec 28, 2015, at 6:12 PM, Goffredo Marocchi  wrote:
> 
> One could say that is extremely petty to redefine very commonly accepted 
> words (private when we mean file restricted, internal when we mean 
> essentially package when there are already pretty well understood meaning 
> from languages which quite frankly Swift will not kill now or 5 years from 
> now... Java and C++ will keep dominating the landscape with bigger threats 
> coming from JavaScript, ruby, etc... embracing and extending seems like a 
> more successful strategy than taking a defined word and changing its meaning).
> 
> Also, the current do fails the Yoda test... do or do not, no try ;).
> 
> I would suggest replacing repeat with do and the current do with something 
> like throwing which the compiler could actually use to generate errors of we 
> are creating a throwing block without any method that could actually throw 
> and I would not touch the current try keyword to minimise changes.

Maybe “throws” instead of “throwing" as in:

throws {
  let z = try f(x, y)
} catch … {
}

> 
> Sent from my iPhone
> 
>> On 28 Dec 2015, at 22:15, Amir Michail via swift-evolution 
>>  wrote:
>> 
>> 
 On Dec 28, 2015, at 1:25 AM, Brent Royal-Gordon  
 wrote:
 
 So “try” instead of “do”. If there is no catch, then just use braces 
 without a keyword for a block. 
 
 And use do-while instead of repeat-while.
>>> 
>>> Do you also propose no longer marking calls to throwing functions with 
>>> `try`?
>> 
>> Maybe put “throws” after such function calls?
>> 
>> try {
>> let z = f(x,y) throws
>> } catch … {
>> }
>> 
>> You could also have “throws?” and “throws!” following the function call.
>> 
>>> Have you read the "Error-Handling Rationale" document in the Swift 
>>> repository? If not, please do: 
>>> 
>>>  If so, please explain why you disagree with it.
>>> 
>>> -- 
>>> Brent Royal-Gordon
>>> Architechies
>> 
>> ___
>> swift-evolution mailing list
>> swift-evolution@swift.org
>> https://lists.swift.org/mailman/listinfo/swift-evolution

___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Epic: Typesafe calculations

2015-12-29 Thread Tim Hawkins via swift-evolution
This just popped up on HN and may be relevant to this discussion.


http://www.home.hs-karlsruhe.de/~fado0001/2015-32C3/paper-onecolumn-colour.pdf


On Tue, Dec 29, 2015, 16:11 Howard Lovatt via swift-evolution <
swift-evolution@swift.org> wrote:

> +1 for the ability to unit check expressions. It is harder to do than it
> sounds because there are many equivalent units, for example force N = mass
> kg * acceleration m/s^2. Therefore N, kg m/s^2, m/s^2 kg, etc. are all
> equal.
>
> Sent from my iPad
>
> > On 28 Dec 2015, at 9:33 AM, Greg Titus via swift-evolution <
> swift-evolution@swift.org> wrote:
> >
> >
> >> On Dec 27, 2015, at 2:56 AM, Tino Heth <2...@gmx.de> wrote:
> >>
> >>
> >>> There’s some unfortunate extra boilerplate here, which could be better
> handled with newtype support in the language, but when compiled with
> optimizations the resulting code is nearly identical to using plain Ints.
> >>
> >> Cool — have you checked the generated assembler for this conclusion?
> But I guess there is some knowledge on how to build an optimizing compiler
> in the core team ;-), so I'd expect little to no penalty (I guess the
> memory footprint of plain Ints is still better).
> >
> > Yes, I have, and actually, the memory footprint is no different! These
> are value-types that are exactly word-sized, and so get passed around in
> registers and stored inline in larger structs.
> >
> >- Greg
> > ___
> > swift-evolution mailing list
> > swift-evolution@swift.org
> > https://lists.swift.org/mailman/listinfo/swift-evolution
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Epic: Typesafe calculations

2015-12-29 Thread Tino Heth via swift-evolution

> Yes, care needs to be taken about the associativity and commutativity of 
> multiplication of units, but that's not too hard either, it basically amounts 
> to some pattern matching along with symbolic computations respecting 
> algebraic identities (think of it as a compile-time "unit interpreter") and 
> maybe some post-normalization.
I agree: "doing it right" is no rocket science (pun intended ;-) — but I'm 
quite sure it won't be possible unless the macro-system that might be 
introduced with Swift 4 is ready.
But there are possible workarounds for the lack metaprogramming the type 
system, so products with three or four factors should be possible without even 
changing the compiler (it will be ugly, though):
It is easy to define +/- for composed units, but it is a huge amount of code 
that has to be generated for all permutations.

@Tim Hawkins:
Thanks for posting the link — although it reminds me on feeling bad for not 
being in Hamburg right now ;-)
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] ternary operator ?: suggestion

2015-12-29 Thread Charles Constant via swift-evolution
I'm with Matthew/Craig.

We discussed a couple very ternary-like versions earlier in the thread,
which I increasingly think are the best options.

The major objection to this came from Lattner, and his objection, if I have
it right, is "this proposal doesn't add enough functionality to justify the
additional complexity/confusion"

The sticking point, at the moment, is formulating a really persuasive
argument for "why we need this." If we can't do that, this proposal is dead.






On Tue, Dec 29, 2015 at 5:38 AM, Matthew Johnson via swift-evolution <
swift-evolution@swift.org> wrote:

>
>
> Sent from my iPad
>
> On Dec 29, 2015, at 7:28 AM, Craig Cruden via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> That looks pretty ugly.
>
> I think the best we can hope for at this point is maybe another keyword
> that mirrors switch but is expression based (aka match) — leaving the
> ternary ? : expression as is - which is not all that bad since any if else
> that becomes a compound expression or more than two resultant values
> (chaining) quickly becomes a mess.
>
>
> I agree that this is probably the best path forward at the moment.  There
> was a post early on showing a ternary-like switch expression.  I don't
> remember whether there were any specific problems with that idea or not,
> but if there aren't that might best route forward.
>
>
> I am not sure that even a “match” expression would be accepted at this
> point because there seems to be general resistance to anything more than
> the existing paradigm with a few functional decorations — and the way of
> doing things is good enough.
>
> Concurrency is also currently off the table at this point -- the fact that
> immutable pure functional code can theoretically be parsed into a
> dependance graph which would allow for out of order [within scope] parallel
> execution on different threads [not sure if the overhead of doing so would
> outweigh the benefits]…. would also not be of sufficient benefit.
>
> The primary focus of Swift is a language for UI development, not server
> development….
>
>
> On 2015-12-29, at 15:07:57, James Campbell via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> What if you could wrap the existing switch statement in a closure and
> return a value from that closure like so
>
> Let value = { switch (other) {
> Case .Some(let value):
> Return value // because this is in a closure the closure will return the
> value not the function this is in
> Case .None:
> Return "hello"
> }}
>
>
> Sent from my iPhone
>
> On 29 Dec 2015, at 07:53, Howard Lovatt via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> You can replace the proposed statement `which` (another thread), the
> existing statement `?:` (this thread), and the global function `??` (which
> is an odd ball) with matching library methods.
>
> A library method is likely slower than a built in at this stage until the
> optimiser improves, but a library function:
>
>
>1. Is documented right in the IDE including code completion,
>statements aren’t (you don’t see quick help for `for`!)
>2. Having a library function allows the use case to be throughly
>investigated. Is worth while as a language statement? What exact features
>are useful? EG should `which` support pattern matching, general boolean
>expressions, or simply be `Equatable` as shown below?
>3. It is simpler to implement, maintain, and change a library function
>that a built-in.
>4. There is no need for a keyword.
>
>
> First `which`:
>
> // Alternative to introducing `which` statement
>
> final
> class Which {
> private
> var result: R?
>
>
> private
> let which: I
>
>
> init(_ which: I) {
> self.which = which
> }
>
>
> func match(value: I, @noescape matchResult: () throws -> R) rethrows
>  -> Self {
> if self.result == nil && self.which == value {
> self.result = try matchResult()
> }
> return self
> }
>
>
> func matchDefault(@noescape defaultResult: () throws -> R) rethrows
>  -> R {
> switch self.result {
> case .None:
> return try defaultResult()
> case .Some(let value):
> return value
> }
> }
> }
>
>
> // Demo
> enum Color {
> case Red, Blue, Green
> }
>
> // Which with a default value
> let i1 = Which(Color.Red) // i = 16711680
> .match(.Red)   { 0xFF }
> .match(.Green) { 0x00FF00 }
> .match(.Blue)  { 0x0FF }
> .matchDefault  { 0 }
>
> // Which that throws an error if it defaults
> let i2: Int! = Which(Color.Green) // i = 16711680
> .match(.Red)   { 0xFF }
> .match(.Green) { 0x00FF00 }
> .match(.Blue)  { 0x0FF }
> .matchDefault  { nil }  // Cant type call to fatalError as no return,
> hence nil and type Int! (note !)
>
>
> Note runtime check for default rather than static check via compiler, not
> as good but not a big deal most of the time. The vast majority of languages

Re: [swift-evolution] ternary operator ?: suggestion

2015-12-29 Thread Matthew Johnson via swift-evolution

> On Dec 29, 2015, at 8:54 AM, Charles Constant  wrote:
> 
> I'm with Matthew/Craig.
> 
> We discussed a couple very ternary-like versions earlier in the thread, which 
> I increasingly think are the best options.
> 
> The major objection to this came from Lattner, and his objection, if I have 
> it right, is "this proposal doesn't add enough functionality to justify the 
> additional complexity/confusion"
> 
> The sticking point, at the moment, is formulating a really persuasive 
> argument for "why we need this." If we can't do that, this proposal is dead.

I was originally hoping we could remove ternary and just make if and switch 
expressions.  

However, It seems to be clear that 1) there are enough challenges to making if 
and switch expressions that it won’t happen any time soon, if ever and 2) the 
conciseness of ternary is highly valued and it will be hard to beat it on 
conciseness.

Given that, a ternary-like switch expression seems pretty valuable IMO.  I 
think concrete examples showing how it helps to increase readability over: 1) 
switch statements and 2) immediately invoked closures are the best way to 
demonstrate the need for this feature.

> 
> 
> 
> 
> 
> 
> On Tue, Dec 29, 2015 at 5:38 AM, Matthew Johnson via swift-evolution 
> mailto:swift-evolution@swift.org>> wrote:
> 
> 
> Sent from my iPad
> 
> On Dec 29, 2015, at 7:28 AM, Craig Cruden via swift-evolution 
> mailto:swift-evolution@swift.org>> wrote:
> 
>> That looks pretty ugly.  
>> 
>> I think the best we can hope for at this point is maybe another keyword that 
>> mirrors switch but is expression based (aka match) — leaving the ternary ? : 
>> expression as is - which is not all that bad since any if else that becomes 
>> a compound expression or more than two resultant values (chaining) quickly 
>> becomes a mess.  
> 
> I agree that this is probably the best path forward at the moment.  There was 
> a post early on showing a ternary-like switch expression.  I don't remember 
> whether there were any specific problems with that idea or not, but if there 
> aren't that might best route forward.
> 
>> 
>> I am not sure that even a “match” expression would be accepted at this point 
>> because there seems to be general resistance to anything more than the 
>> existing paradigm with a few functional decorations — and the way of doing 
>> things is good enough.  
>> 
>> Concurrency is also currently off the table at this point -- the fact that 
>> immutable pure functional code can theoretically be parsed into a dependance 
>> graph which would allow for out of order [within scope] parallel execution 
>> on different threads [not sure if the overhead of doing so would outweigh 
>> the benefits]…. would also not be of sufficient benefit. 
>> 
>> The primary focus of Swift is a language for UI development, not server 
>> development….
>> 
>> 
>>> On 2015-12-29, at 15:07:57, James Campbell via swift-evolution 
>>> mailto:swift-evolution@swift.org>> wrote:
>>> 
>>> What if you could wrap the existing switch statement in a closure and 
>>> return a value from that closure like so
>>> 
>>> Let value = { switch (other) {
>>> Case .Some(let value):
>>> Return value // because this is in a closure the closure will return the 
>>> value not the function this is in
>>> Case .None:
>>> Return "hello" 
>>> }}
>>> 
>>> 
>>> Sent from my iPhone
>>> 
>>> On 29 Dec 2015, at 07:53, Howard Lovatt via swift-evolution 
>>> mailto:swift-evolution@swift.org>> wrote:
>>> 
 You can replace the proposed statement `which` (another thread), the 
 existing statement `?:` (this thread), and the global function `??` (which 
 is an odd ball) with matching library methods.
 
 A library method is likely slower than a built in at this stage until the 
 optimiser improves, but a library function:
 
 Is documented right in the IDE including code completion, statements 
 aren’t (you don’t see quick help for `for`!)
 Having a library function allows the use case to be throughly 
 investigated. Is worth while as a language statement? What exact features 
 are useful? EG should `which` support pattern matching, general boolean 
 expressions, or simply be `Equatable` as shown below?
 It is simpler to implement, maintain, and change a library function that a 
 built-in.
 There is no need for a keyword.
 
 First `which`:
 
 // Alternative to introducing `which` statement
 
 final
 class Which {
 private
 var result: R?
 
 private
 let which: I
 
 init(_ which: I) {
 self.which = which
 }
 
 func match(value: I, @noescape matchResult: () throws -> R) rethrows 
 -> Self {
 if self.result == nil && self.which == value {
 self.result = try matchResult()
 }
 return self
 }
 
 func matchDefault(@noescape defaultResult: (

Re: [swift-evolution] Proposal: Implement a rotate algorithm, equivalent to std::rotate() in C++

2015-12-29 Thread Sergey Bolshedvorsky via swift-evolution
Hi Dmitri,

Thank you for your feedback! I’ve updated a proposal based on your comments: 
https://github.com/apple/swift-evolution/pull/77 


> What jumps at me immediately is that the APIs are using integers to specify 
> positions in the collection.  I think they should be using collection's 
> indices instead.
Yes you are right, the APIs should use collection indexes. 

> I'm unsure why we need `first` and `last` -- shouldn't the API operate on the 
> whole collection?  We have slices to operate on subsequences.

The C++ implementation allows to rotate all elements of collection or only some 
of them. A precondition of this function is that
0 <= first <= middle <= last < count

> Another point to consider is how the call site of these functions looks like:

 I’ve added 2 API usage examples to PR:

Example of rotating all elements of the collection:

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
let rotated = numbers.rotateFrom(0, middle: 3, last: 8)
// rotated contains [4, 5, 6, 7, 8, 9, 1, 2, 3]

Example of rotating some elements of the collection:

let numbers = [10, 12, 13, 11, 15, 14]
let rotated = numbers.rotateFrom(1, middle: 3, last: 4)
// rotated contains [10, 11, 12, 13, 15, 14]


> It is interesting that you are proposing that the new algorithms should 
> produce lazy views.  I agree this is consistent with the rest of the library, 
> but I'm worried about the performance implications.  Have you thought about 
> this?  One point to keep in mind is that you can implement the 
> `_copyToNativeArrayBuffer()` and `_initializeTo()` entry points in all new 
> lazy collections, using the optimal eager algorithm.  This way, converting 
> them to arrays will be fast.
Thanks for pointing out the performance issue with lazy views. I will draft the 
implementation of algorithms for regular collections at first and then I will 
think how it can be reused with lazy views.

Sergey



> On 29 Dec 2015, at 06:38, Dmitri Gribenko  wrote:
> 
> On Mon, Dec 28, 2015 at 10:29 PM, Sergey Bolshedvorsky via swift-evolution 
> mailto:swift-evolution@swift.org>> wrote:
> Hi all,
> 
> I have created a PR with with a formal proposal for this feature: 
> https://github.com/apple/swift-evolution/pull/77 
> 
> 
> What are your thoughts?
> 
> Thank you for the proposal!
> 
> What jumps at me immediately is that the APIs are using integers to specify 
> positions in the collection.  I think they should be using collection's 
> indices instead.
> 
> I'm unsure why we need `first` and `last` -- shouldn't the API operate on the 
> whole collection?  We have slices to operate on subsequences.
> 
> It is interesting that you are proposing that the new algorithms should 
> produce lazy views.  I agree this is consistent with the rest of the library, 
> but I'm worried about the performance implications.  Have you thought about 
> this?  One point to keep in mind is that you can implement the 
> `_copyToNativeArrayBuffer()` and `_initializeTo()` entry points in all new 
> lazy collections, using the optimal eager algorithm.  This way, converting 
> them to arrays will be fast.
> 
> Another point to consider is how the call site of these functions looks like:
> 
> collection.rotate(10, middle: 20, last: 30)
> 
> The first number hangs in the air, it is unclear what its meaning is.
> 
> Dmitri
> 
> -- 
> main(i,j){for(i=2;;i++){for(j=2;j (j){printf("%d\n",i);}}} /*Dmitri Gribenko  >*/

___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Idea] Add an (Index, Element) sequence to CollectionType

2015-12-29 Thread Wallacy via swift-evolution
FWIW: In cases like this, just remember call ".reverse()" and remove from
the back.

var array = [ "", "a", "b", "c", "", "d" ]
for (index, element) in array.enumerate().reverse() {
if element == "" {
array.removeAtIndex(index)
}
}
print(array) // ["a", "b", "c", "d"]

zip is useful when we have ArraySlice as has been said before:

var array = [ "", "a", "b", "c", "", "d", "", "e", "" , "f", "g", ""]
var secondHalf = array[array.count/2.. escreveu:

>
> The original example contains a bug which is present on all looping
> version/alternative due to the mutating nature of the array. Using the zip
> implementation:
>
> var array = [ "", "a", "b", "c", "", "d" ]
> var secondHalf = array[array.count/2.. for (index, element) in zip(secondHalf.indices, secondHalf) {
> if element == "" {
> secondHalf.removeAtIndex(index)
> }
> }
>
> The variable index cycles through 3,4 and 5; but in order to be able to
> remove the right element beyond the first removal, the variable index
> should have cycled through 3, 4 and 4 (as some elements got shifted after
> the first mutation). Mutating the array/list which one loops over is a
> risky business and is a nice source of bugs (including infinite loop). If
> this (Index, Element) is further investigated, it should consider that one
> may also want to do a insert(:atIndex:), and may expect the (Index,
> Element) to have proper Index but only for the original Element.
>
> Dany St-Amant
>
>
> Le 28 déc. 2015 à 01:06, Kevin Ballard via swift-evolution <
> swift-evolution@swift.org> a écrit :
>
> What you're asking for can already be done with `zip(col.indices, col)`.
> And in my experience the need for this sort of thing is rare enough that
> there's no need to have a dedicated property for it in the stdlib. The few
> times that I've needed this sort of thing, I've always just said
>
> for index in col.indices {
> let elt = col[index]
> // ...
> }
>
> and that's pretty simple. But if I ever did need to map it, I'd just use
> the aforementioned zip() expression.
>
> -Kevin Ballard
>
> On Sun, Dec 27, 2015, at 12:08 AM, Patrick Pijnappel via swift-evolution
> wrote:
>
> -- Introduction
>
> There should be a property on CollectionType that returns a sequence of
> (Index, Element) tuples.
> Currently enumerate() is often used instead, but it is not well suited to
> the task and can lead to bugs.
>
>
>
> -- Motivation
>
> Using enumerate() instead of an (Index, Element) sequence has two main
> problems.
> Both arise because enumerate() returns a sequence of (n, Element) tuples,
> where n is the element *number*, instead of a sequence of (Index, Element)
> .
>
> 1) It doesn't work for collections not indexed by integers.
>
> 2) It doesn't do what you might expect in some cases, as indices do not
> always start at 0.
> For example ArraySlice's indices do not: array[2..<5] starts with index 2.
> Consider the following code to take the 2nd half of the array and remove
> all empty elements:
>
> var array = [ "", "a", "b", "c", "", "d" ]
> var secondHalf = array[array.count/2.. for (index, element) in secondHalf.enumerate() {
> if element == "" {
> secondHalf.removeAtIndex(index)
> }
> }
>
> This code will crash (ignoring for a moment this should probably be using
> filter).
>
>
>
> -- Alternatives
>
> The same effect can already be achieved using the following:
>
> for index in collection.indices {
>   let element = collection[index]
>   // ...
> }
>
> However having a dedicated (Index, Element) sequence has the following
> advantages:
> a) It can help prevent people from using enumerate() inappropriately.
> b) It is very common use case that deserves shortening.
> c) It can be chained (e.g. to map).
>
>
>
> -- Proposed Solution
>
> Add a property/method on CollectionType that returns a sequence of (Index,
> Element) tuples.
> For example, using a property named indexed:
>
> for (index, element) in collection.indexed {
>   // ...
> }
>
> This should be the preferred idiom when you want both the index and the
> element.
>
> Note that enumerate() does still have valid roles to play:
> - When you actually do want the element number, not the index.
> - When you have a SequenceType, as it isn't indexed.
>
>
>
> -- Implementation
>
> The feature could be entirely implemented using existing constructs:
>
> extension CollectionType {
>   var indexed: AnySequence<(Index, Generator.Element)> {
> return AnySequence(indices.lazy.map { ($0, self[$0]) })
>   }
> }
>
> Alternatively, a dedicated SequenceType and/or GeneratorType could be
> added.
>
>
> *___*
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
> ___
> swift-evolution mai

Re: [swift-evolution] Epic: Typesafe calculations

2015-12-29 Thread plx via swift-evolution
FWIW I began a draft for a newtype/wrapper-synthesis proposal but abandoned it 
due to:

- (a) perceived lack of community interest 
- (b) running into *serious* complications around associated types

…note that this *didn’t* directly-address any sort of units system, but would 
be somewhat complementary (and a good first step in that direction). 

The short version of the issue in (b) is that whereas the desired 
behavior-and-semantics for “direct" newtype/wrapper-style constructs — where 
`Foo` is a newtype of `Bar` — seem pretty straightforward to specify, that’s 
not enough; you also have to deal with the “indirect” scenario, e.g. with 
situations in which `Foo` is a newtype of `Bar`, but `Bar` is also a 
`CollectionType`, and you want `Foo` to also be a `CollectionType` (or any 
other similar case).

In that specific case, you *probably* want this:

- `Foo.Element` == `Bar.Element`
- `Foo.Index` == a *newtype* of `Bar.Index` (e.g., not just a bare `Bar.Index`)
- `Foo.Generator` == `Bar.Generator` (I assume)
- `Foo.SubSequence` == 
  - `Foo`, when `Bar.SubSequence` == `Bar`
  - `Slice`, when `Bar.SubSequence` == `Slice`
  - a *newtype* of `Bar.SubSequence`, when `Bar.SubSequence` is some other type

…and although you can quibble with the exact choices here, the general issue is 
that it’s seemingly quite hard to really achieve the type-safety goals for some 
newtype/wrapper proposal without also addressing how to potentially “re-wrap” 
the wrapped type’s associated types.

It can be done I’m sure, but it’s seemingly rather involved; it definitely 
feels like a “Swift 4 (or later)” feature. If there’s enough community interest 
I could pick it up and flesh it out a bit more.

> On Dec 24, 2015, at 9:36 PM, Stephen Christopher via swift-evolution 
>  wrote:
> 
> I have been working for a couple weeks (since the previous [newtype 
> discussion](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151207/001821.html
>  
> )
>  ) on a related pitch. There seem to me to be multiple ways to solve this 
> problem - a newtype(esque) keyword, struct subtyping, or forwarding as 
> Matthew is suggesting. I’d hoped to have a discussion starter out before the 
> holidays, but it takes a fair amount of work to put together even a decent 
> draft for a proposal. This is top of my list currently for a way to 
> contribute though. Looking forward to the ensuing discussions.
> 
> Thanks for the pointer on class delegation. I’ve looked at delegated 
> properties there (which came up in relation to Joe’s recent proposal for 
> behaviors on properties).
> 
> - Step Christopher
> 
> 
> 
> On Thu, Dec 24, 2015 at 2:40 PM, Matthew Johnson via swift-evolution 
> mailto:swift-evolution@swift.org>> wrote:
> 
> 
> Sent from my iPad
> 
> > On Dec 24, 2015, at 1:07 PM, Tino Heth <2...@gmx.de > 
> > wrote:
> >
> >
> >> I'm planning to write a proposal for automatic forwarding.
> > Something like class delegation in Kotlin?
> > Please hurry, I've no work to distract me for the rest of the year, and 
> > extending typealias could be a very quick proposal ;-)
> 
> Details are still brewing.  I am not familiar with class delegation in Kotlin 
> but will look it up.  Thanks for mentioning it!
> 
> I plan to spend a lot of time on Swift proposal work over the next week and a 
> half but can't make any promises on timing.  I made that mistake with my 
> proposal on flexible memberwise initialization which ended up taking a couple 
> weeks longer than I expected (for several reasons).  What I can say is that 
> this is pretty high on my Swift proposal priority list.
> 
> Matthew
> ___
> swift-evolution mailing list
> swift-evolution@swift.org 
> https://lists.swift.org/mailman/listinfo/swift-evolution 
> 
> 
>  ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Proposal: CollectionType.cycle property for an infinite sequence

2015-12-29 Thread plx via swift-evolution
Personally I’d say this should be a -1 for standard-library inclusion.

Swift’s not really built to handle infinite sequences right now; until they are 
handed better by the standard library convenience methods for creating them 
shouldn’t be in the standard library.

You’d also want to call `fatalError` for at least `reduce`, `reverse`, `sort`, 
`split`(?), `flatMap`, `dropLast`, `suffix`, and `forEach`.

`startsWith` and `elementsEqual` and `lexicographicComparison` are all broken 
if you call them like e.g. `self.startsWith(self)`.

You can conceivably implement a non-crashing `contains`, `minElement` and 
`maxElement` on `CycleSequence` by calling through to the wrapped collection, 
but that’ll seemingly evaporate as soon as your `CycleSequence` winds up hidden 
inside an `AnySequence`.

Which illustrates why this is a -1 for me; there's nothing wrong with the 
functionality in isolation and there’s nothing wrong with infinite sequences, 
but the standard library should play well with itself, and this wouldn’t play 
well with the rest of the standard library.

That opinion could change as the language changes or the standard library 
evolves.

> On Dec 28, 2015, at 1:20 AM, Kevin Ballard via swift-evolution 
>  wrote:
> 
> ## Introduction
> 
> Add a new property `cycle` to CollectionType that returns an infinite 
> SequenceType that yields the elements of the collection in a loop.
> 
> ## Motivation
> 
> It's sometimes useful to be able to have an infinite sequence. For example, 
> `CollectionOfOne(x).cycle` could be used to have an infinite sequence of a 
> single element (similar to Repeat but without a count). A common use for 
> infinite sequences is zipping with a finite sequence. As far as I'm aware, 
> the stdlib does not currently provide any way to create such an infinite 
> sequence.
> 
> ## Proposed solution
> 
> Extend CollectionType with a new property `cycle` that yields a type that 
> conforms to SequenceType. This sequence yields each element of the collection 
> in an infinite loop.
> 
> ## Detailed design
> 
> 2 new types would be added:
> 
> struct CycleSequence : LazySequenceType { ... }
> struct CycleGenerator : GeneratorType { ... }
> 
> CollectionType would be extended with a property:
> 
> extension CollectionType {
>public var cycle: CycleSequence { get }
> }
> 
> This is an extension of CollectionType instead of SequenceType because it 
> requires a multi-pass sequence (and SequenceType does not provide that 
> guarantee). The returned type conforms to SequenceType instead of 
> CollectionType because there is no possible `endIndex` that satisfies the 
> requirement of being reachable from `startIndex` by zero or more applications 
> of `successor()`.
> 
> Because the default eager versions of map and filter will execute forever on 
> an infinite sequence, CycleSequence conforms to LazySequenceType instead of 
> SequenceType in order to provide lazy versions of those functions. 
> Additionally, it will provide implementations of the eager versions that 
> simply trigger a fatalError(), as the alternative is an infinite loop that 
> consumes more and more memory.
> 
> ## Impact on existing code
> 
> None
> 
> -Kevin Ballard
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


[swift-evolution] [Proposal Draft] automatic protocol forwarding

2015-12-29 Thread Matthew Johnson via swift-evolution
I have completed a first draft of a proposal to introduce automatic protocol 
forwarding.  I’m looking forward to feedback from everyone!
Automatic protocol forwarding

Proposal: SE- 

Author(s): Matthew Johnson 
Status: Review
Review manager: TBD
Introduction

Automatic protocol forwarding introduces the ability to use delegation without 
the need write forwarding member implementations manually. 

A preliminary mailing list thread on this topic had the subject protocol based 
invocation forwarding 

Motivation

Delegation is a robust, composition oriented design technique that keeps 
interface and implementation inheritance separate. The primary drawback to this 
technique is that it requires a lot of manual boilerplate to forward 
implemenation to the implementing member. This proposal eliminates the need to 
write such boilerplate manually, thus making delegation-based designs much more 
convenient and attractive.

This proposal may also serve as the foundation for a future enhancement 
allowing a very concise “newtype” declaration.

Proposed solution

I propose introducing a forward declaration be allowed within a type 
declaration or type extension. The forward declaration will cause the compiler 
to synthesize implementations of the members required by the forwarded 
protocols. The synthesized implementations will simply forward the method call 
to the specified member.

The basic declaration looks like this:

forward Protocol, OtherProtocol to memberIdentifier
The first clause contains a list of protocols to forward. 

The second clause specifies the identifier of the property to which the 
protocol members will be forwarded. Any visible property that implements the 
members required by the protocol is eligible for forwarding. It does not matter 
whether it is stored, computed, lazy, etc.

It is also possible to include an access control declaration modifier to 
specify the visibility of the synthesized members.

Self parameters

When a protocol member includes a Self parameter forwarding implementations 
must accept the forwarding type but supply an argument of the forwardee type 
when making the forwarding call. The most straightforward way to do this is to 
simply use the same property getter that is used when forwarding. This is the 
proposed solution.

Self return types

When a protocol member includes a Self return type forwarding implementations 
must return the forwarding type. However, the forwardee implmentation will 
return a value of the forwardee type. This result must be used to produce a 
value of the forwarding type in some way.

The solution in this proposal is based on an ad-hoc overloading convention. A 
protocol-based solution would probably be desirable if it were possible, 
however it is not. This proposal supports forwarding to more than one member, 
possibly with different types. A protocol-based solution would require the 
forwarding type to conform to the “Self return value conversion” protocol once 
for each forwardee type.

Static members

When a forwardee value is returned from a static member an initializer will be 
used to produce a final return value. The initializer must be visible at the 
source location of the forward declaration and must look like this:

struct Forwarder {
let forwardee: Forwardee
forward P to forwardee
init(_ forwardeeReturnValue: Forwardee) { //... }
}
Instance members

When a forwardee value is returned from an instance member an instance method 
will be used to transform the return value into a value of the correct type. An 
instance method is necessary in order to allow the forwarding type to access 
the state of the instance upon which the method was called when performing the 
transformation.

If the instance method is not implemented the initializer used for static 
members will be used instead.

The transformation has the form:

struct Forwarder {
let forwardee: Forwardee
forward P to forwardee
func transformedForwardingReturnValue(forwardeeReturnValue: Forwardee) -> 
Forwarder { //... }
}
NOTE: This method should have a better name. Suggestions are appreciated!

Examples

Basic example

NOTE: Forwardee does not actually conform to P itself. Conformance is not 
required to synthesize the forwarding member implementations. It is only 
required that members necessary for forwarding exist. This is particularly 
important to the second example.

public protocol P {
typealias TA
var i: Int
func foo() -> Bool
}

private struct Forwardee {
typealias TA = String
var i: Int = 42
func foo() -> Bool { return true }
}

public struct Forwarder {
private let forwardee: Forwardee
}

extension Forwarder: P {
// user declares
public forward P to forwardee

// com

Re: [swift-evolution] use standard syntax instead of "do" and "repeat"

2015-12-29 Thread Goffredo Marocchi via swift-evolution
I think we want to leave throws and rethrows at the method signature level and 
to mean that we want to throw an actual exception so I would not reuse it this 
way as it would be confusing.

Sent from my iPhone

> On 29 Dec 2015, at 14:24, Amir Michail  wrote:
> 
> 
>> On Dec 28, 2015, at 6:12 PM, Goffredo Marocchi  wrote:
>> 
>> One could say that is extremely petty to redefine very commonly accepted 
>> words (private when we mean file restricted, internal when we mean 
>> essentially package when there are already pretty well understood meaning 
>> from languages which quite frankly Swift will not kill now or 5 years from 
>> now... Java and C++ will keep dominating the landscape with bigger threats 
>> coming from JavaScript, ruby, etc... embracing and extending seems like a 
>> more successful strategy than taking a defined word and changing its 
>> meaning).
>> 
>> Also, the current do fails the Yoda test... do or do not, no try ;).
>> 
>> I would suggest replacing repeat with do and the current do with something 
>> like throwing which the compiler could actually use to generate errors of we 
>> are creating a throwing block without any method that could actually throw 
>> and I would not touch the current try keyword to minimise changes.
> 
> Maybe “throws” instead of “throwing" as in:
> 
> throws {
>  let z = try f(x, y)
> } catch … {
> }
> 
>> 
>> Sent from my iPhone
>> 
>>> On 28 Dec 2015, at 22:15, Amir Michail via swift-evolution 
>>>  wrote:
>>> 
>>> 
> On Dec 28, 2015, at 1:25 AM, Brent Royal-Gordon  
> wrote:
> 
> So “try” instead of “do”. If there is no catch, then just use braces 
> without a keyword for a block. 
> 
> And use do-while instead of repeat-while.
 
 Do you also propose no longer marking calls to throwing functions with 
 `try`?
>>> 
>>> Maybe put “throws” after such function calls?
>>> 
>>> try {
>>> let z = f(x,y) throws
>>> } catch … {
>>> }
>>> 
>>> You could also have “throws?” and “throws!” following the function call.
>>> 
 Have you read the "Error-Handling Rationale" document in the Swift 
 repository? If not, please do: 
 
  If so, please explain why you disagree with it.
 
 -- 
 Brent Royal-Gordon
 Architechies
>>> 
>>> ___
>>> swift-evolution mailing list
>>> swift-evolution@swift.org
>>> https://lists.swift.org/mailman/listinfo/swift-evolution
> 
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal draft] Generalized Naming for Any Function

2015-12-29 Thread Bartlomiej Cichosz via swift-evolution
Hi,

I am sorry if this was already considered (jumping in a bit late), but what 
about using the following syntax:

let fn = aGameView.insertSubview(_, aboveSubview: _)

This is similar to a function calling syntax (rather than function definition 
syntax), but with _ instead of specific arguments.

The reason I think this may be useful is because it could be generalized to a 
syntax for partial application (assuming such functionality is desired in 
Swift):

let insertCardViewAtTheBottomOfTheDeck = aGameView.insertSubview(_, 
aboveSubview: playingSurfaceView)

then:

insertCardViewAtTheBottomOfTheDeck(anotherCard)


Or:

let insertMyCard = aGameView.insertSubview(myCard, aboveSubview: _)

then:

insertMyCard(aboveSubview:otherCard)


In the above examples, the definitions of insertCardViewAtTheBottomOfTheDeck 
and insertMyCard would return partially applied functions. Whereas the first 
example, the definition of fn, where all arguments are specified as _ is a 
special case that refers to the original function.

Some of the issues mentioned in the proposal remain, for example, how to 
disambiguate same function names with different parameter types, such as:

let fn1 = aGameView.insertSubview(_, aboveSubview: _:CardView)

or 

let fn2 = aGameView.insertSubview(_, aboveSubview: _ as CardView)



Or different return values:

let fn3 = aGameView.insertSubview(_, aboveSubview: playingSurfaceView) -> Bool


Getters and setters, using the example from the proposal:

let getRow = someMatrix.subscript(row: _).get


All of the above assumes, of course, that presence of one or more _ is 
sufficient to parse these not as function calls, but partial application 
expressions (with the special case of all _s being just reference to the 
original function). If that’s the case, it would eliminate the need for 
back-ticks.

Regards,

Bart



> On Dec 27, 2015, at 02:22, Douglas Gregor via swift-evolution 
>  wrote:
> 
> Hi all,
> 
> Here’s a proposal draft to allow one to name any function in Swift. In 
> effect, it’s continuing the discussion of retrieving getters and setters as 
> functions started by Michael Henson here:
> 
>   
> https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151207/002168.html
>  
> 
> 
> the proposal follows, and is available here as well:
> 
>   
> https://github.com/DougGregor/swift-evolution/blob/generalized-naming/proposals/-generalized-naming.md
>  
> 
> 
> Comments appreciated!
> 
> Generalized Naming for Any Function
> 
> Proposal: SE- 
> 
> Author(s): Doug Gregor 
> Status: Awaiting Review
> Review manager: TBD
>  
> Introduction
> 
> Swift includes support for first-class functions, such that any function (or 
> method) can be placed into a value of function type. However, it is not 
> possible to specifically name every function that is part of a Swift 
> program---one cannot provide the argument labels when naming a function, nor 
> are property and subscript getters and setters referenceable. This proposal 
> introduces a general syntax that allows one to name anything that is a 
> function within Swift in an extensible manner.
> 
> Swift-evolution thread: Michael Henson started a thread about the 
> getter/setter issue here 
> ,
>  continued here 
> .
>  See the Alternatives considered 
> 
>  section for commentary on that discussion.
> 
>  
> Motivation
> 
> It's fairly common in Swift for multiple functions or methods to have the 
> same "base name", but be distinguished by parameter labels. For example, 
> UIView has three methods with the same base name insertSubview:
> 
> extension UIView {
>   func insertSubview(view: UIView, at index: Int)
>   func insertSubview(view: UIView, aboveSubview siblingSubview: UIView)
>   func insertSubview(view: UIView, belowSubview siblingSubview: UIView)
> }
> When calling these methods, the argument labels distinguish the different 
> methods, e.g.,
> 
> someView.insertSubview(view, at: 3)
> someView.insertSubview(view, aboveSubview: otherView)
> someView.insertSubview(view, belowSubview: otherView)
> However, when referencing the function to create a function value, one cannot 

[swift-evolution] Why aren't source to source transformations part of the Swift language standard?

2015-12-29 Thread Amir Michail via swift-evolution
Source to source transformations are part of a developer’s job, don’t need a 
GUI, and can be done more easily and accurately by the Swift compiler. 
Moreover, the compiler could be made interactive taking in extra information 
from the developer as required during the "compile" (again without requiring a 
GUI).

You could have special directives for source to source transformations such as:

@extractMethodBegin
… swift code ...
@extractMethodEnd

@indentBegin
… swift code ...
@indentEnd

@commitCommentFragmentBegin
… swift code ...
@commitCommentFragmentEnd

etc…

Why encourage reinventing the wheel by pushing source to source transformations 
to tools of varying quality and completeness?
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal draft] Generalized Naming for Any Function

2015-12-29 Thread Joe Groff via swift-evolution
We also have a problem with disambiguating same-named members that come from 
different extensions, whether via protocol extensions or independent concrete 
extensions from different modules. Could we extend this scheme to allow for 
disambiguating extension methods by protocol/module name?

extension ProtocolA { func foo() }
extension ProtocolB { func foo() }

public struct Foo: ProtocolA, ProtocolB {
  func callBothFoos() {
self.`ProtocolA.foo`()
self.`ProtocolB.foo`()
  }
}

import A // extends Bar with bar()
import B // also extends Bar with bar()

extension Bar {
  func callBothBars() {
self.`A.bar`()
self.`B.bar`()
  }
}

-Joe

> On Dec 26, 2015, at 11:22 PM, Douglas Gregor via swift-evolution 
>  wrote:
> 
> Hi all,
> 
> Here’s a proposal draft to allow one to name any function in Swift. In 
> effect, it’s continuing the discussion of retrieving getters and setters as 
> functions started by Michael Henson here:
> 
>   
> https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151207/002168.html
>  
> 
> 
> the proposal follows, and is available here as well:
> 
>   
> https://github.com/DougGregor/swift-evolution/blob/generalized-naming/proposals/-generalized-naming.md
>  
> 
> 
> Comments appreciated!
> 
> Generalized Naming for Any Function
> 
> Proposal: SE- 
> 
> Author(s): Doug Gregor 
> Status: Awaiting Review
> Review manager: TBD
>  
> Introduction
> 
> Swift includes support for first-class functions, such that any function (or 
> method) can be placed into a value of function type. However, it is not 
> possible to specifically name every function that is part of a Swift 
> program---one cannot provide the argument labels when naming a function, nor 
> are property and subscript getters and setters referenceable. This proposal 
> introduces a general syntax that allows one to name anything that is a 
> function within Swift in an extensible manner.
> 
> Swift-evolution thread: Michael Henson started a thread about the 
> getter/setter issue here 
> ,
>  continued here 
> .
>  See the Alternatives considered 
> 
>  section for commentary on that discussion.
> 
>  
> Motivation
> 
> It's fairly common in Swift for multiple functions or methods to have the 
> same "base name", but be distinguished by parameter labels. For example, 
> UIView has three methods with the same base name insertSubview:
> 
> extension UIView {
>   func insertSubview(view: UIView, at index: Int)
>   func insertSubview(view: UIView, aboveSubview siblingSubview: UIView)
>   func insertSubview(view: UIView, belowSubview siblingSubview: UIView)
> }
> When calling these methods, the argument labels distinguish the different 
> methods, e.g.,
> 
> someView.insertSubview(view, at: 3)
> someView.insertSubview(view, aboveSubview: otherView)
> someView.insertSubview(view, belowSubview: otherView)
> However, when referencing the function to create a function value, one cannot 
> provide the labels:
> 
> let fn = someView.insertSubview // ambiguous: could be any of the three 
> methods
> In some cases, it is possible to use type annotations to disambiguate:
> 
> let fn: (UIView, Int) = someView.insertSubview// ok: uses 
> insertSubview(_:at:)
> let fn: (UIView, UIView) = someView.insertSubview // error: still ambiguous!
> To resolve the latter case, one must fall back to creating a closure:
> 
> let fn: (UIView, UIView) = { view, otherView in
>   button.insertSubview(view, otherView)
> }
> which is painfully tedious. A similar workaround is required to produce a 
> function value for a getter of a property, e.g.,
> 
> extension UIButton {
>   var currentTitle: String? { ... }
> }
> 
> var fn: () -> String? = { () in
>   return button.currentTitle
> }
> One additional bit of motivation: Swift should probably get some way to ask 
> for the Objective-C selector for a given method (rather than writing a string 
> literal). The argument to such an operation would likely be a reference to a 
> method, which would benefit from being able to name any method, including 
> getters and setters.
> 
>  
> 

Re: [swift-evolution] Proposal: CollectionType.cycle property for an infinite sequence

2015-12-29 Thread Kevin Ballard via swift-evolution
On Tue, Dec 29, 2015, at 02:27 AM, Andrew Bennett wrote:
> +1 looks good, I had a go at implementing it and I think it may
> require changes not discussed in the proposal.
>
> You've covered the potential issues fairly well, to be a little more
> explicit these are the issues I've found:
>> 1) LazySequenceType's property array cannot be defined without an
>> infinite sized array.

Good point, I forgot about that one. But that's really just the same
thing as saying `Array(seq)`, so I don't have any problems with just
saying that it's an error to access that property on an infinite
sequence (in this case I'd just make it fatalError()).

I do wish I could mark those sorts of things with @available(*,
unavailable, message="this cannot be used on an infinite sequence") to
provide a compile-time error for anyone accessing it on the concrete
type (generic access via the protocol wouldn't catch that of course),
but I discovered that if you try and use that on a function like map(),
Swift actually goes ahead and adds the default implementation to your
type anyway (basically throwing away your marked-as-unavailable method).
Which I suppose makes some sense, but I wish there was an alternative
that worked.

>> 2) what should [1,2,3].cycle.suffix(4) return? [3,1,2,3] probably has
>> the least surprises, but it's like asking what's the number before
>> infinity.

Nothing. You can't take a suffix on an infinite list. There is no end to
it. That method should be overridden to fatalError() (or if not, it
would just loop forever).

>> 3) dropLast should return AnySequence(self), but requires
>> specialisation, this may have to also be a fatalError (see below).

Good point. Since there is no end to the sequence, dropLast() on an
infinite sequence is still an infinite sequence. Honestly, the default
implementation should work fine, but it's probably a good idea to just
override it to return AnySequence(self) as you suggest anyway because
it's an easy win.

> One issue I don't think you've mentioned, and I don't seem to be able
> to resolve is this:
>> let mySequence = [1,2,3].cycle.dropLast(1) mySequence.suffix(7)
>
> This could have well defined behaviour (see part 2 above), however the
> implementation has some issues.

The only well-defined behavior this can have is to loop forever (or to
abort with a fatalError). It's simply an error to take a suffix() of an
infinite sequence.

> In this case mySequence is an AnySequence, mySequence.suffix(7)
> uses AnySequence's specialisation and so tries to iterate over the
> entire sequence to find the suffix. AnySequence is type-erased so
> there's no way to specialise when the underlying sequence is infinite
> (to get a valid implementation of suffix).

That's fine, looping forever is a perfectly reasonable course of action
when you try and take a suffix() of an infinite sequence.

> Potential solutions: * Replace erased Any* types with a more flexible
> alternative that doesn't remove type information (higher kinded types
> perhaps).

The whole point of the Any* types is they do remove type information.

> * Replace SequenceType with two protocols FiniteSequenceType and
> InfiniteSequenceType, have type erased versions of each, duplicate all
> the things.

What's the point of this? All you can do with that is get rid of a
couple of methods that would loop forever on infinite sequences, but
it's a lot of work and a lot of duplication for what seems like an
extremely small win.

I'd much rather just come up with some alternative to @available(*,
unavailable) that actually leaves the method intact but provides a compile-
time error if you call it. This would be strictly intended for protocol
methods, as you'd still need to provide an implementation (such as
`fatalError("not supported")`) that would be called when the method is
accessed via a generic type bound on the protocol (or via an existential
protocol value, for protocols that support that).

> * Add a property to SequenceType to indicate if it's definitely finite
> (undefined?), AnySequence uses a different backing implementation
> depending on this boolean.

And what would AnySequence do with that information? All it could really
do is make sure to call fatalError() instead of looping forever when a
method like suffix() is called.

-Kevin Ballard
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal draft] Generalized Naming for Any Function

2015-12-29 Thread Matthew Johnson via swift-evolution

> On Dec 29, 2015, at 12:17 PM, Joe Groff via swift-evolution 
>  wrote:
> 
> We also have a problem with disambiguating same-named members that come from 
> different extensions, whether via protocol extensions or independent concrete 
> extensions from different modules. Could we extend this scheme to allow for 
> disambiguating extension methods by protocol/module name?
> 
> extension ProtocolA { func foo() }
> extension ProtocolB { func foo() }
> 
> public struct Foo: ProtocolA, ProtocolB {
>   func callBothFoos() {
> self.`ProtocolA.foo`()
> self.`ProtocolB.foo`()
>   }
> }
> 
> import A // extends Bar with bar()
> import B // also extends Bar with bar()
> 
> extension Bar {
>   func callBothBars() {
> self.`A.bar`()
> self.`B.bar`()
>   }
> }
> 

Like many others I am not a fan of the backticks being required in common use 
cases, but I don’t mind them in edge cases at all.  In those cases they are far 
better than no solution.  So +1 to using backticks to allow disambiguation!

> -Joe
> 
>> On Dec 26, 2015, at 11:22 PM, Douglas Gregor via swift-evolution 
>> mailto:swift-evolution@swift.org>> wrote:
>> 
>> Hi all,
>> 
>> Here’s a proposal draft to allow one to name any function in Swift. In 
>> effect, it’s continuing the discussion of retrieving getters and setters as 
>> functions started by Michael Henson here:
>> 
>>  
>> https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151207/002168.html
>>  
>> 
>> 
>> the proposal follows, and is available here as well:
>> 
>>  
>> https://github.com/DougGregor/swift-evolution/blob/generalized-naming/proposals/-generalized-naming.md
>>  
>> 
>> 
>> Comments appreciated!
>> 
>> Generalized Naming for Any Function
>> 
>> Proposal: SE- 
>> 
>> Author(s): Doug Gregor 
>> Status: Awaiting Review
>> Review manager: TBD
>>  
>> Introduction
>> 
>> Swift includes support for first-class functions, such that any function (or 
>> method) can be placed into a value of function type. However, it is not 
>> possible to specifically name every function that is part of a Swift 
>> program---one cannot provide the argument labels when naming a function, nor 
>> are property and subscript getters and setters referenceable. This proposal 
>> introduces a general syntax that allows one to name anything that is a 
>> function within Swift in an extensible manner.
>> 
>> Swift-evolution thread: Michael Henson started a thread about the 
>> getter/setter issue here 
>> ,
>>  continued here 
>> .
>>  See the Alternatives considered 
>> 
>>  section for commentary on that discussion.
>> 
>>  
>> Motivation
>> 
>> It's fairly common in Swift for multiple functions or methods to have the 
>> same "base name", but be distinguished by parameter labels. For example, 
>> UIView has three methods with the same base name insertSubview:
>> 
>> extension UIView {
>>   func insertSubview(view: UIView, at index: Int)
>>   func insertSubview(view: UIView, aboveSubview siblingSubview: UIView)
>>   func insertSubview(view: UIView, belowSubview siblingSubview: UIView)
>> }
>> When calling these methods, the argument labels distinguish the different 
>> methods, e.g.,
>> 
>> someView.insertSubview(view, at: 3)
>> someView.insertSubview(view, aboveSubview: otherView)
>> someView.insertSubview(view, belowSubview: otherView)
>> However, when referencing the function to create a function value, one 
>> cannot provide the labels:
>> 
>> let fn = someView.insertSubview // ambiguous: could be any of the three 
>> methods
>> In some cases, it is possible to use type annotations to disambiguate:
>> 
>> let fn: (UIView, Int) = someView.insertSubview// ok: uses 
>> insertSubview(_:at:)
>> let fn: (UIView, UIView) = someView.insertSubview // error: still ambiguous!
>> To resolve the latter case, one must fall back to creating a closure:
>> 
>> let fn: (UIView, UIView) = { view, otherView in
>>   button.insertSubview(view, otherView)
>> }
>> which is painfully tedious. A similar workaround is required to produce a 
>> function value for a getter of a property, e.g.,
>> 
>> extension UIButton {
>>   var currentTitle: String?

Re: [swift-evolution] [Proposal draft] Generalized Naming for Any Function

2015-12-29 Thread Douglas Gregor via swift-evolution


Sent from my iPhone

> On Dec 29, 2015, at 10:17 AM, Joe Groff  wrote:
> 
> We also have a problem with disambiguating same-named members that come from 
> different extensions, whether via protocol extensions or independent concrete 
> extensions from different modules. Could we extend this scheme to allow for 
> disambiguating extension methods by protocol/module name?

That's a fantastic idea!

> 
> extension ProtocolA { func foo() }
> extension ProtocolB { func foo() }
> 
> public struct Foo: ProtocolA, ProtocolB {
>   func callBothFoos() {
> self.`ProtocolA.foo`()
> self.`ProtocolB.foo`()
>   }
> }
> 
> import A // extends Bar with bar()
> import B // also extends Bar with bar()
> 
> extension Bar {
>   func callBothBars() {
> self.`A.bar`()
> self.`B.bar`()
>   }
> }
> 
> -Joe
> 
>> On Dec 26, 2015, at 11:22 PM, Douglas Gregor via swift-evolution 
>>  wrote:
>> 
>> Hi all,
>> 
>> Here’s a proposal draft to allow one to name any function in Swift. In 
>> effect, it’s continuing the discussion of retrieving getters and setters as 
>> functions started by Michael Henson here:
>> 
>>  
>> https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151207/002168.html
>> 
>> the proposal follows, and is available here as well:
>> 
>>  
>> https://github.com/DougGregor/swift-evolution/blob/generalized-naming/proposals/-generalized-naming.md
>> 
>> Comments appreciated!
>> 
>> Generalized Naming for Any Function
>> Proposal: SE-
>> Author(s): Doug Gregor
>> Status: Awaiting Review
>> Review manager: TBD
>> Introduction
>> 
>> Swift includes support for first-class functions, such that any function (or 
>> method) can be placed into a value of function type. However, it is not 
>> possible to specifically name every function that is part of a Swift 
>> program---one cannot provide the argument labels when naming a function, nor 
>> are property and subscript getters and setters referenceable. This proposal 
>> introduces a general syntax that allows one to name anything that is a 
>> function within Swift in an extensible manner.
>> 
>> Swift-evolution thread: Michael Henson started a thread about the 
>> getter/setter issue here, continued here. See the Alternatives considered 
>> section for commentary on that discussion.
>> 
>> Motivation
>> 
>> It's fairly common in Swift for multiple functions or methods to have the 
>> same "base name", but be distinguished by parameter labels. For example, 
>> UIView has three methods with the same base name insertSubview:
>> 
>> extension UIView {
>>   func insertSubview(view: UIView, at index: Int)
>>   func insertSubview(view: UIView, aboveSubview siblingSubview: UIView)
>>   func insertSubview(view: UIView, belowSubview siblingSubview: UIView)
>> }
>> When calling these methods, the argument labels distinguish the different 
>> methods, e.g.,
>> 
>> someView.insertSubview(view, at: 3)
>> someView.insertSubview(view, aboveSubview: otherView)
>> someView.insertSubview(view, belowSubview: otherView)
>> However, when referencing the function to create a function value, one 
>> cannot provide the labels:
>> 
>> let fn = someView.insertSubview // ambiguous: could be any of the three 
>> methods
>> In some cases, it is possible to use type annotations to disambiguate:
>> 
>> let fn: (UIView, Int) = someView.insertSubview// ok: uses 
>> insertSubview(_:at:)
>> let fn: (UIView, UIView) = someView.insertSubview // error: still ambiguous!
>> To resolve the latter case, one must fall back to creating a closure:
>> 
>> let fn: (UIView, UIView) = { view, otherView in
>>   button.insertSubview(view, otherView)
>> }
>> which is painfully tedious. A similar workaround is required to produce a 
>> function value for a getter of a property, e.g.,
>> 
>> extension UIButton {
>>   var currentTitle: String? { ... }
>> }
>> 
>> var fn: () -> String? = { () in
>>   return button.currentTitle
>> }
>> One additional bit of motivation: Swift should probably get some way to ask 
>> for the Objective-C selector for a given method (rather than writing a 
>> string literal). The argument to such an operation would likely be a 
>> reference to a method, which would benefit from being able to name any 
>> method, including getters and setters.
>> 
>> Proposed solution
>> 
>> Swift currently has a back-tick escaping syntax that lets one use keywords 
>> for names, which would otherwise fail to parse. For example,
>> 
>> func `try`() -> Bool { ... }
>> declares a function named try, even though try is a keyword. I propose to 
>> extend the back-tick syntax to allow compound Swift names (e.g., 
>> insertSubview(_:aboveSubview:)) and references to the accessors of 
>> properties (e.g., the getter for currentTitle). Specifically,
>> 
>> Compound names can be written entirely within the back-ticks, e.g.,
>> 
>> let fn = someView.`insertSubview(_:at:)`
>> let fn1 = someView.`insertSubview(_:aboveSubview:)`
>> The same syntax can also refer to initializers, e.g.,

Re: [swift-evolution] [Proposal draft] Generalized Naming for Any Function

2015-12-29 Thread Erica Sadun via swift-evolution
Talk about things you didn't know you needed until you see them. This is a 
really nice way of disambiguating!

-- E

> On Dec 29, 2015, at 12:03 PM, Douglas Gregor via swift-evolution 
>  wrote:
> 
> 
> 
> Sent from my iPhone
> 
> On Dec 29, 2015, at 10:17 AM, Joe Groff  > wrote:
> 
>> We also have a problem with disambiguating same-named members that come from 
>> different extensions, whether via protocol extensions or independent 
>> concrete extensions from different modules. Could we extend this scheme to 
>> allow for disambiguating extension methods by protocol/module name?
> 
> That's a fantastic idea!
> 
>> 
>> extension ProtocolA { func foo() }
>> extension ProtocolB { func foo() }
>> 
>> public struct Foo: ProtocolA, ProtocolB {
>>   func callBothFoos() {
>> self.`ProtocolA.foo`()
>> self.`ProtocolB.foo`()
>>   }
>> }
>> 
>> import A // extends Bar with bar()
>> import B // also extends Bar with bar()
>> 
>> extension Bar {
>>   func callBothBars() {
>> self.`A.bar`()
>> self.`B.bar`()
>>   }
>> }
>> 
>> -Joe
>> 
>>> On Dec 26, 2015, at 11:22 PM, Douglas Gregor via swift-evolution 
>>> mailto:swift-evolution@swift.org>> wrote:
>>> 
>>> Hi all,
>>> 
>>> Here’s a proposal draft to allow one to name any function in Swift. In 
>>> effect, it’s continuing the discussion of retrieving getters and setters as 
>>> functions started by Michael Henson here:
>>> 
>>> 
>>> https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151207/002168.html
>>>  
>>> 
>>> 
>>> the proposal follows, and is available here as well:
>>> 
>>> 
>>> https://github.com/DougGregor/swift-evolution/blob/generalized-naming/proposals/-generalized-naming.md
>>>  
>>> 
>>> 
>>> Comments appreciated!
>>> 
>>> Generalized Naming for Any Function
>>> 
>>> Proposal: SE- 
>>> 
>>> Author(s): Doug Gregor 
>>> Status: Awaiting Review
>>> Review manager: TBD
>>>  
>>> Introduction
>>> 
>>> Swift includes support for first-class functions, such that any function 
>>> (or method) can be placed into a value of function type. However, it is not 
>>> possible to specifically name every function that is part of a Swift 
>>> program---one cannot provide the argument labels when naming a function, 
>>> nor are property and subscript getters and setters referenceable. This 
>>> proposal introduces a general syntax that allows one to name anything that 
>>> is a function within Swift in an extensible manner.
>>> 
>>> Swift-evolution thread: Michael Henson started a thread about the 
>>> getter/setter issue here 
>>> ,
>>>  continued here 
>>> .
>>>  See the Alternatives considered 
>>> 
>>>  section for commentary on that discussion.
>>> 
>>>  
>>> Motivation
>>> 
>>> It's fairly common in Swift for multiple functions or methods to have the 
>>> same "base name", but be distinguished by parameter labels. For example, 
>>> UIView has three methods with the same base name insertSubview:
>>> 
>>> extension UIView {
>>>   func insertSubview(view: UIView, at index: Int)
>>>   func insertSubview(view: UIView, aboveSubview siblingSubview: UIView)
>>>   func insertSubview(view: UIView, belowSubview siblingSubview: UIView)
>>> }
>>> When calling these methods, the argument labels distinguish the different 
>>> methods, e.g.,
>>> 
>>> someView.insertSubview(view, at: 3)
>>> someView.insertSubview(view, aboveSubview: otherView)
>>> someView.insertSubview(view, belowSubview: otherView)
>>> However, when referencing the function to create a function value, one 
>>> cannot provide the labels:
>>> 
>>> let fn = someView.insertSubview // ambiguous: could be any of the three 
>>> methods
>>> In some cases, it is possible to use type annotations to disambiguate:
>>> 
>>> let fn: (UIView, Int) = someView.insertSubview// ok: uses 
>>> insertSubview(_:at:)
>>> let fn: (UIView, UIView) = someView.insertSubview // error: still ambiguous!
>>> To resolve the latter case, one must fall back to creating a closure:
>>> 
>>> let fn: (UIView, UIView) = { view, otherView in
>>>   button.insertSubview(view, otherView)
>>> }
>>> which is painfully tedious. A similar workaround

Re: [swift-evolution] Proposal: CollectionType.cycle property for an infinite sequence

2015-12-29 Thread Kevin Ballard via swift-evolution
On Tue, Dec 29, 2015, at 08:14 AM, plx via swift-evolution wrote:
> Personally I’d say this should be a -1 for standard-library inclusion.
> 
> Swift’s not really built to handle infinite sequences right now; until they 
> are handed better by the standard library convenience methods for creating 
> them shouldn’t be in the standard library.

As far as I can tell, the only way in which it's "not really built" to handle 
this is that there are multiple constructs that attempt to eagerly consume an 
entire sequence, and using these with an infinite sequence would end up looping 
forever. But I don't consider that to be a particularly serious problem. You 
could "fix" it by refactoring SequenceType into two protocols, SequenceType 
(for possibly-infinite sequences) and FiniteSequenceType (for known-finite 
sequences) and then going over the entire standard library and updating various 
spots to use FiniteSequenceType, except this would be very limiting (sequences 
that are not known if they're infinite to the compiler could still be valid for 
various eager algorithms if the programmer knows it will be finite in practice).

> You’d also want to call `fatalError` for at least `reduce`, `reverse`, 
> `sort`, `split`(?), `flatMap`, `dropLast`, `suffix`, and `forEach`.

You can only do it for the ones defined in the protocol, not ones defined in 
extensions. This means map, filter, forEach, and suffix.

split is actually perfectly implementable for a CycleSequence, although it does 
need a custom implementation. split is bounded by at most Int.max splits, which 
means it is guaranteed to terminate even for an infinite sequence (although the 
final subsequence does need to be infinite[1]). Even if there are no separators 
in the cycle, it can just return the cycle itself.

[1] Interestingly, the current implementation actually dumps the remainder into 
an Array and returns that (wrapped in AnySequence), which is curious because it 
would be perfectly legal for it to just wrap the generator up in AnySequence 
and return that instead. I'm tempted to submit a PR to change that now, as it 
just seems like unnecessary work to use an array.

> `startsWith` and `elementsEqual` and `lexicographicComparison` are all broken 
> if you call them like e.g. `self.startsWith(self)`.

That's true, but what do you really expect when you're calling them with two 
infinite sequences? It's not so much that they're broken as it is that you're 
creating an infinite loop without any way to break out. And FWIW, 
lexicographicalCompare is actually something you might want to explicitly 
support on infinite sequences if you know your sequences aren't equal and want 
to find out which one is less than the other.

There are plenty of ways to shoot yourself in the foot. I don't think infinite 
sequences are really the big problem you're making them out to be.

> You can conceivably implement a non-crashing `contains`, `minElement` and 
> `maxElement` on `CycleSequence` by calling through to the wrapped collection, 
> but that’ll seemingly evaporate as soon as your `CycleSequence` winds up 
> hidden inside an `AnySequence`.

You can't override those anyway in a generic context, because they're not 
members of the protocol, they're just extensions. You could implement them such 
that your implementation is called when working on the concrete CycleSequence 
type, but I'm not sure if that's a great idea to do that when the actual 
behavior differs from calling it generically on SequenceType (well, triggering 
a fatalError() instead of an infinite loop is fine because they're both Bottom, 
but returning a valid result in one context and looping infinitely in the other 
seems bad).

Of course, these methods could actually be moved into the protocol itself, 
which would let us override them. I'm not entirely sure why they aren't in the 
protocol to begin with, I guess because there's not much need for overriding 
these outside of infinite sequences (well, finite sorted sequences could 
provide an optimized min/maxElement, and an optimized version of contains(_: 
Self.Generator.Element), but maybe there's tradeoffs to doing this, e.g. maybe 
there's some reason why having a large protocol witness table is a bad idea).

> Which illustrates why this is a -1 for me; there's nothing wrong with the 
> functionality in isolation and there’s nothing wrong with infinite sequences, 
> but the standard library should play well with itself, and this wouldn’t play 
> well with the rest of the standard library.

Ultimately, there's not much difference between an infinite sequence and a 
sequence of Int.max elements. The latter is finite, but it's so massive 
(especially on 64-bit) that any kind of eager processing is going to hit the 
same problems as an infinite sequence. Every problem you describe will be a 
problem with the simple sequence `(0.. That opinion could change as the language changes or the standard library 
> evolves.
> 
> > On Dec 28, 2015, at 1:2

Re: [swift-evolution] Why aren't source to source transformations part of the Swift language standard?

2015-12-29 Thread Jacob Bandes-Storch via swift-evolution
I would not recommend phrasing these proposals as "Why doesn't Swift
already support X?" when you are proposing a new feature.

Instead, I'd like to see much more fleshed out examples of what you'd
propose to change, and how it would help Swift developers. From the small
amount of information you've given here, I can't understand what you're
trying to do.

Jacob

On Tue, Dec 29, 2015 at 10:07 AM, Amir Michail via swift-evolution <
swift-evolution@swift.org> wrote:

> Source to source transformations are part of a developer’s job, don’t need
> a GUI, and can be done more easily and accurately by the Swift compiler.
> Moreover, the compiler could be made interactive taking in extra
> information from the developer as required during the "compile" (again
> without requiring a GUI).
>
> You could have special directives for source to source transformations
> such as:
>
> @extractMethodBegin
> … swift code ...
> @extractMethodEnd
>
> @indentBegin
> … swift code ...
> @indentEnd
>
> @commitCommentFragmentBegin
> … swift code ...
> @commitCommentFragmentEnd
>
> etc…
>
> Why encourage reinventing the wheel by pushing source to source
> transformations to tools of varying quality and completeness?
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Why aren't source to source transformations part of the Swift language standard?

2015-12-29 Thread Amir Michail via swift-evolution

> On Dec 29, 2015, at 2:34 PM, Jacob Bandes-Storch  wrote:
> 
> I would not recommend phrasing these proposals as "Why doesn't Swift already 
> support X?" when you are proposing a new feature.
> 
> Instead, I'd like to see much more fleshed out examples of what you'd propose 
> to change, and how it would help Swift developers. From the small amount of 
> information you've given here, I can't understand what you're trying to do.

Xcode is not open source and it is unlikely that Swift source to source 
transformations that will be part of Xcode in the future  (e.g., extract 
method) will be open source.

What I propose would be a way to embed source to source transformations into 
Swift using directives in the language. As the language is open source, so will 
be the transformations.

Note also that the compiler already has the information required for source to 
source transformations and so it makes sense to embed these transformations in 
the compiler itself.

> 
> Jacob
> 
> On Tue, Dec 29, 2015 at 10:07 AM, Amir Michail via swift-evolution 
> mailto:swift-evolution@swift.org>> wrote:
> Source to source transformations are part of a developer’s job, don’t need a 
> GUI, and can be done more easily and accurately by the Swift compiler. 
> Moreover, the compiler could be made interactive taking in extra information 
> from the developer as required during the "compile" (again without requiring 
> a GUI).
> 
> You could have special directives for source to source transformations such 
> as:
> 
> @extractMethodBegin
> … swift code ...
> @extractMethodEnd
> 
> @indentBegin
> … swift code ...
> @indentEnd
> 
> @commitCommentFragmentBegin
> … swift code ...
> @commitCommentFragmentEnd
> 
> etc…
> 
> Why encourage reinventing the wheel by pushing source to source 
> transformations to tools of varying quality and completeness?
> ___
> swift-evolution mailing list
> swift-evolution@swift.org 
> https://lists.swift.org/mailman/listinfo/swift-evolution 
> 
> 

___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] rename dropFirst() and dropLast()

2015-12-29 Thread Kevin Ballard via swift-evolution
On Mon, Dec 28, 2015, at 04:23 PM, Kevin Ballard wrote:
> That said, `droppingFirst` sounds pretty weird to me. "drop" (and the related 
> verb "take" that we're not using) has precedent in multiple languages (Rust 
> and Haskell come to mind) to mean "return a new sequence that skips the first 
> N elements". And I'm not aware of any language that sets precedent for the 
> verb "drop" to mean "mutate the receiver".

Hmm, I just took a look, and while Rust does use "take", it actually doesn't 
use "drop" (but Haskell does). Instead it uses "skip", which seems like a good 
candidate if we're going to rename this. I'm tempted to say we should use 
"take" instead of "prefix" as well, because `seq.prefix(3)` isn't actually 
immediately obvious what it does (as the verb "prefix" usually means to add 
onto the front, not to take the front). And we can use "takeLast" for "suffix" 
(neither Rust nor Haskell appears to have an equivalent of takeLast; I believe 
Rust doesn't because none of its iterator adaptors use dynamically-allocated 
memory, and I think Haskell expects you to just do `reverse . take n . 
reverse`). Although I do notice Haskell has a function dropWhileEnd that drops 
the suffix, which suggests "takeEnd" and "dropEnd" here.

Which is to say, if we're going to rename these methods, my vote is:

prefix -> take
suffix -> takeEnd or takeLast
dropFirst -> skip
dropLast -> skipEnd or skipLast

-Kevin Ballard
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal draft] Generalized Naming for Any Function

2015-12-29 Thread Douglas Gregor via swift-evolution

>> On Dec 27, 2015, at 10:37 AM, Joe Groff  wrote:
>> 
>> 
>> On Dec 26, 2015, at 11:22 PM, Douglas Gregor via swift-evolution 
>>  wrote:
>> 
>> Hi all,
>> 
>> Here’s a proposal draft to allow one to name any function in Swift. In 
>> effect, it’s continuing the discussion of retrieving getters and setters as 
>> functions started by Michael Henson here:
>> 
>>  
>> https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151207/002168.html
>> 
>> the proposal follows, and is available here as well:
>> 
>>  
>> https://github.com/DougGregor/swift-evolution/blob/generalized-naming/proposals/-generalized-naming.md
>> 
>> Comments appreciated!
>> 
>> Generalized Naming for Any Function
>> 
[snip]
> 
>> Getters and setters can be written using dotted syntax within the back-ticks:
>> 
>> let specificTitle = button.`currentTitle.get` // has type () -> String?
>> let otherTitle = UIButton.`currentTitle.get`  // has type (UIButton) -> () 
>> -> String?
>> let setTintColor = button.`tintColor.set` // has type (UIColor!) -> ()
>> The same syntax works with subscript getters and setters as well, using the 
>> full name of the subscript:
>> 
>> extension Matrix {
>>   subscript (row row: Int) -> [Double] {
>> get { ... }
>> set { ... }
>>   }
>> }
>> 
>> let getRow = someMatrix.`subscript(row:).get` // has type (Int) -> () -> 
>> [Double]
>> let setRow = someMatrix.`subscript(row:).set` // has type (Int) -> 
>> ([Double]) -> ()
> At least as far as pure Swift is concerned, for unapplied access, like 
> `UIButton.currentTitle`, I think it would be more consistent with the way 
> method references works for that to give you the getter (or lens) without 
> decoration. instance.instanceMethod has type Args -> Ret, and 
> Type.instanceMethod has type Self -> Args -> Ret; by analogy, since 
> instance.instanceProperty has type Ret or inout Ret, it's reasonable to 
> expect Type.instanceProperty to have type Self -> [inout] Ret.

Yes, that seems reasonable.

> Forming a getter or setter partially applied to an instance feels unmotivated 
> to me—{ button.currentTitle } or { button.currentTitle = $0 } already work, 
> and are arguably clearer than this syntax.

I’m not strongly motivated by it in and of itself; rather, I like the idea of 
being able to get at all of the functions (for completeness/consistency), 
partly because of the Objective-C selector issue.

> I acknowledge that this leaves forming selectors from setters out to dry, but 
> I feel like that's something that could be incorporated into a "lens" design 
> along with typed selectors. As a rough sketch, we could say that the 
> representation of @convention(selector) T -> inout U is a pair of 
> getter/setter selectors,

I should weigh in over on a typed-selectors thread, but my personal view is 
that typed selectors are a well-designed feature that isn't worth doing: one 
would probably not use them outside of interoperability with Objective-C. To 
make that work, we'd need a Clang feature as well (to express the types), then 
all of the relevant Objective-C APIs would need to adopt it for us to see the 
benefits. On iOS, we are talking about a relatively small number of APIs 
(100-ish), and many of those have blocks/closure-based variants that are 
preferred. 

> and provide API on Selector to grab the individual selectors from that, maybe 
> Selector(getterFor: UIView.currentTitle)/(setterFor: UIView.currentTitle)

Sure. I suspect that retrieving the selector of a getter/setter will be fairly 
rare, so I'm fine with that operation being ugly. 

> . I don't think get/set is a good interface for working with Swift 
> properties, so I don't like the idea of building in language support to 
> codify it beyond what's needed for ObjC interaction.

That is an excellent point. I think you've convinced me to drop the 
getter/setter part of this: lenses are the right abstraction for working with 
properties, and we can handle ObjC getter/setter in some other way. 

>> Can we drop the back-ticks? It's very tempting to want to drop the 
>> back-ticks entirely, because something like
>> 
>> let fn = someView.insertSubview(_:at:)
>> can be correctly parsed as a reference to insertSubview(_:at:). However, it 
>> breaks down at the margins, e.g., with getter/setter references or 
>> no-argument functions:
>> 
>> extension Optional {
>>   func get() -> T { return self! }
>> }
>> 
>> let fn1 = button.currentTitle.get   // getter or Optional.get?
>> let fn2 = set.removeAllElements()   // call or reference?
> From what I remember, the bigger concern with allowing foo(bar:bas:) without 
> backticks is parser error recovery. The unambiguity with call syntax depends 
> on having the `:)` token pair at the end. The edit distance between 
> foo(bar:bas:) and a call foo(bar: bas) or work-in-progress call foo(bar: x, 
> bas: ) is pretty slight, and would be tricky to give good diagnostics for. If 
> we felt confident we could give good diagnostics, I'd

Re: [swift-evolution] [Proposal draft] Generalized Naming for Any Function

2015-12-29 Thread Félix Cloutier via swift-evolution
Currently, they can be disambiguated using (self as ProtocolA).bar(), no?

Félix

> Le 29 déc. 2015 à 14:10:51, Erica Sadun via swift-evolution 
>  a écrit :
> 
> Talk about things you didn't know you needed until you see them. This is a 
> really nice way of disambiguating!
> 
> -- E
> 
>> On Dec 29, 2015, at 12:03 PM, Douglas Gregor via swift-evolution 
>> mailto:swift-evolution@swift.org>> wrote:
>> 
>> 
>> 
>> Sent from my iPhone
>> 
>> On Dec 29, 2015, at 10:17 AM, Joe Groff > > wrote:
>> 
>>> We also have a problem with disambiguating same-named members that come 
>>> from different extensions, whether via protocol extensions or independent 
>>> concrete extensions from different modules. Could we extend this scheme to 
>>> allow for disambiguating extension methods by protocol/module name?
>> 
>> That's a fantastic idea!
>> 
>>> 
>>> extension ProtocolA { func foo() }
>>> extension ProtocolB { func foo() }
>>> 
>>> public struct Foo: ProtocolA, ProtocolB {
>>>   func callBothFoos() {
>>> self.`ProtocolA.foo`()
>>> self.`ProtocolB.foo`()
>>>   }
>>> }
>>> 
>>> import A // extends Bar with bar()
>>> import B // also extends Bar with bar()
>>> 
>>> extension Bar {
>>>   func callBothBars() {
>>> self.`A.bar`()
>>> self.`B.bar`()
>>>   }
>>> }
>>> 
>>> -Joe
>>> 
 On Dec 26, 2015, at 11:22 PM, Douglas Gregor via swift-evolution 
 mailto:swift-evolution@swift.org>> wrote:
 
 Hi all,
 
 Here’s a proposal draft to allow one to name any function in Swift. In 
 effect, it’s continuing the discussion of retrieving getters and setters 
 as functions started by Michael Henson here:
 

 https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151207/002168.html
  
 
 
 the proposal follows, and is available here as well:
 

 https://github.com/DougGregor/swift-evolution/blob/generalized-naming/proposals/-generalized-naming.md
  
 
 
 Comments appreciated!
 
 Generalized Naming for Any Function
 
 Proposal: SE- 
 
 Author(s): Doug Gregor 
 Status: Awaiting Review
 Review manager: TBD
  
 Introduction
 
 Swift includes support for first-class functions, such that any function 
 (or method) can be placed into a value of function type. However, it is 
 not possible to specifically name every function that is part of a Swift 
 program---one cannot provide the argument labels when naming a function, 
 nor are property and subscript getters and setters referenceable. This 
 proposal introduces a general syntax that allows one to name anything that 
 is a function within Swift in an extensible manner.
 
 Swift-evolution thread: Michael Henson started a thread about the 
 getter/setter issue here 
 ,
  continued here 
 .
  See the Alternatives considered 
 
  section for commentary on that discussion.
 
  
 Motivation
 
 It's fairly common in Swift for multiple functions or methods to have the 
 same "base name", but be distinguished by parameter labels. For example, 
 UIView has three methods with the same base name insertSubview:
 
 extension UIView {
   func insertSubview(view: UIView, at index: Int)
   func insertSubview(view: UIView, aboveSubview siblingSubview: UIView)
   func insertSubview(view: UIView, belowSubview siblingSubview: UIView)
 }
 When calling these methods, the argument labels distinguish the different 
 methods, e.g.,
 
 someView.insertSubview(view, at: 3)
 someView.insertSubview(view, aboveSubview: otherView)
 someView.insertSubview(view, belowSubview: otherView)
 However, when referencing the function to create a function value, one 
 cannot provide the labels:
 
 let fn = someView.insertSubview // ambiguous: could be any of the three 
 methods
 In some cases, it is possible to use type annotations to disambiguate:
 
 let fn: (UIView, Int) = someView.insertSubview// ok: uses 
 insertSubview(_

Re: [swift-evolution] rename dropFirst() and dropLast()

2015-12-29 Thread Daniel Duan via swift-evolution
Hi Kevin,

“take" and “skip” are fine as free function names. As method names, they are a 
step back from following the API Guidelines (“non-mutating methods should read 
as noun phrases”).

- Daniel

> On Dec 29, 2015, at 11:40 AM, Kevin Ballard via swift-evolution 
>  wrote:
> 
> On Mon, Dec 28, 2015, at 04:23 PM, Kevin Ballard wrote:
>> That said, `droppingFirst` sounds pretty weird to me. "drop" (and the 
>> related verb "take" that we're not using) has precedent in multiple 
>> languages (Rust and Haskell come to mind) to mean "return a new sequence 
>> that skips the first N elements". And I'm not aware of any language that 
>> sets precedent for the verb "drop" to mean "mutate the receiver".
> 
> Hmm, I just took a look, and while Rust does use "take", it actually doesn't 
> use "drop" (but Haskell does). Instead it uses "skip", which seems like a 
> good candidate if we're going to rename this. I'm tempted to say we should 
> use "take" instead of "prefix" as well, because `seq.prefix(3)` isn't 
> actually immediately obvious what it does (as the verb "prefix" usually means 
> to add onto the front, not to take the front). And we can use "takeLast" for 
> "suffix" (neither Rust nor Haskell appears to have an equivalent of takeLast; 
> I believe Rust doesn't because none of its iterator adaptors use 
> dynamically-allocated memory, and I think Haskell expects you to just do 
> `reverse . take n . reverse`). Although I do notice Haskell has a function 
> dropWhileEnd that drops the suffix, which suggests "takeEnd" and "dropEnd" 
> here.
> 
> Which is to say, if we're going to rename these methods, my vote is:
> 
> prefix -> take
> suffix -> takeEnd or takeLast
> dropFirst -> skip
> dropLast -> skipEnd or skipLast
> 
> -Kevin Ballard
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal draft] Generalized Naming for Any Function

2015-12-29 Thread Douglas Gregor via swift-evolution


Sent from my iPhone

> On Dec 29, 2015, at 11:03 AM, Douglas Gregor via swift-evolution 
>  wrote:
> 
> 
> 
> Sent from my iPhone
> 
>> On Dec 29, 2015, at 10:17 AM, Joe Groff  wrote:
>> 
>> We also have a problem with disambiguating same-named members that come from 
>> different extensions, whether via protocol extensions or independent 
>> concrete extensions from different modules. Could we extend this scheme to 
>> allow for disambiguating extension methods by protocol/module name?
> 
> That's a fantastic idea!

It does introduce some ambiguities at the margins. Given

  foo.`bar.get`()

Do we look for bar in the lexical scope or in the member scope of foo? Or both 
with yet another disambiguation mechanism?

I'm still traumatized by implementing the related C++ rules for

  foo.bar::get 

:)

This is the other thing that nudges me toward dropping getters/setters from the 
generalized naming proposal, because it leaves the use of '.' within backticks 
for your newly-proposed meaning. 
> 
>> 
>> extension ProtocolA { func foo() }
>> extension ProtocolB { func foo() }
>> 
>> public struct Foo: ProtocolA, ProtocolB {
>>   func callBothFoos() {
>> self.`ProtocolA.foo`()
>> self.`ProtocolB.foo`()
>>   }
>> }
>> 
>> import A // extends Bar with bar()
>> import B // also extends Bar with bar()
>> 
>> extension Bar {
>>   func callBothBars() {
>> self.`A.bar`()
>> self.`B.bar`()
>>   }
>> }
>> 
>> -Joe
>> 
>>> On Dec 26, 2015, at 11:22 PM, Douglas Gregor via swift-evolution 
>>>  wrote:
>>> 
>>> Hi all,
>>> 
>>> Here’s a proposal draft to allow one to name any function in Swift. In 
>>> effect, it’s continuing the discussion of retrieving getters and setters as 
>>> functions started by Michael Henson here:
>>> 
>>> 
>>> https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151207/002168.html
>>> 
>>> the proposal follows, and is available here as well:
>>> 
>>> 
>>> https://github.com/DougGregor/swift-evolution/blob/generalized-naming/proposals/-generalized-naming.md
>>> 
>>> Comments appreciated!
>>> 
>>> Generalized Naming for Any Function
>>> Proposal: SE-
>>> Author(s): Doug Gregor
>>> Status: Awaiting Review
>>> Review manager: TBD
>>> Introduction
>>> 
>>> Swift includes support for first-class functions, such that any function 
>>> (or method) can be placed into a value of function type. However, it is not 
>>> possible to specifically name every function that is part of a Swift 
>>> program---one cannot provide the argument labels when naming a function, 
>>> nor are property and subscript getters and setters referenceable. This 
>>> proposal introduces a general syntax that allows one to name anything that 
>>> is a function within Swift in an extensible manner.
>>> 
>>> Swift-evolution thread: Michael Henson started a thread about the 
>>> getter/setter issue here, continued here. See the Alternatives considered 
>>> section for commentary on that discussion.
>>> 
>>> Motivation
>>> 
>>> It's fairly common in Swift for multiple functions or methods to have the 
>>> same "base name", but be distinguished by parameter labels. For example, 
>>> UIView has three methods with the same base name insertSubview:
>>> 
>>> extension UIView {
>>>   func insertSubview(view: UIView, at index: Int)
>>>   func insertSubview(view: UIView, aboveSubview siblingSubview: UIView)
>>>   func insertSubview(view: UIView, belowSubview siblingSubview: UIView)
>>> }
>>> When calling these methods, the argument labels distinguish the different 
>>> methods, e.g.,
>>> 
>>> someView.insertSubview(view, at: 3)
>>> someView.insertSubview(view, aboveSubview: otherView)
>>> someView.insertSubview(view, belowSubview: otherView)
>>> However, when referencing the function to create a function value, one 
>>> cannot provide the labels:
>>> 
>>> let fn = someView.insertSubview // ambiguous: could be any of the three 
>>> methods
>>> In some cases, it is possible to use type annotations to disambiguate:
>>> 
>>> let fn: (UIView, Int) = someView.insertSubview// ok: uses 
>>> insertSubview(_:at:)
>>> let fn: (UIView, UIView) = someView.insertSubview // error: still ambiguous!
>>> To resolve the latter case, one must fall back to creating a closure:
>>> 
>>> let fn: (UIView, UIView) = { view, otherView in
>>>   button.insertSubview(view, otherView)
>>> }
>>> which is painfully tedious. A similar workaround is required to produce a 
>>> function value for a getter of a property, e.g.,
>>> 
>>> extension UIButton {
>>>   var currentTitle: String? { ... }
>>> }
>>> 
>>> var fn: () -> String? = { () in
>>>   return button.currentTitle
>>> }
>>> One additional bit of motivation: Swift should probably get some way to ask 
>>> for the Objective-C selector for a given method (rather than writing a 
>>> string literal). The argument to such an operation would likely be a 
>>> reference to a method, which would benefit from being able to name any 
>>> method, including getters and setters.
>>> 
>>> Prop

Re: [swift-evolution] [Proposal draft] Generalized Naming for Any Function

2015-12-29 Thread Douglas Gregor via swift-evolution


Sent from my iPhone

> On Dec 29, 2015, at 11:48 AM, Félix Cloutier  wrote:
> 
> Currently, they can be disambiguated using (self as ProtocolA).bar(), no?

Not if ProtocolA has self requirements or associated types. 
> 
> Félix
> 
>> Le 29 déc. 2015 à 14:10:51, Erica Sadun via swift-evolution 
>>  a écrit :
>> 
>> Talk about things you didn't know you needed until you see them. This is a 
>> really nice way of disambiguating!
>> 
>> -- E
>> 
>>> On Dec 29, 2015, at 12:03 PM, Douglas Gregor via swift-evolution 
>>>  wrote:
>>> 
>>> 
>>> 
>>> Sent from my iPhone
>>> 
 On Dec 29, 2015, at 10:17 AM, Joe Groff  wrote:
 
 We also have a problem with disambiguating same-named members that come 
 from different extensions, whether via protocol extensions or independent 
 concrete extensions from different modules. Could we extend this scheme to 
 allow for disambiguating extension methods by protocol/module name?
>>> 
>>> That's a fantastic idea!
>>> 
 
 extension ProtocolA { func foo() }
 extension ProtocolB { func foo() }
 
 public struct Foo: ProtocolA, ProtocolB {
   func callBothFoos() {
 self.`ProtocolA.foo`()
 self.`ProtocolB.foo`()
   }
 }
 
 import A // extends Bar with bar()
 import B // also extends Bar with bar()
 
 extension Bar {
   func callBothBars() {
 self.`A.bar`()
 self.`B.bar`()
   }
 }
 
 -Joe
 
> On Dec 26, 2015, at 11:22 PM, Douglas Gregor via swift-evolution 
>  wrote:
> 
> Hi all,
> 
> Here’s a proposal draft to allow one to name any function in Swift. In 
> effect, it’s continuing the discussion of retrieving getters and setters 
> as functions started by Michael Henson here:
> 
>   
> https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151207/002168.html
> 
> the proposal follows, and is available here as well:
> 
>   
> https://github.com/DougGregor/swift-evolution/blob/generalized-naming/proposals/-generalized-naming.md
> 
> Comments appreciated!
> 
> Generalized Naming for Any Function
> 
> Proposal: SE-
> Author(s): Doug Gregor
> Status: Awaiting Review
> Review manager: TBD
> Introduction
> 
> Swift includes support for first-class functions, such that any function 
> (or method) can be placed into a value of function type. However, it is 
> not possible to specifically name every function that is part of a Swift 
> program---one cannot provide the argument labels when naming a function, 
> nor are property and subscript getters and setters referenceable. This 
> proposal introduces a general syntax that allows one to name anything 
> that is a function within Swift in an extensible manner.
> 
> Swift-evolution thread: Michael Henson started a thread about the 
> getter/setter issue here, continued here. See the Alternatives considered 
> section for commentary on that discussion.
> 
> Motivation
> 
> It's fairly common in Swift for multiple functions or methods to have the 
> same "base name", but be distinguished by parameter labels. For example, 
> UIView has three methods with the same base name insertSubview:
> 
> extension UIView {
>   func insertSubview(view: UIView, at index: Int)
>   func insertSubview(view: UIView, aboveSubview siblingSubview: UIView)
>   func insertSubview(view: UIView, belowSubview siblingSubview: UIView)
> }
> When calling these methods, the argument labels distinguish the different 
> methods, e.g.,
> 
> someView.insertSubview(view, at: 3)
> someView.insertSubview(view, aboveSubview: otherView)
> someView.insertSubview(view, belowSubview: otherView)
> However, when referencing the function to create a function value, one 
> cannot provide the labels:
> 
> let fn = someView.insertSubview // ambiguous: could be any of the three 
> methods
> In some cases, it is possible to use type annotations to disambiguate:
> 
> let fn: (UIView, Int) = someView.insertSubview// ok: uses 
> insertSubview(_:at:)
> let fn: (UIView, UIView) = someView.insertSubview // error: still 
> ambiguous!
> To resolve the latter case, one must fall back to creating a closure:
> 
> let fn: (UIView, UIView) = { view, otherView in
>   button.insertSubview(view, otherView)
> }
> which is painfully tedious. A similar workaround is required to produce a 
> function value for a getter of a property, e.g.,
> 
> extension UIButton {
>   var currentTitle: String? { ... }
> }
> 
> var fn: () -> String? = { () in
>   return button.currentTitle
> }
> One additional bit of motivation: Swift should probably get some way to 
> ask for the Objective-C selector for a given method (rather than writing 
> a string

Re: [swift-evolution] [Proposal Draft] automatic protocol forwarding

2015-12-29 Thread Kevin Ballard via swift-evolution
I briefly skimmed your proposal, so I apologize if you already addressed
this, but it occurs to me that we could support automatic protocol
forwarding today on a per-protocol basis simply by declaring a separate
protocol that provides default implementations doing the forwarding.
Handling of Self return types can then be done by adding a required
initializer (or just not implementing that method, so the concrete type
is forced to deal with it even though everything else is forwarded).

For example, if I want to automatically forward SequenceType to a
member, I can do something like

protocol SequenceTypeForwarder : SequenceType {

typealias ForwardedSequenceType : SequenceType




var forwardedSequence : ForwardedSequenceType { get }

}




extension SequenceTypeForwarder {

func generate() -> ForwardedSequenceType.Generator {

return forwardedSequence.generate()

}




func underestimateCount() -> Int {

return forwardedSequence.underestimateCount()

}




func map(@noescape transform:
(ForwardedSequenceType.Generator.Element) throws -> T) rethrows -> [T] {

return try forwardedSequence.map(transform)

}




func filter(@noescape includeElement:
(ForwardedSequenceType.Generator.Element) throws -> Bool) rethrows ->
[ForwardedSequenceType.Generator.Element] {

return try forwardedSequence.filter(includeElement)

}




func forEach(@noescape body: (ForwardedSequenceType.Generator.Element)
throws -> Void) rethrows {

return try forwardedSequence.forEach(body)

}




func dropFirst(n: Int) -> ForwardedSequenceType.SubSequence {

return forwardedSequence.dropFirst(n)

}




func dropLast(n: Int) -> ForwardedSequenceType.SubSequence {

return forwardedSequence.dropLast(n)

}




func prefix(maxLength: Int) -> ForwardedSequenceType.SubSequence {

return forwardedSequence.prefix(maxLength)

}




func suffix(maxLength: Int) -> ForwardedSequenceType.SubSequence {

return forwardedSequence.suffix(maxLength)

}




func split(maxSplit: Int, allowEmptySlices: Bool, @noescape isSeparator:
(ForwardedSequenceType.Generator.Element) throws -> Bool) rethrows ->
[ForwardedSequenceType.SubSequence] {

return try forwardedSequence.split(maxSplit, allowEmptySlices:
allowEmptySlices, isSeparator: isSeparator)

}

}


With this protocol declared, I can then say something like

struct Foo {

var ary: [Int]

}




extension Foo : SequenceTypeForwarder {

var forwardedSequence: [Int] { return ary }

}


and my struct Foo now automatically implements SequenceType by
forwarding to its variable `ary`.

The downside to this is it needs to be manually declared for each
protocol. But I wager that most protocols actually aren't really
amenable to forwarding anyway.

-Kevin Ballard
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal draft] Generalized Naming for Any Function

2015-12-29 Thread Joe Groff via swift-evolution

> On Dec 29, 2015, at 12:03 PM, Douglas Gregor  wrote:
> 
> 
> 
> Sent from my iPhone
> 
> On Dec 29, 2015, at 11:03 AM, Douglas Gregor via swift-evolution 
> mailto:swift-evolution@swift.org>> wrote:
> 
>> 
>> 
>> Sent from my iPhone
>> 
>> On Dec 29, 2015, at 10:17 AM, Joe Groff > > wrote:
>> 
>>> We also have a problem with disambiguating same-named members that come 
>>> from different extensions, whether via protocol extensions or independent 
>>> concrete extensions from different modules. Could we extend this scheme to 
>>> allow for disambiguating extension methods by protocol/module name?
>> 
>> That's a fantastic idea!
> 
> It does introduce some ambiguities at the margins. Given
> 
>   foo.`bar.get`()
> 
> Do we look for bar in the lexical scope or in the member scope of foo? Or 
> both with yet another disambiguation mechanism?
> 
> I'm still traumatized by implementing the related C++ rules for
> 
>   foo.bar::get 
> 
> :)

Clearly we should just adopt Koenig lookup rules.

> This is the other thing that nudges me toward dropping getters/setters from 
> the generalized naming proposal, because it leaves the use of '.' within 
> backticks for your newly-proposed meaning. 

Well, even if we drop `.get`/`.set` from the proposal, there's still the 
potential ambiguity between module names and type or protocol names. As an 
example from the wild, there's an Either module which defines an Either type, 
and we have bugs on file saying you can't pick one or the other. It seems like 
we'll ultimately want some sort of absolute qualification scheme.

-Joe

>>> 
>>> extension ProtocolA { func foo() }
>>> extension ProtocolB { func foo() }
>>> 
>>> public struct Foo: ProtocolA, ProtocolB {
>>>   func callBothFoos() {
>>> self.`ProtocolA.foo`()
>>> self.`ProtocolB.foo`()
>>>   }
>>> }
>>> 
>>> import A // extends Bar with bar()
>>> import B // also extends Bar with bar()
>>> 
>>> extension Bar {
>>>   func callBothBars() {
>>> self.`A.bar`()
>>> self.`B.bar`()
>>>   }
>>> }
>>> 
>>> -Joe
>>> 
 On Dec 26, 2015, at 11:22 PM, Douglas Gregor via swift-evolution 
 mailto:swift-evolution@swift.org>> wrote:
 
 Hi all,
 
 Here’s a proposal draft to allow one to name any function in Swift. In 
 effect, it’s continuing the discussion of retrieving getters and setters 
 as functions started by Michael Henson here:
 

 https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151207/002168.html
  
 
 
 the proposal follows, and is available here as well:
 

 https://github.com/DougGregor/swift-evolution/blob/generalized-naming/proposals/-generalized-naming.md
  
 
 
 Comments appreciated!
 
 Generalized Naming for Any Function
 
 Proposal: SE- 
 
 Author(s): Doug Gregor 
 Status: Awaiting Review
 Review manager: TBD
  
 Introduction
 
 Swift includes support for first-class functions, such that any function 
 (or method) can be placed into a value of function type. However, it is 
 not possible to specifically name every function that is part of a Swift 
 program---one cannot provide the argument labels when naming a function, 
 nor are property and subscript getters and setters referenceable. This 
 proposal introduces a general syntax that allows one to name anything that 
 is a function within Swift in an extensible manner.
 
 Swift-evolution thread: Michael Henson started a thread about the 
 getter/setter issue here 
 ,
  continued here 
 .
  See the Alternatives considered 
 
  section for commentary on that discussion.
 
  
 Motivation
 
 It's fairly common in Swift for multiple functions or methods to have the 
 same "base name", but be distinguished by parameter labels. For example, 
 UIView has three methods with the same base name insertSubview:
 
 extension UIView {
   func insertSubview(view: UIView, at index: Int)
   func insertSubview(view: UIView, aboveSubview siblin

Re: [swift-evolution] Why aren't source to source transformations part of the Swift language standard?

2015-12-29 Thread John McCall via swift-evolution
> On Dec 29, 2015, at 11:40 AM, Amir Michail via swift-evolution 
>  wrote:
>> On Dec 29, 2015, at 2:34 PM, Jacob Bandes-Storch > > wrote:
>> 
>> I would not recommend phrasing these proposals as "Why doesn't Swift already 
>> support X?" when you are proposing a new feature.
>> 
>> Instead, I'd like to see much more fleshed out examples of what you'd 
>> propose to change, and how it would help Swift developers. From the small 
>> amount of information you've given here, I can't understand what you're 
>> trying to do.
> 
> Xcode is not open source and it is unlikely that Swift source to source 
> transformations that will be part of Xcode in the future  (e.g., extract 
> method) will be open source.
> 
> What I propose would be a way to embed source to source transformations into 
> Swift using directives in the language. As the language is open source, so 
> will be the transformations.
> 
> Note also that the compiler already has the information required for source 
> to source transformations and so it makes sense to embed these 
> transformations in the compiler itself.

“Source to source transformation” is a really broad term and could mean 
anything from a macro system to defining an entirely new language that compiles 
down to Swift source.  In this case, you seem to be asking for a refactoring 
engine that would be driven by source annotations, which sounds basically 
pointless except perhaps as a vehicle for extremely lazy research papers.

I think a refactoring engine would be very welcome in the Swift repository.  
However, the technical design of its interface is a detail that should be 
decided according to the needs of its implementers and users rather than by 
random people making comments on mailing lists.  If you are interested in 
contributing to that effort, that’s great, but you will need to write some 
code.  Also, that discussion should occur on the development lists rather than 
the evolution list, since it’s fundamentally a question of tools implementation 
rather than language design.

John.

> 
>> 
>> Jacob
>> 
>> On Tue, Dec 29, 2015 at 10:07 AM, Amir Michail via swift-evolution 
>> mailto:swift-evolution@swift.org>> wrote:
>> Source to source transformations are part of a developer’s job, don’t need a 
>> GUI, and can be done more easily and accurately by the Swift compiler. 
>> Moreover, the compiler could be made interactive taking in extra information 
>> from the developer as required during the "compile" (again without requiring 
>> a GUI).
>> 
>> You could have special directives for source to source transformations such 
>> as:
>> 
>> @extractMethodBegin
>> … swift code ...
>> @extractMethodEnd
>> 
>> @indentBegin
>> … swift code ...
>> @indentEnd
>> 
>> @commitCommentFragmentBegin
>> … swift code ...
>> @commitCommentFragmentEnd
>> 
>> etc…
>> 
>> Why encourage reinventing the wheel by pushing source to source 
>> transformations to tools of varying quality and completeness?
>> ___
>> swift-evolution mailing list
>> swift-evolution@swift.org 
>> https://lists.swift.org/mailman/listinfo/swift-evolution 
>> 
>> 
> 
> 
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] rename dropFirst() and dropLast()

2015-12-29 Thread Kevin Ballard via swift-evolution
I guess that's a good argument for keeping "prefix" and "suffix" instead of 
"take" and "takeEnd". But there is no good noun phrase to use for 
dropFirst/dropLast (Haskell's "init" and "tail" are nouns but they're very 
confusing and don't really make sense once you add in an integral argument 
anyway). The guidelines do say it's acceptable to use an imperative verb if 
there is no good noun phrase, so "skip" and "skipEnd" (or "skipLast", or maybe 
"skipSuffix" if we're keeping "suffix") are still reasonable.

Incidentally, it occurs to me that "removingFirst" is actually not an 
appropriate name here, because dropFirst is a method of SequenceType, and 
SequenceType does not have mutating methods. removeFirst is actually defined by 
RangeReplaceableCollectionType (and by Set, and also by CollectionType if 
SubSequence == Self).

-Kevin Ballard

On Tue, Dec 29, 2015, at 11:55 AM, Daniel Duan wrote:
> Hi Kevin,
> 
> “take" and “skip” are fine as free function names. As method names, they are 
> a step back from following the API Guidelines (“non-mutating methods should 
> read as noun phrases”).
> 
> - Daniel
> 
> > On Dec 29, 2015, at 11:40 AM, Kevin Ballard via swift-evolution 
> >  wrote:
> > 
> > On Mon, Dec 28, 2015, at 04:23 PM, Kevin Ballard wrote:
> >> That said, `droppingFirst` sounds pretty weird to me. "drop" (and the 
> >> related verb "take" that we're not using) has precedent in multiple 
> >> languages (Rust and Haskell come to mind) to mean "return a new sequence 
> >> that skips the first N elements". And I'm not aware of any language that 
> >> sets precedent for the verb "drop" to mean "mutate the receiver".
> > 
> > Hmm, I just took a look, and while Rust does use "take", it actually 
> > doesn't use "drop" (but Haskell does). Instead it uses "skip", which seems 
> > like a good candidate if we're going to rename this. I'm tempted to say we 
> > should use "take" instead of "prefix" as well, because `seq.prefix(3)` 
> > isn't actually immediately obvious what it does (as the verb "prefix" 
> > usually means to add onto the front, not to take the front). And we can use 
> > "takeLast" for "suffix" (neither Rust nor Haskell appears to have an 
> > equivalent of takeLast; I believe Rust doesn't because none of its iterator 
> > adaptors use dynamically-allocated memory, and I think Haskell expects you 
> > to just do `reverse . take n . reverse`). Although I do notice Haskell has 
> > a function dropWhileEnd that drops the suffix, which suggests "takeEnd" and 
> > "dropEnd" here.
> > 
> > Which is to say, if we're going to rename these methods, my vote is:
> > 
> > prefix -> take
> > suffix -> takeEnd or takeLast
> > dropFirst -> skip
> > dropLast -> skipEnd or skipLast
> > 
> > -Kevin Ballard
> > ___
> > swift-evolution mailing list
> > swift-evolution@swift.org
> > https://lists.swift.org/mailman/listinfo/swift-evolution
> 
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Idea] Expression to retrieve the Objective-C selector of a method

2015-12-29 Thread Douglas Gregor via swift-evolution


Sent from my iPhone

> On Dec 27, 2015, at 12:07 AM, Jacob Bandes-Storch  wrote:
> 
> This is a neat idea. Here are some of my thoughts after initial readthrough:
> 
> - For symmetry with Obj-C code, how about using "@selector", such as 
> @selector(UIView.`insertSubview(_:at:)`) ?

@ means at-tribute in Swift, whereas this is a specific expression. 

> - Or, why bother with a new expression? Could the compiler just do this 
> automatically when it encounters an @objc function being passed as a 
> Selector? So, you'd simply be able to say "let sel1: Selector = 
> UIView.`frame.get`"

It could, but I don't think it should: the operation is not common enough that 
making it implicit would reduce overall syntactic noise, and it would introduce 
ambiguities between selector- and closure-based APIs. 

> - Should the migrator offer to convert string-constant selectors to this form?

Yes, absolutely.

> - It might be worth considering this in the context of the "type-safe 
> selectors" idea that was floating around a while back.

Yes, I should have referenced that. Apologies!

> - Would it be valid to qualify a function with a subclass's name, when it's 
> really only defined on the superclass? That is, would 
> "objc_selector(MyView.`frame.get`)" work even if MyView doesn't override the 
> `frame` property?

Yes. MyView still has that property even if it doesn't override it. 
> 
> I could see this last one as a potential source of user confusion, because 
> naming a particular class wouldn't actually tell you which implementation 
> gets called when performing the selector (that's just the nature of the Obj-C 
> runtime).

To some extent, that's the nature of overriding. But objective-c allows one to 
use a selector with an unrelated class, which can certainly be confusing. I 
feel like that comes from the runtime itself, and isn't something we can avoid 
with any syntax we pick. 

> Jacob Bandes-Storch
> 
>> On Sat, Dec 26, 2015 at 11:48 PM, Douglas Gregor via swift-evolution 
>>  wrote:
>> Hi all,
>> 
>> Currently, producing an Objective-C selector in Swift is an error-prone 
>> operation. One effectively just writes a string literal and uses it in a 
>> context where an ObjectiveC.Selector is expected:
>> 
>> control.sendAction(“doSomething:”, to: target, forEvent: event)
>> 
>> There are many points of failure here:
>> 
>> 1) The compiler doesn’t syntax-check at all to make sure it’s a valid 
>> spelling for a selector
>> 2) The compiler doesn’t look for existing methods with this selector anywhere
>> 3) The mapping from a Swift method name to an Objective-C selector isn’t 
>> always immediately obvious (especially for initializers), and will be 
>> getting significantly more complicated with the renaming work for Swift 3 
>> (https://github.com/apple/swift-evolution/blob/master/proposals/0005-objective-c-name-translation.md).
>> 
>> I suggest that we add an expression ‘objc_selector(method-reference)` that 
>> produces the Objective-C selector for the named method, and produces an 
>> error if the method does not have an Objective-C entry point. For example:
>> 
>> control.sendAction(objc_selector(MyApplication.doSomething), to: 
>> target, forEvent: event)
>> 
>> “doSomething” is a method of MyApplication, which might even have a 
>> completely-unrelated name in Objective-C:
>> 
>> extension MyApplication {
>> @objc(jumpUpAndDown:)
>> func doSomething(sender: AnyObject?) { … }
>> }
>> 
>> By naming the Swift method and having objc_selector do the work to form the 
>> Objective-C selector, we free the programming from having to do the naming 
>> translation manually and get static checking that the method exists and is 
>> exposed to Objective-C.
>> 
>> This proposal composes with my “Generalized Naming for Any Function” 
>> proposal, which lets us name methods fully, including getters/setters:
>> 
>> let sel1: Selector = objc_selector(UIView.`insertSubview(_:at:)`) // 
>> produces the Selector “insertSubview:atIndex:"
>> let sel2: Selector = objc_selector(UIView.`frame.get`) // produces 
>> the Selector “frame"
>> 
>> I don’t like the `objc_selector` syntax at all, but otherwise I think this 
>> functionality is straightforward.
>> 
>> - Doug
>> 
>> ___
>> swift-evolution mailing list
>> swift-evolution@swift.org
>> https://lists.swift.org/mailman/listinfo/swift-evolution
> 
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal draft] Generalized Naming for Any Function

2015-12-29 Thread Brent Royal-Gordon via swift-evolution
> Currently, they can be disambiguated using (self as ProtocolA).bar(), no?

I think this method is more about, for instance:

extension NSString {
func drawAtPoint(point: CGPoint, withAttributes attributes: 
[String: AnyObject]?) {
doSomeOtherThing()
myString.`UIKit.drawAtPoint`(point, withAttributes: 
attrs)
}
}

You use it to access a method by the module it comes from, not the protocol it 
comes from.

-- 
Brent Royal-Gordon
Architechies

___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] rename dropFirst() and dropLast()

2015-12-29 Thread Brent Royal-Gordon via swift-evolution
> I guess that's a good argument for keeping "prefix" and "suffix" instead of 
> "take" and "takeEnd". But there is no good noun phrase to use for 
> dropFirst/dropLast (Haskell's "init" and "tail" are nouns but they're very 
> confusing and don't really make sense once you add in an integral argument 
> anyway). The guidelines do say it's acceptable to use an imperative verb if 
> there is no good noun phrase, so "skip" and "skipEnd" (or "skipLast", or 
> maybe "skipSuffix" if we're keeping "suffix") are still reasonable.

I'm thinking:

collection.onlyFirst(5)
collection.exceptFirst(5)
collection.onlyLast(5)
collection.exceptLast(5)

Perfectly parallel, don't sound like mutating operations, and very clear about 
which part you keep and which part you toss.

-- 
Brent Royal-Gordon
Architechies

___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal Draft] automatic protocol forwarding

2015-12-29 Thread Félix Cloutier via swift-evolution
As the resident you-can-already-do-this grumpy guy, I tend to agree that most 
protocols aren't easily amenable to forwarding, and this solution works too.

In general, I think that Swift already doesn't impose too much boilerplate, and 
I think that most features to reduce boilerplate would be better served by 
having a sane macro system in Swift. (This is probably not in scope for Swift 
3, though.)

Félix

> Le 29 déc. 2015 à 15:06:48, Kevin Ballard via swift-evolution 
>  a écrit :
> 
> I briefly skimmed your proposal, so I apologize if you already addressed 
> this, but it occurs to me that we could support automatic protocol forwarding 
> today on a per-protocol basis simply by declaring a separate protocol that 
> provides default implementations doing the forwarding. Handling of Self 
> return types can then be done by adding a required initializer (or just not 
> implementing that method, so the concrete type is forced to deal with it even 
> though everything else is forwarded).
>  
> For example, if I want to automatically forward SequenceType to a member, I 
> can do something like
>  
> protocol SequenceTypeForwarder : SequenceType {
> typealias ForwardedSequenceType : SequenceType
> 
> var forwardedSequence : ForwardedSequenceType { get }
> }
> 
> extension SequenceTypeForwarder {
> func generate() -> ForwardedSequenceType.Generator {
> return forwardedSequence.generate()
> }
> 
> func underestimateCount() -> Int {
> return forwardedSequence.underestimateCount()
> }
> 
> func map(@noescape transform: 
> (ForwardedSequenceType.Generator.Element) throws -> T) rethrows -> [T] {
> return try forwardedSequence.map(transform)
> }
> 
> func filter(@noescape includeElement: 
> (ForwardedSequenceType.Generator.Element) throws -> Bool) rethrows -> 
> [ForwardedSequenceType.Generator.Element] {
> return try forwardedSequence.filter(includeElement)
> }
> 
> func forEach(@noescape body: (ForwardedSequenceType.Generator.Element) 
> throws -> Void) rethrows {
> return try forwardedSequence.forEach(body)
> }
> 
> func dropFirst(n: Int) -> ForwardedSequenceType.SubSequence {
> return forwardedSequence.dropFirst(n)
> }
> 
> func dropLast(n: Int) -> ForwardedSequenceType.SubSequence {
> return forwardedSequence.dropLast(n)
> }
> 
> func prefix(maxLength: Int) -> ForwardedSequenceType.SubSequence {
> return forwardedSequence.prefix(maxLength)
> }
> 
> func suffix(maxLength: Int) -> ForwardedSequenceType.SubSequence {
> return forwardedSequence.suffix(maxLength)
> }
> 
> func split(maxSplit: Int, allowEmptySlices: Bool, @noescape isSeparator: 
> (ForwardedSequenceType.Generator.Element) throws -> Bool) rethrows -> 
> [ForwardedSequenceType.SubSequence] {
> return try forwardedSequence.split(maxSplit, allowEmptySlices: 
> allowEmptySlices, isSeparator: isSeparator)
> }
> }
>  
> With this protocol declared, I can then say something like
>  
> struct Foo {
> var ary: [Int]
> }
> 
> extension Foo : SequenceTypeForwarder {
> var forwardedSequence: [Int] { return ary }
> }
>  
> and my struct Foo now automatically implements SequenceType by forwarding to 
> its variable `ary`.
>  
> The downside to this is it needs to be manually declared for each protocol. 
> But I wager that most protocols actually aren't really amenable to forwarding 
> anyway.
>  
> -Kevin Ballard
> 
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal draft] Generalized Naming for Any Function

2015-12-29 Thread Félix Cloutier via swift-evolution
Right.

Félix

> Le 29 déc. 2015 à 15:04:11, Douglas Gregor  a écrit :
> 
> 
> 
> Sent from my iPhone
> 
> On Dec 29, 2015, at 11:48 AM, Félix Cloutier  > wrote:
> 
>> Currently, they can be disambiguated using (self as ProtocolA).bar(), no?
> 
> Not if ProtocolA has self requirements or associated types. 
>> 
>> Félix
>> 
>>> Le 29 déc. 2015 à 14:10:51, Erica Sadun via swift-evolution 
>>> mailto:swift-evolution@swift.org>> a écrit :
>>> 
>>> Talk about things you didn't know you needed until you see them. This is a 
>>> really nice way of disambiguating!
>>> 
>>> -- E
>>> 
 On Dec 29, 2015, at 12:03 PM, Douglas Gregor via swift-evolution 
 mailto:swift-evolution@swift.org>> wrote:
 
 
 
 Sent from my iPhone
 
 On Dec 29, 2015, at 10:17 AM, Joe Groff >>> > wrote:
 
> We also have a problem with disambiguating same-named members that come 
> from different extensions, whether via protocol extensions or independent 
> concrete extensions from different modules. Could we extend this scheme 
> to allow for disambiguating extension methods by protocol/module name?
 
 That's a fantastic idea!
 
> 
> extension ProtocolA { func foo() }
> extension ProtocolB { func foo() }
> 
> public struct Foo: ProtocolA, ProtocolB {
>   func callBothFoos() {
> self.`ProtocolA.foo`()
> self.`ProtocolB.foo`()
>   }
> }
> 
> import A // extends Bar with bar()
> import B // also extends Bar with bar()
> 
> extension Bar {
>   func callBothBars() {
> self.`A.bar`()
> self.`B.bar`()
>   }
> }
> 
> -Joe
> 
>> On Dec 26, 2015, at 11:22 PM, Douglas Gregor via swift-evolution 
>> mailto:swift-evolution@swift.org>> wrote:
>> 
>> Hi all,
>> 
>> Here’s a proposal draft to allow one to name any function in Swift. In 
>> effect, it’s continuing the discussion of retrieving getters and setters 
>> as functions started by Michael Henson here:
>> 
>>  
>> https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151207/002168.html
>>  
>> 
>> 
>> the proposal follows, and is available here as well:
>> 
>>  
>> https://github.com/DougGregor/swift-evolution/blob/generalized-naming/proposals/-generalized-naming.md
>>  
>> 
>> 
>> Comments appreciated!
>> 
>> Generalized Naming for Any Function
>> 
>> Proposal: SE- 
>> 
>> Author(s): Doug Gregor 
>> Status: Awaiting Review
>> Review manager: TBD
>>  
>> Introduction
>> 
>> Swift includes support for first-class functions, such that any function 
>> (or method) can be placed into a value of function type. However, it is 
>> not possible to specifically name every function that is part of a Swift 
>> program---one cannot provide the argument labels when naming a function, 
>> nor are property and subscript getters and setters referenceable. This 
>> proposal introduces a general syntax that allows one to name anything 
>> that is a function within Swift in an extensible manner.
>> 
>> Swift-evolution thread: Michael Henson started a thread about the 
>> getter/setter issue here 
>> ,
>>  continued here 
>> .
>>  See the Alternatives considered 
>> 
>>  section for commentary on that discussion.
>> 
>>  
>> Motivation
>> 
>> It's fairly common in Swift for multiple functions or methods to have 
>> the same "base name", but be distinguished by parameter labels. For 
>> example, UIView has three methods with the same base name insertSubview:
>> 
>> extension UIView {
>>   func insertSubview(view: UIView, at index: Int)
>>   func insertSubview(view: UIView, aboveSubview siblingSubview: UIView)
>>   func insertSubview(view: UIView, belowSubview siblingSubview: UIView)
>> }
>> When calling these methods, the argument labels distinguish the 
>> different methods, e.g.,
>> 
>> som

Re: [swift-evolution] Beef up Imports

2015-12-29 Thread Developer via swift-evolution
How is this done for things like the Darwin module?

~Robert Widmann

2015/12/28 20:19、T.J. Usiyan via swift-evolution  
のメッセージ:

> +1 in general. 
> 
> As an aside (In response to David), I have wanted the ability to import 
> 'submodules' from a framework since Swift 1.0. Being able to group related 
> functionality to import is a desirable feature, IMO
> TJ
> 
>> On Mon, Dec 28, 2015 at 7:01 PM, David Waite via swift-evolution 
>>  wrote:
>> 
>>> On Dec 28, 2015, at 5:07 PM, Chris Lattner via swift-evolution 
>>>  wrote:
>>> 
>>> +1 for this general direction, if not this specific syntax.  It would also 
>>> be great to have import integrate with SPM so you can import a package from 
>>> an SCM URL.  This would be pretty handy in particular for #! scripts.
>> This seems like it would strongly motivate toward a (possibly 
>> directory-scoped or system-scoped) package cache. Not saying thats a bad 
>> thing, just that it seems different than the executable packaging Swift has 
>> today with “Apps".
>> 
>> -DW
>> 
>> 
>> 
>> ___
>> swift-evolution mailing list
>> swift-evolution@swift.org
>> https://lists.swift.org/mailman/listinfo/swift-evolution
> 
> 
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] rename dropFirst() and dropLast()

2015-12-29 Thread James Campbell via swift-evolution
What about shift and pop?

They both could take an argument of a number of items to shift or pop ? 



Sent from my iPhone

On 29 Dec 2015, at 20:25, Brent Royal-Gordon via swift-evolution 
 wrote:

>> I guess that's a good argument for keeping "prefix" and "suffix" instead of 
>> "take" and "takeEnd". But there is no good noun phrase to use for 
>> dropFirst/dropLast (Haskell's "init" and "tail" are nouns but they're very 
>> confusing and don't really make sense once you add in an integral argument 
>> anyway). The guidelines do say it's acceptable to use an imperative verb if 
>> there is no good noun phrase, so "skip" and "skipEnd" (or "skipLast", or 
>> maybe "skipSuffix" if we're keeping "suffix") are still reasonable.
> 
> I'm thinking:
> 
>collection.onlyFirst(5)
>collection.exceptFirst(5)
>collection.onlyLast(5)
>collection.exceptLast(5)
> 
> Perfectly parallel, don't sound like mutating operations, and very clear 
> about which part you keep and which part you toss.
> 
> -- 
> Brent Royal-Gordon
> Architechies
> 
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] rename dropFirst() and dropLast()

2015-12-29 Thread Daniel Duan via swift-evolution
I made the same observation on Haskell in the original post :)

“removeFirst()” is also defined in CollectionType. So “dropFirst()” is 
removeFirst()’s – in the Guidelines’ term – "non-mutating counterpart" for all 
CollectionTypes. Therefore, “removingFirst()” would be the winner.

(My personal preference notwithstanding, that is).

> On Dec 29, 2015, at 12:15 PM, Kevin Ballard  wrote:
> 
> I guess that's a good argument for keeping "prefix" and "suffix" instead of 
> "take" and "takeEnd". But there is no good noun phrase to use for 
> dropFirst/dropLast (Haskell's "init" and "tail" are nouns but they're very 
> confusing and don't really make sense once you add in an integral argument 
> anyway). The guidelines do say it's acceptable to use an imperative verb if 
> there is no good noun phrase, so "skip" and "skipEnd" (or "skipLast", or 
> maybe "skipSuffix" if we're keeping "suffix") are still reasonable.
> 
> Incidentally, it occurs to me that "removingFirst" is actually not an 
> appropriate name here, because dropFirst is a method of SequenceType, and 
> SequenceType does not have mutating methods. removeFirst is actually defined 
> by RangeReplaceableCollectionType (and by Set, and also by CollectionType if 
> SubSequence == Self).
> 
> -Kevin Ballard
> 
> On Tue, Dec 29, 2015, at 11:55 AM, Daniel Duan wrote:
>> Hi Kevin,
>> 
>> “take" and “skip” are fine as free function names. As method names, they are 
>> a step back from following the API Guidelines (“non-mutating methods should 
>> read as noun phrases”).
>> 
>> - Daniel
>> 
>>> On Dec 29, 2015, at 11:40 AM, Kevin Ballard via swift-evolution 
>>>  wrote:
>>> 
>>> On Mon, Dec 28, 2015, at 04:23 PM, Kevin Ballard wrote:
 That said, `droppingFirst` sounds pretty weird to me. "drop" (and the 
 related verb "take" that we're not using) has precedent in multiple 
 languages (Rust and Haskell come to mind) to mean "return a new sequence 
 that skips the first N elements". And I'm not aware of any language that 
 sets precedent for the verb "drop" to mean "mutate the receiver".
>>> 
>>> Hmm, I just took a look, and while Rust does use "take", it actually 
>>> doesn't use "drop" (but Haskell does). Instead it uses "skip", which seems 
>>> like a good candidate if we're going to rename this. I'm tempted to say we 
>>> should use "take" instead of "prefix" as well, because `seq.prefix(3)` 
>>> isn't actually immediately obvious what it does (as the verb "prefix" 
>>> usually means to add onto the front, not to take the front). And we can use 
>>> "takeLast" for "suffix" (neither Rust nor Haskell appears to have an 
>>> equivalent of takeLast; I believe Rust doesn't because none of its iterator 
>>> adaptors use dynamically-allocated memory, and I think Haskell expects you 
>>> to just do `reverse . take n . reverse`). Although I do notice Haskell has 
>>> a function dropWhileEnd that drops the suffix, which suggests "takeEnd" and 
>>> "dropEnd" here.
>>> 
>>> Which is to say, if we're going to rename these methods, my vote is:
>>> 
>>> prefix -> take
>>> suffix -> takeEnd or takeLast
>>> dropFirst -> skip
>>> dropLast -> skipEnd or skipLast
>>> 
>>> -Kevin Ballard
>>> ___
>>> swift-evolution mailing list
>>> swift-evolution@swift.org
>>> https://lists.swift.org/mailman/listinfo/swift-evolution
>> 

___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] rename dropFirst() and dropLast()

2015-12-29 Thread Kevin Ballard via swift-evolution
Actually that's not true, CollectionType does not define dropFirst(). It merely 
provides a default implementation. dropFirst() is only actually defined in 
SequenceType, which does not have any mutating methods. Renaming it to 
"removingFirst()" would be against the guidelines for all sequences that are 
not also RangeReplaceableCollectionTypes.

-Kevin Ballard

On Tue, Dec 29, 2015, at 12:39 PM, Daniel Duan wrote:
> I made the same observation on Haskell in the original post :)
> 
> “removeFirst()” is also defined in CollectionType. So “dropFirst()” is 
> removeFirst()’s – in the Guidelines’ term – "non-mutating counterpart" for 
> all CollectionTypes. Therefore, “removingFirst()” would be the winner.
> 
> (My personal preference notwithstanding, that is).
> 
> > On Dec 29, 2015, at 12:15 PM, Kevin Ballard  wrote:
> > 
> > I guess that's a good argument for keeping "prefix" and "suffix" instead of 
> > "take" and "takeEnd". But there is no good noun phrase to use for 
> > dropFirst/dropLast (Haskell's "init" and "tail" are nouns but they're very 
> > confusing and don't really make sense once you add in an integral argument 
> > anyway). The guidelines do say it's acceptable to use an imperative verb if 
> > there is no good noun phrase, so "skip" and "skipEnd" (or "skipLast", or 
> > maybe "skipSuffix" if we're keeping "suffix") are still reasonable.
> > 
> > Incidentally, it occurs to me that "removingFirst" is actually not an 
> > appropriate name here, because dropFirst is a method of SequenceType, and 
> > SequenceType does not have mutating methods. removeFirst is actually 
> > defined by RangeReplaceableCollectionType (and by Set, and also by 
> > CollectionType if SubSequence == Self).
> > 
> > -Kevin Ballard
> > 
> > On Tue, Dec 29, 2015, at 11:55 AM, Daniel Duan wrote:
> >> Hi Kevin,
> >> 
> >> “take" and “skip” are fine as free function names. As method names, they 
> >> are a step back from following the API Guidelines (“non-mutating methods 
> >> should read as noun phrases”).
> >> 
> >> - Daniel
> >> 
> >>> On Dec 29, 2015, at 11:40 AM, Kevin Ballard via swift-evolution 
> >>>  wrote:
> >>> 
> >>> On Mon, Dec 28, 2015, at 04:23 PM, Kevin Ballard wrote:
>  That said, `droppingFirst` sounds pretty weird to me. "drop" (and the 
>  related verb "take" that we're not using) has precedent in multiple 
>  languages (Rust and Haskell come to mind) to mean "return a new sequence 
>  that skips the first N elements". And I'm not aware of any language that 
>  sets precedent for the verb "drop" to mean "mutate the receiver".
> >>> 
> >>> Hmm, I just took a look, and while Rust does use "take", it actually 
> >>> doesn't use "drop" (but Haskell does). Instead it uses "skip", which 
> >>> seems like a good candidate if we're going to rename this. I'm tempted to 
> >>> say we should use "take" instead of "prefix" as well, because 
> >>> `seq.prefix(3)` isn't actually immediately obvious what it does (as the 
> >>> verb "prefix" usually means to add onto the front, not to take the 
> >>> front). And we can use "takeLast" for "suffix" (neither Rust nor Haskell 
> >>> appears to have an equivalent of takeLast; I believe Rust doesn't because 
> >>> none of its iterator adaptors use dynamically-allocated memory, and I 
> >>> think Haskell expects you to just do `reverse . take n . reverse`). 
> >>> Although I do notice Haskell has a function dropWhileEnd that drops the 
> >>> suffix, which suggests "takeEnd" and "dropEnd" here.
> >>> 
> >>> Which is to say, if we're going to rename these methods, my vote is:
> >>> 
> >>> prefix -> take
> >>> suffix -> takeEnd or takeLast
> >>> dropFirst -> skip
> >>> dropLast -> skipEnd or skipLast
> >>> 
> >>> -Kevin Ballard
> >>> ___
> >>> swift-evolution mailing list
> >>> swift-evolution@swift.org
> >>> https://lists.swift.org/mailman/listinfo/swift-evolution
> >> 
> 
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] RFC: Proposed rewrite of Unmanaged

2015-12-29 Thread Janosch Hildebrand via swift-evolution

> On 19 Dec 2015, at 22:09, Dave Abrahams  wrote:
> 
> 
>> On Dec 18, 2015, at 6:18 PM, Janosch Hildebrand via swift-evolution 
>> mailto:swift-evolution@swift.org>> wrote:
>> ...
> 
> I don't see any point in having "manuallyRelease()" if we already have 
> "release()"; they'd do the same thing if you dropped the return value.

I like the proposed idea of having two separate types for handling unannotated 
CF APIs and MRC which would also nicely resolve this issue. 

Would a separate type for MRC also fall under this proposal or would that 
require a separate proposal?

And speaking of a separate type for MRC, how about `ManagedReference` as a 
name? Seems much better than `Unmanaged`, nicely contrasts with 
`UnsafeReference` and `ManuallyManagedReference` is a bit of a mouthful...

>> I don't think this use case even needs to be described in the documentation 
>> for `UnsafeReference` and it's fine if its use is very much discouraged.
>> 
>> Personally I prefer the proposed `manuallyRetain()`/`manuallyRelease()` over 
>> plain `retain()`/`release()` as it clearly separates the returning and more 
>> generally applicable `release()` from the MRC methods. `retain()` would 
>> probably also have to return the object which would interfere with the max 
>> safe usage pattern.
> 
> I don't understand your last sentence; care to clarify?

My main reason for preferring `manuallyRetain()`/`manuallyRelease()` over 
`retain()`/`release()` would be that the former would *not* return the object, 
thus more cleanly separating them from the current `release()` which returns 
the object to be used from now on, with the `UnsafeReference` to be discarded 
at that point.

I just think it might be more confusing to also use `release()` for MRC and 
also introducing `retain()` would only exacerbate the issue. For symmetry 
reasons `retain()` would likely also return the object. That would make it very 
similar to `release()` and `.object` which it really shouldn't be as it 
shouldn't ever be used for handling object from unannotated CF APIs.

I think having a third method/property with a very similar signature would 
likely confusion regarding the "Maximally Safe Usage" pattern you described.

But as mentioned above I would actually prefer having two separate types which 
would also make this a non-issue.


>> As Joe mentioned, `Unmanaged` has a use for manual ref counting beyond 
>> immediate transfer from un-annotated APIs. 
>> 
>> I have used it for performance reasons myself (~ twice) and while I think 
>> it's a pretty small use case there isn't really any alternative.
>> If it would help I can also describe my use-cases in more detail.
> 
> Yes please!

One place I used Unmanaged is in a small project where I experiment with binary 
heaps in Swift. I've put the project on Github 
--(https://github.com/Jnosh/SwiftBinaryHeapExperiments) but basically I'm using 
`Unmanaged` in two places here:

1) Testing the 'overhead' of (A)RC.
Basically comparing the performance of using ARC-managed objects in the heaps 
vs. using 'unmanaged' objects. In Swift 1.2 the difference was still ~2x but 
with Swift 2+ it's likely approaching the cost of the retain/release when 
entering and exiting the collection.

Now this could also be accomplished using `unowned(unsafe)` but `Unmanaged` has 
some minor advantages:
a) I can keep the objects alive without keeping them in a separate 
collection. Not a big issue here since I'm doing that anyway but I also find 
that `Unmanaged` makes it clearer that & how the objects are (partly) manually 
managed.
b) I had previously experimented with using `unowned(unsafe)` for this 
purpose but found that `Unmanaged` performed better. However, that was in a 
more complex example and in the Swift 1.2 era. A quick test indicates that in 
this case and with Swift 2.1 `unowned(unsafe)` and `Unmanaged` perform about 
equally.

2) A (object only) binary heap that uses `Unmanaged` internally
Not much practical use either in this case since the compiler seems to do quite 
well by itself but still a somewhat interesting exercise.
`Unmanaged` is pretty much required here to make CoW work by manually retaining 
the objects.


The other project was a simple 2D sprite engine (think a simplified version of 
SpriteKit) I experimented with about a year ago.
Textures and Shaders were abstracted as value types privately backed by 
reference types that managed the underlying OpenGL objects, i.e. destroy the 
OpenGL texture object on deinit, etc...

I found this to be quite nice to use but ARC overhead during batching & 
rendering amounted to something like 20-30% of CPU time IIRC. (This was under 
Swift 1.2 and with WMO). Using `Unmanaged` was one of the things I played 
around with to get around this and it worked very well.
The `Unmanaged` instances were created when draw commands are submitted to the 
renderer so they were only used inside the rendering pipeline.
I eventually switched to using the OpenGL n

Re: [swift-evolution] [Proposal draft] Generalized Naming for Any Function

2015-12-29 Thread John McCall via swift-evolution
> On Dec 28, 2015, at 1:14 PM, Joe Groff  wrote:
>> On Dec 28, 2015, at 1:09 PM, Brent Royal-Gordon  
>> wrote:
>> 
>>> and you could access the unapplied lens for an instance property using 
>>> `Type.property` syntax, analogous to how `Type.method` works. I feel like 
>>> if we did that, then it would obviate the need for explicit `property.get` 
>>> or `property.set` for most native Swift uses, though maybe not ObjC interop 
>>> uses.
>> 
>> I feel like if you don't have a way to fetch an unbound getter, you're 
>> missing the 90% case, which is constructs like:
>> 
>>  let textValues = textViews.map(.#text.get)
> 
> Agreed. I think there are a couple ways to approach that. We could resolve 
> unbound property references contextually, so that Type.property gives you the 
> getter in normal function context, or the lens in inout function context, 
> and/or either allow implicit upconversion from lens to getter function or 
> provide an explicit getter((inout T) -> inout U) -> T -> U adapter function.

So the contextual lookup rule would be:

If the expression
  .foo
or
  .foo(E…)
is known from context to yield a value of type T, then:
  if T is a nominal type, the expression is equivalent to T.foo(E…);
  if T is a function type (inout? U -> V), then the expression is equivalent to 
{ (x: inout? U) in x.foo(E…) };
  if T is a lens function type (inout? U -> inout V), then the argument 
expression (E…) shall not be present and the expression shall be equivalent to 
{ (x: inout? U) in &x.foo }, or whatever the “applied” lens syntax is;
otherwise the expression is ill-formed.

This would be an obstacle to allowing extension methods on a hypothetical 
Swift.Function type, but I think that’s an acceptable sacrifice.

John.
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal Draft] automatic protocol forwarding

2015-12-29 Thread Brent Royal-Gordon via swift-evolution
> I have completed a first draft of a proposal to introduce automatic protocol 
> forwarding.  I’m looking forward to feedback from everyone!

Some things I don't see discussed here:

* Does it have to be a protocol? Why not also allow the concrete type of the 
property you're forwarding to? Obviously you couldn't form a subtype 
relationship (unless you could...), but this might be useful to reduce 
boilerplate when you're proxying something.

* Why the method-based conversion syntax for return values, rather than 
something a little more like a property declaration?

var number: Int
forward IntegerType to number {
static return(newValue: Int) {
return NumberWrapper(newValue)
}
return(newValue: Int) {
return NumberWrapper(newValue)
}
}

* If you want to keep the method-based syntax, why use the `init(_:)` 
initializer instead of one specifically for forwarding, like 
`init(forwardedReturnValue:)`?

* If you want to keep the method-based syntax, why do all forwards, even to 
different members, share the same transformation method? Wouldn't it be better 
to have, for instance, `init(returnedNumber:)` and 
`transformedReturnedNumber(_:)`, so that forwards to other properties could use 
different logic?

* If you want to keep the method-based syntax, would it make sense to instead 
have an initializer for instance initializers too, and just have it take a 
second parameter with the instance?

init(forwardedReturnValue: Int) {...}
init(forwardedReturnValue: Int, from: NumberWrapper) {...}

* Does this mean that a `public forward` declaration would forward `internal` 
members through synthesized `public` interfaces, if the forwarder and forwardee 
happened to be in the same module?

> All synthesized members recieve access control modifiers matching the access 
> control modifier applied to the forward declaration.


* You don't explicitly mention this, but I assume mutating methods work and 
mutate `self`?

-- 
Brent Royal-Gordon
Architechies

___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] RFC: Proposed rewrite of Unmanaged

2015-12-29 Thread Janosch Hildebrand via swift-evolution
I like "transfer" but I think this would be mostly helpful to people familiar 
with manual ref. counting in Obj-C.
It's probably just as confusing to others and the visual similarity could be 
confusing as well (like with `Unmanaged`).

But I also wouldn't be opposed to these if they were selected...


> On 20 Dec 2015, at 06:56, Félix Cloutier via swift-evolution 
>  wrote:
> 
> There's still the "release" issue (std::unique_ptr::release versus -[NSObject 
> release]), but "transfer" seems like a good word to me. What about 
> "transferByRetaining" and "transferWithoutRetaining"?
> 
> Félix
> 
>> Le 20 déc. 2015 à 00:01:22, Nevin Brackett-Rozinsky via swift-evolution 
>> mailto:swift-evolution@swift.org>> a écrit :
>> 
>> Floating an idea here—not sure if it’s even in the right ballpark, and I’m 
>> certainly not tied to the specific wording, but what about something along 
>> the lines of:
>> 
>> .transferByReleasing()
>> .transferWithoutReleasing()  // or perhaps just .transfer()
>> 
>> Or the slightly-more-verbose:
>> 
>> .transferObjectByReleasingReference()
>> .transferObjectWithoutReleasingReference()// or .transferObject()
>> 
>> Nevin

- Janosch

___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal Draft] automatic protocol forwarding

2015-12-29 Thread Matthew Johnson via swift-evolution
Hi Kevin,

Thanks for taking time to look at the proposal.

The technique you show here is not bad, but it has several deficiencies IMO 
which are addressed by the solution in the proposal.

1. Forwarding should be an implementation detail, not exposed as it is with 
this method.
2. As such, the getter for the forwardee is visible.  The forwardee is an 
implementation detail that should not be visible in most cases.
3. There is no way to specify access control for the synthesized methods and if 
there were it would be coupled to the access control of the conformance.
4. You can't forward to a type that doesn't conform to the protocol.  This is 
particularly important for existential forwardees (at least until they conform 
to their protocol).
5. A type that can't conform to the protocol can't forward an implementation of 
the members of the protocol.  Specifically, non-final classes cannot 
automatically forward a group of methods to an implementer.
6. This solution does not lay the foundation for a newtype feature. It would be 
possible to have a specialized newtype feature, but why not build it on top of 
a more general forwarding feature?

You may be right that many protocols are not amenable to forwarding.  The 
motivation for this proposal is that it enables delegation-based designs to be 
implemented succinctly.  In that use case the protocols will be designed 
alongside concrete implementations and types that forward to them.  A secondary 
motivation for this proposal is to lay a foundation for a newtype feature.  In 
that case the protocols to be forwarded would be specifically designed to 
represent the portion of the interface of the wrapped type which should be 
visible to users of the newtype.

I hope these points might be enough to convince you that it is worth a closer 
look.

Matthew

> On Dec 29, 2015, at 2:06 PM, Kevin Ballard via swift-evolution 
>  wrote:
> 
> I briefly skimmed your proposal, so I apologize if you already addressed 
> this, but it occurs to me that we could support automatic protocol forwarding 
> today on a per-protocol basis simply by declaring a separate protocol that 
> provides default implementations doing the forwarding. Handling of Self 
> return types can then be done by adding a required initializer (or just not 
> implementing that method, so the concrete type is forced to deal with it even 
> though everything else is forwarded).
>  
> For example, if I want to automatically forward SequenceType to a member, I 
> can do something like
>  
> protocol SequenceTypeForwarder : SequenceType {
> typealias ForwardedSequenceType : SequenceType
> 
> var forwardedSequence : ForwardedSequenceType { get }
> }
> 
> extension SequenceTypeForwarder {
> func generate() -> ForwardedSequenceType.Generator {
> return forwardedSequence.generate()
> }
> 
> func underestimateCount() -> Int {
> return forwardedSequence.underestimateCount()
> }
> 
> func map(@noescape transform: 
> (ForwardedSequenceType.Generator.Element) throws -> T) rethrows -> [T] {
> return try forwardedSequence.map(transform)
> }
> 
> func filter(@noescape includeElement: 
> (ForwardedSequenceType.Generator.Element) throws -> Bool) rethrows -> 
> [ForwardedSequenceType.Generator.Element] {
> return try forwardedSequence.filter(includeElement)
> }
> 
> func forEach(@noescape body: (ForwardedSequenceType.Generator.Element) 
> throws -> Void) rethrows {
> return try forwardedSequence.forEach(body)
> }
> 
> func dropFirst(n: Int) -> ForwardedSequenceType.SubSequence {
> return forwardedSequence.dropFirst(n)
> }
> 
> func dropLast(n: Int) -> ForwardedSequenceType.SubSequence {
> return forwardedSequence.dropLast(n)
> }
> 
> func prefix(maxLength: Int) -> ForwardedSequenceType.SubSequence {
> return forwardedSequence.prefix(maxLength)
> }
> 
> func suffix(maxLength: Int) -> ForwardedSequenceType.SubSequence {
> return forwardedSequence.suffix(maxLength)
> }
> 
> func split(maxSplit: Int, allowEmptySlices: Bool, @noescape isSeparator: 
> (ForwardedSequenceType.Generator.Element) throws -> Bool) rethrows -> 
> [ForwardedSequenceType.SubSequence] {
> return try forwardedSequence.split(maxSplit, allowEmptySlices: 
> allowEmptySlices, isSeparator: isSeparator)
> }
> }
>  
> With this protocol declared, I can then say something like
>  
> struct Foo {
> var ary: [Int]
> }
> 
> extension Foo : SequenceTypeForwarder {
> var forwardedSequence: [Int] { return ary }
> }
>  
> and my struct Foo now automatically implements SequenceType by forwarding to 
> its variable `ary`.
>  
> The downside to this is it needs to be manually declared for each protocol. 
> But I wager that most protocols actually aren't really amenable to forwarding 
> anyway.
>  
> -Kevin Ballard
> 
> ___
> swift-evolution mailing list
> swif

Re: [swift-evolution] rename dropFirst() and dropLast()

2015-12-29 Thread Thorsten Seitz via swift-evolution
withoutFirst()
withoutLast()

-Thorsten

> Am 29.12.2015 um 21:43 schrieb Kevin Ballard via swift-evolution 
> :
> 
> Actually that's not true, CollectionType does not define dropFirst(). It 
> merely provides a default implementation. dropFirst() is only actually 
> defined in SequenceType, which does not have any mutating methods. Renaming 
> it to "removingFirst()" would be against the guidelines for all sequences 
> that are not also RangeReplaceableCollectionTypes.
> 
> -Kevin Ballard
> 
> On Tue, Dec 29, 2015, at 12:39 PM, Daniel Duan wrote:
>> I made the same observation on Haskell in the original post :)
>> 
>> “removeFirst()” is also defined in CollectionType. So “dropFirst()” is 
>> removeFirst()’s – in the Guidelines’ term – "non-mutating counterpart" for 
>> all CollectionTypes. Therefore, “removingFirst()” would be the winner.
>> 
>> (My personal preference notwithstanding, that is).
>> 
>>> On Dec 29, 2015, at 12:15 PM, Kevin Ballard  wrote:
>>> 
>>> I guess that's a good argument for keeping "prefix" and "suffix" instead of 
>>> "take" and "takeEnd". But there is no good noun phrase to use for 
>>> dropFirst/dropLast (Haskell's "init" and "tail" are nouns but they're very 
>>> confusing and don't really make sense once you add in an integral argument 
>>> anyway). The guidelines do say it's acceptable to use an imperative verb if 
>>> there is no good noun phrase, so "skip" and "skipEnd" (or "skipLast", or 
>>> maybe "skipSuffix" if we're keeping "suffix") are still reasonable.
>>> 
>>> Incidentally, it occurs to me that "removingFirst" is actually not an 
>>> appropriate name here, because dropFirst is a method of SequenceType, and 
>>> SequenceType does not have mutating methods. removeFirst is actually 
>>> defined by RangeReplaceableCollectionType (and by Set, and also by 
>>> CollectionType if SubSequence == Self).
>>> 
>>> -Kevin Ballard
>>> 
>>> On Tue, Dec 29, 2015, at 11:55 AM, Daniel Duan wrote:
 Hi Kevin,
 
 “take" and “skip” are fine as free function names. As method names, they 
 are a step back from following the API Guidelines (“non-mutating methods 
 should read as noun phrases”).
 
 - Daniel
 
> On Dec 29, 2015, at 11:40 AM, Kevin Ballard via swift-evolution 
>  wrote:
> 
> On Mon, Dec 28, 2015, at 04:23 PM, Kevin Ballard wrote:
>> That said, `droppingFirst` sounds pretty weird to me. "drop" (and the 
>> related verb "take" that we're not using) has precedent in multiple 
>> languages (Rust and Haskell come to mind) to mean "return a new sequence 
>> that skips the first N elements". And I'm not aware of any language that 
>> sets precedent for the verb "drop" to mean "mutate the receiver".
> 
> Hmm, I just took a look, and while Rust does use "take", it actually 
> doesn't use "drop" (but Haskell does). Instead it uses "skip", which 
> seems like a good candidate if we're going to rename this. I'm tempted to 
> say we should use "take" instead of "prefix" as well, because 
> `seq.prefix(3)` isn't actually immediately obvious what it does (as the 
> verb "prefix" usually means to add onto the front, not to take the 
> front). And we can use "takeLast" for "suffix" (neither Rust nor Haskell 
> appears to have an equivalent of takeLast; I believe Rust doesn't because 
> none of its iterator adaptors use dynamically-allocated memory, and I 
> think Haskell expects you to just do `reverse . take n . reverse`). 
> Although I do notice Haskell has a function dropWhileEnd that drops the 
> suffix, which suggests "takeEnd" and "dropEnd" here.
> 
> Which is to say, if we're going to rename these methods, my vote is:
> 
> prefix -> take
> suffix -> takeEnd or takeLast
> dropFirst -> skip
> dropLast -> skipEnd or skipLast
> 
> -Kevin Ballard
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
 
>> 
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] rename dropFirst() and dropLast()

2015-12-29 Thread Daniel Duan via swift-evolution
For concrete types that conform to CollectionType:

[2, 1, 3].removeFirst()// => 2
[2, 1, 3].removingFirst() // => [1, 3]

seems like what the “non-mutating counterpart” guideline is aiming for. As 
another example, the guideline includes “stripNewlines()” and 
“strippingNewlines()”.

For SequenceType conforming types that aren’t CollectionTypes, they would be 
stuck with “removingFirst()”, which, technically, is a noun phrase (again, not 
my personal favorite). I don’t this result is against anything in the 
guidelines.



> On Dec 29, 2015, at 12:43 PM, Kevin Ballard  wrote:
> 
> Actually that's not true, CollectionType does not define dropFirst(). It 
> merely provides a default implementation. dropFirst() is only actually 
> defined in SequenceType, which does not have any mutating methods. Renaming 
> it to "removingFirst()" would be against the guidelines for all sequences 
> that are not also RangeReplaceableCollectionTypes.
> 
> -Kevin Ballard
> 
> On Tue, Dec 29, 2015, at 12:39 PM, Daniel Duan wrote:
>> I made the same observation on Haskell in the original post :)
>> 
>> “removeFirst()” is also defined in CollectionType. So “dropFirst()” is 
>> removeFirst()’s – in the Guidelines’ term – "non-mutating counterpart" for 
>> all CollectionTypes. Therefore, “removingFirst()” would be the winner.
>> 
>> (My personal preference notwithstanding, that is).
>> 
>>> On Dec 29, 2015, at 12:15 PM, Kevin Ballard  wrote:
>>> 
>>> I guess that's a good argument for keeping "prefix" and "suffix" instead of 
>>> "take" and "takeEnd". But there is no good noun phrase to use for 
>>> dropFirst/dropLast (Haskell's "init" and "tail" are nouns but they're very 
>>> confusing and don't really make sense once you add in an integral argument 
>>> anyway). The guidelines do say it's acceptable to use an imperative verb if 
>>> there is no good noun phrase, so "skip" and "skipEnd" (or "skipLast", or 
>>> maybe "skipSuffix" if we're keeping "suffix") are still reasonable.
>>> 
>>> Incidentally, it occurs to me that "removingFirst" is actually not an 
>>> appropriate name here, because dropFirst is a method of SequenceType, and 
>>> SequenceType does not have mutating methods. removeFirst is actually 
>>> defined by RangeReplaceableCollectionType (and by Set, and also by 
>>> CollectionType if SubSequence == Self).
>>> 
>>> -Kevin Ballard
>>> 
>>> On Tue, Dec 29, 2015, at 11:55 AM, Daniel Duan wrote:
 Hi Kevin,
 
 “take" and “skip” are fine as free function names. As method names, they 
 are a step back from following the API Guidelines (“non-mutating methods 
 should read as noun phrases”).
 
 - Daniel
 
> On Dec 29, 2015, at 11:40 AM, Kevin Ballard via swift-evolution 
>  wrote:
> 
> On Mon, Dec 28, 2015, at 04:23 PM, Kevin Ballard wrote:
>> That said, `droppingFirst` sounds pretty weird to me. "drop" (and the 
>> related verb "take" that we're not using) has precedent in multiple 
>> languages (Rust and Haskell come to mind) to mean "return a new sequence 
>> that skips the first N elements". And I'm not aware of any language that 
>> sets precedent for the verb "drop" to mean "mutate the receiver".
> 
> Hmm, I just took a look, and while Rust does use "take", it actually 
> doesn't use "drop" (but Haskell does). Instead it uses "skip", which 
> seems like a good candidate if we're going to rename this. I'm tempted to 
> say we should use "take" instead of "prefix" as well, because 
> `seq.prefix(3)` isn't actually immediately obvious what it does (as the 
> verb "prefix" usually means to add onto the front, not to take the 
> front). And we can use "takeLast" for "suffix" (neither Rust nor Haskell 
> appears to have an equivalent of takeLast; I believe Rust doesn't because 
> none of its iterator adaptors use dynamically-allocated memory, and I 
> think Haskell expects you to just do `reverse . take n . reverse`). 
> Although I do notice Haskell has a function dropWhileEnd that drops the 
> suffix, which suggests "takeEnd" and "dropEnd" here.
> 
> Which is to say, if we're going to rename these methods, my vote is:
> 
> prefix -> take
> suffix -> takeEnd or takeLast
> dropFirst -> skip
> dropLast -> skipEnd or skipLast
> 
> -Kevin Ballard
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
 
>> 

___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal Draft] automatic protocol forwarding

2015-12-29 Thread Matthew Johnson via swift-evolution

> On Dec 29, 2015, at 3:08 PM, Brent Royal-Gordon  
> wrote:
> 
>> I have completed a first draft of a proposal to introduce automatic protocol 
>> forwarding.  I’m looking forward to feedback from everyone!
> 
> Some things I don't see discussed here:
> 
> * Does it have to be a protocol? Why not also allow the concrete type of the 
> property you're forwarding to? Obviously you couldn't form a subtype 
> relationship (unless you could...), but this might be useful to reduce 
> boilerplate when you're proxying something.

This is addressed in the alternatives considered section.  The short answer is 
that there the direct interface of the concrete type does not contain 
sufficient information about potential Self parameters to do this well.  This 
information does exist in the protocol declarations.  Allowing this information 
to be specified in concrete interfaces would add enough complexity to the 
language that I don’t think it is worthwhile.  Joe Groff and I discussed this 
briefly yesterday: 
https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151228/004660.html
 
.

What you *can* do is declare a protocol containing the generalized signatures 
(substituting Self where appropriate) of all of the members of your concrete 
interface that you wish to be available to forward.  That is a one-time 
protocol declaration that allows you to forward the concrete interface as many 
times as you wish.  It seems like a reasonable tradeoff.

> 
> * Why the method-based conversion syntax for return values, rather than 
> something a little more like a property declaration?
> 
>   var number: Int
>   forward IntegerType to number {
>   static return(newValue: Int) {
>   return NumberWrapper(newValue)
>   }
>   return(newValue: Int) {
>   return NumberWrapper(newValue)
>   }
>   }

This is actually a really good idea to consider!  I didn’t consider something 
like this mostly because I didn’t think of it.  I’m going to seriously consider 
adopting an approach along these lines.

One possible advantage of the approach I used is that the initializer may 
already exist for other reasons and you would not need to do any extra work.

A big advantage of this approach is that it would work even when you are 
forwarding different protocols to more than one member with the same type.

> 
> * If you want to keep the method-based syntax, why use the `init(_:)` 
> initializer instead of one specifically for forwarding, like 
> `init(forwardedReturnValue:)`?

That was a somewhat arbitrary decision I suppose.  I also considered having the 
compiler look for any initializer accepting the correct type regardless of 
label.

> 
> * If you want to keep the method-based syntax, why do all forwards, even to 
> different members, share the same transformation method? Wouldn't it be 
> better to have, for instance, `init(returnedNumber:)` and 
> `transformedReturnedNumber(_:)`, so that forwards to other properties could 
> use different logic?

That is a limitation of the approach I used and the proposal disallows you to 
do such forwarding because of the ambiguity.  I am glad you identified a 
solution to that!

> 
> * If you want to keep the method-based syntax, would it make sense to instead 
> have an initializer for instance initializers too, and just have it take a 
> second parameter with the instance?
> 
>   init(forwardedReturnValue: Int) {...}
>   init(forwardedReturnValue: Int, from: NumberWrapper) {…}

Part of the reason the instance method was used is because sometimes the right 
thing to do might be to mutate and then return self.  Using an instance method 
gives you the flexibility to do that if necessary.

> 
> * Does this mean that a `public forward` declaration would forward `internal` 
> members through synthesized `public` interfaces, if the forwarder and 
> forwardee happened to be in the same module?
> 
>> All synthesized members recieve access control modifiers matching the access 
>> control modifier applied to the forward declaration.

Yes, if the forwardee had internal visibility and the forwarder was public the 
forwarder could publicly forward the interface.  This is intentional behavior.  
The forwardee may well be an internal implementation detail while the methods 
of the protocol are part of the public interface of the forwarder.  It is 
possible to write code that does this manually today.

> * You don't explicitly mention this, but I assume mutating methods work and 
> mutate `self`?

Mutating methods are something I didn’t think about carefully yet.  Thanks for 
pointing that out!  But generally, yes a forwarding implementation of a 
mutating method would need to mutate the forwardee which is part of self, thus 
mutating self.

> 
> -- 
> Brent Royal-Gordon
> Architechies
> 

___

Re: [swift-evolution] [Idea] Expression to retrieve the Objective-C selector of a method

2015-12-29 Thread Joe Groff via swift-evolution

> On Dec 29, 2015, at 12:19 PM, Douglas Gregor via swift-evolution 
>  wrote:
> 
> 
> 
> Sent from my iPhone
> 
> On Dec 27, 2015, at 12:07 AM, Jacob Bandes-Storch  > wrote:
> 
>> This is a neat idea. Here are some of my thoughts after initial readthrough:
>> 
>> - For symmetry with Obj-C code, how about using "@selector", such as 
>> @selector(UIView.`insertSubview(_:at:)`) ?
> 
> @ means at-tribute in Swift, whereas this is a specific expression. 
> 
>> - Or, why bother with a new expression? Could the compiler just do this 
>> automatically when it encounters an @objc function being passed as a 
>> Selector? So, you'd simply be able to say "let sel1: Selector = 
>> UIView.`frame.get`"
> 
> It could, but I don't think it should: the operation is not common enough 
> that making it implicit would reduce overall syntactic noise, and it would 
> introduce ambiguities between selector- and closure-based APIs. 

Maybe we can make constructor-like "Selector(Class.method)" syntax work (and 
"Selector(getterFor:/setterFor: Class.property)" for property accessors) 
instead of introducing a new magic function name.

-Joe

>> - Should the migrator offer to convert string-constant selectors to this 
>> form?
> 
> Yes, absolutely.
> 
>> - It might be worth considering this in the context of the "type-safe 
>> selectors" idea that was floating around a while back.
> 
> Yes, I should have referenced that. Apologies!
> 
>> - Would it be valid to qualify a function with a subclass's name, when it's 
>> really only defined on the superclass? That is, would 
>> "objc_selector(MyView.`frame.get`)" work even if MyView doesn't override the 
>> `frame` property?
> 
> Yes. MyView still has that property even if it doesn't override it. 
>> 
>> I could see this last one as a potential source of user confusion, because 
>> naming a particular class wouldn't actually tell you which implementation 
>> gets called when performing the selector (that's just the nature of the 
>> Obj-C runtime).
> 
> To some extent, that's the nature of overriding. But objective-c allows one 
> to use a selector with an unrelated class, which can certainly be confusing. 
> I feel like that comes from the runtime itself, and isn't something we can 
> avoid with any syntax we pick. 
> 
>> Jacob Bandes-Storch
>> 
>> On Sat, Dec 26, 2015 at 11:48 PM, Douglas Gregor via swift-evolution 
>> mailto:swift-evolution@swift.org>> wrote:
>> Hi all,
>> 
>> Currently, producing an Objective-C selector in Swift is an error-prone 
>> operation. One effectively just writes a string literal and uses it in a 
>> context where an ObjectiveC.Selector is expected:
>> 
>> control.sendAction(“doSomething:”, to: target, forEvent: event)
>> 
>> There are many points of failure here:
>> 
>> 1) The compiler doesn’t syntax-check at all to make sure it’s a valid 
>> spelling for a selector
>> 2) The compiler doesn’t look for existing methods with this selector anywhere
>> 3) The mapping from a Swift method name to an Objective-C selector isn’t 
>> always immediately obvious (especially for initializers), and will be 
>> getting significantly more complicated with the renaming work for Swift 3 
>> (https://github.com/apple/swift-evolution/blob/master/proposals/0005-objective-c-name-translation.md
>>  
>> ).
>> 
>> I suggest that we add an expression ‘objc_selector(method-reference)` that 
>> produces the Objective-C selector for the named method, and produces an 
>> error if the method does not have an Objective-C entry point. For example:
>> 
>> control.sendAction(objc_selector(MyApplication.doSomething), to: 
>> target, forEvent: event)
>> 
>> “doSomething” is a method of MyApplication, which might even have a 
>> completely-unrelated name in Objective-C:
>> 
>> extension MyApplication {
>> @objc(jumpUpAndDown:)
>> func doSomething(sender: AnyObject?) { … }
>> }
>> 
>> By naming the Swift method and having objc_selector do the work to form the 
>> Objective-C selector, we free the programming from having to do the naming 
>> translation manually and get static checking that the method exists and is 
>> exposed to Objective-C.
>> 
>> This proposal composes with my “Generalized Naming for Any Function” 
>> proposal, which lets us name methods fully, including getters/setters:
>> 
>> let sel1: Selector = objc_selector(UIView.`insertSubview(_:at:)`) // 
>> produces the Selector “insertSubview:atIndex:"
>> let sel2: Selector = objc_selector(UIView.`frame.get`) // produces 
>> the Selector “frame"
>> 
>> I don’t like the `objc_selector` syntax at all, but otherwise I think this 
>> functionality is straightforward.
>> 
>> - Doug
>> 
>> ___
>> swift-evolution mailing list
>> swift-evolution@swift.org 

Re: [swift-evolution] Proposal: Implement a rotate algorithm, equivalent to std::rotate() in C++

2015-12-29 Thread Dmitri Gribenko via swift-evolution
On Tue, Dec 29, 2015 at 5:30 PM, Sergey Bolshedvorsky
 wrote:
> Hi Dmitri,
>
> Thank you for your feedback! I’ve updated a proposal based on your comments:
> https://github.com/apple/swift-evolution/pull/77
>
> What jumps at me immediately is that the APIs are using integers to specify
> positions in the collection.  I think they should be using collection's
> indices instead.
>
> Yes you are right, the APIs should use collection indexes.
>
> I'm unsure why we need `first` and `last` -- shouldn't the API operate on
> the whole collection?  We have slices to operate on subsequences.
>
> The C++ implementation allows to rotate all elements of collection or only
> some of them. A precondition of this function is that
> 0 <= first <= middle <= last < count

Right, but this question is relevant for every algorithm (sort,
partition, etc.).  That's why we have writeback through slices:

myArray[first.. Another point to consider is how the call site of these functions looks
> like:
>
>
>  I’ve added 2 API usage examples to PR:
>
> Example of rotating all elements of the collection:
>
> let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
> let rotated = numbers.rotateFrom(0, middle: 3, last: 8)
> // rotated contains [4, 5, 6, 7, 8, 9, 1, 2, 3]
>
> Example of rotating some elements of the collection:
>
> let numbers = [10, 12, 13, 11, 15, 14]
> let rotated = numbers.rotateFrom(1, middle: 3, last: 4)
> // rotated contains [10, 11, 12, 13, 15, 14]
>
>
> It is interesting that you are proposing that the new algorithms should
> produce lazy views.  I agree this is consistent with the rest of the
> library, but I'm worried about the performance implications.  Have you
> thought about this?  One point to keep in mind is that you can implement the
> `_copyToNativeArrayBuffer()` and `_initializeTo()` entry points in all new
> lazy collections, using the optimal eager algorithm.  This way, converting
> them to arrays will be fast.
>
> Thanks for pointing out the performance issue with lazy views. I will draft
> the implementation of algorithms for regular collections at first and then I
> will think how it can be reused with lazy views.
>
> Sergey
>
>
>
> On 29 Dec 2015, at 06:38, Dmitri Gribenko  wrote:
>
> On Mon, Dec 28, 2015 at 10:29 PM, Sergey Bolshedvorsky via swift-evolution
>  wrote:
>>
>> Hi all,
>>
>> I have created a PR with with a formal proposal for this feature:
>> https://github.com/apple/swift-evolution/pull/77
>>
>> What are your thoughts?
>
>
> Thank you for the proposal!
>
> What jumps at me immediately is that the APIs are using integers to specify
> positions in the collection.  I think they should be using collection's
> indices instead.
>
> I'm unsure why we need `first` and `last` -- shouldn't the API operate on
> the whole collection?  We have slices to operate on subsequences.
>
> It is interesting that you are proposing that the new algorithms should
> produce lazy views.  I agree this is consistent with the rest of the
> library, but I'm worried about the performance implications.  Have you
> thought about this?  One point to keep in mind is that you can implement the
> `_copyToNativeArrayBuffer()` and `_initializeTo()` entry points in all new
> lazy collections, using the optimal eager algorithm.  This way, converting
> them to arrays will be fast.
>
> Another point to consider is how the call site of these functions looks
> like:
>
> collection.rotate(10, middle: 20, last: 30)
>
> The first number hangs in the air, it is unclear what its meaning is.
>
> Dmitri
>
> --
> main(i,j){for(i=2;;i++){for(j=2;j (j){printf("%d\n",i);}}} /*Dmitri Gribenko */
>
>



-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Proposal: Add scan, takeWhile, dropWhile, and iterate to the stdlib

2015-12-29 Thread Thorsten Seitz via swift-evolution
+1

-Thorsten

> Am 29.12.2015 um 00:59 schrieb Kevin Ballard via swift-evolution 
> :
> 
> ## Introduction
> 
> Add a few more functional sequence utilities to the standard library.
> 
> ## Motivation
> 
> We have map, filter, and reduce, but we're missing a bunch of useful 
> utilities like scan, iterate, takeWhile, and dropWhile. Interestingly, the 
> stdlib includes an implementation of scan in the doc comment for 
> LazySequenceType, it just doesn't actually provide it as API.
> 
> ## Proposed solution
> 
> We extend SequenceType with 3 new methods scan, takeWhile, and dropWhile. We 
> also add a single global function iterate.
> 
> ## Detailed design
> 
> We add the following extension to SequenceType:
> 
> extension SequenceType {
>func scan(initial: T, @noescape combine: (T, Self.Generator.Element) 
> throws -> T) rethrows -> [T]
>func dropWhile(@noescape dropElement: (Self.Generator.Element) throws -> 
> Bool) rethrows -> [Self.Generator.Element]
>func takeWhile(@noescape takeElement: (Self.Generator.Element) throws -> 
> Bool) rethrows -> [Self.Generator.Element]
> }
> 
> These all take functions, so to follow convention they're @noescape and 
> return arrays. We also provide an extension of CollectionType that overrides 
> a couple of these methods:
> 
> extension CollectionType {
>func dropWhile(@noescape dropElement: (Self.Generator.Element) throws -> 
> Bool) rethrows -> Self.SubSequence
>func takeWhile(@noescape takeElement: (Self.Generator.Element) throws -> 
> Bool) rethrows -> Self.SubSequence
> }
> 
> We also provide lazy versions:
> 
> extension LazySequenceType {
>func scan(initial: T, combine: (T, Self.Generator.Element) -> T) -> 
> LazyScanSequence
>func dropWhile(dropElement: (Self.Generator.Element) -> Bool) -> 
> LazyDropWhileSequence
>func takeWhile(takeElement: (Self.Generator.Element) -> Bool) -> 
> LazyTakeWhileSequence
> }
> 
> extension LazyCollectionType {
>func dropWhile(dropElement: (Self.Generator.Element) -> Bool) -> 
> LazyDropWhileCollection
>func takeWhile(takeElement: (Self.Generator.Element) -> Bool) -> 
> LazyTakeWhileCollection
> }
> 
> No collection variant of scan is provided because that would require storing 
> the last value in the index itself, which would cause problems if the combine 
> function isn't pure.
> 
> LazyDropWhileCollection would behave similarly to LazyFilterCollection in 
> that it runs the predicate against the elements to drop when accessing 
> startIndex; unlike LazyFilterCollection, because there's nothing else to skip 
> after that point, the index itself can actually be Self.Elements.Index (just 
> like a slice). LazyTakeWhileCollection also runs the predicate against the 
> first element when accessing startIndex, but it does need a unique index type 
> (because endIndex has to be some sentinel value, as it doesn't know where the 
> end is until you reach that point; this index type would therefore only 
> conform to ForwardIndexType).
> 
> And finally, we provide a global function
> 
> func iterate(initial: T, _ f: T -> T) -> IterateSequence
> 
> This function is inherently lazy and yields an infinite list of nested 
> applications of the function, so iterate(x, f) yields a sequence like [x, 
> f(x), f(f(x)), ...].
> 
> -Kevin Ballard
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal Draft] automatic protocol forwarding

2015-12-29 Thread Joe Groff via swift-evolution

> On Dec 29, 2015, at 1:24 PM, Matthew Johnson via swift-evolution 
>  wrote:
> 
> Hi Kevin,
> 
> Thanks for taking time to look at the proposal.
> 
> The technique you show here is not bad, but it has several deficiencies IMO 
> which are addressed by the solution in the proposal.
> 
> 1. Forwarding should be an implementation detail, not exposed as it is with 
> this method.

This could theoretically be managed by access control on protocol conformances:

public struct Foo: internal SequenceTypeForwarder, public SequenceType { ... }

though that's even more boilerplatey, and makes it easy to accidentally expose 
more API than you intended to.

-Joe

> 2. As such, the getter for the forwardee is visible.  The forwardee is an 
> implementation detail that should not be visible in most cases.
> 3. There is no way to specify access control for the synthesized methods and 
> if there were it would be coupled to the access control of the conformance.
> 4. You can't forward to a type that doesn't conform to the protocol.  This is 
> particularly important for existential forwardees (at least until they 
> conform to their protocol).
> 5. A type that can't conform to the protocol can't forward an implementation 
> of the members of the protocol.  Specifically, non-final classes cannot 
> automatically forward a group of methods to an implementer.
> 6. This solution does not lay the foundation for a newtype feature. It would 
> be possible to have a specialized newtype feature, but why not build it on 
> top of a more general forwarding feature?
> 
> You may be right that many protocols are not amenable to forwarding.  The 
> motivation for this proposal is that it enables delegation-based designs to 
> be implemented succinctly.  In that use case the protocols will be designed 
> alongside concrete implementations and types that forward to them.  A 
> secondary motivation for this proposal is to lay a foundation for a newtype 
> feature.  In that case the protocols to be forwarded would be specifically 
> designed to represent the portion of the interface of the wrapped type which 
> should be visible to users of the newtype.
> 
> I hope these points might be enough to convince you that it is worth a closer 
> look.
> 
> Matthew
> 
>> On Dec 29, 2015, at 2:06 PM, Kevin Ballard via swift-evolution 
>> mailto:swift-evolution@swift.org>> wrote:
>> 
>> I briefly skimmed your proposal, so I apologize if you already addressed 
>> this, but it occurs to me that we could support automatic protocol 
>> forwarding today on a per-protocol basis simply by declaring a separate 
>> protocol that provides default implementations doing the forwarding. 
>> Handling of Self return types can then be done by adding a required 
>> initializer (or just not implementing that method, so the concrete type is 
>> forced to deal with it even though everything else is forwarded).
>>  
>> For example, if I want to automatically forward SequenceType to a member, I 
>> can do something like
>>  
>> protocol SequenceTypeForwarder : SequenceType {
>> typealias ForwardedSequenceType : SequenceType
>> 
>> var forwardedSequence : ForwardedSequenceType { get }
>> }
>> 
>> extension SequenceTypeForwarder {
>> func generate() -> ForwardedSequenceType.Generator {
>> return forwardedSequence.generate()
>> }
>> 
>> func underestimateCount() -> Int {
>> return forwardedSequence.underestimateCount()
>> }
>> 
>> func map(@noescape transform: 
>> (ForwardedSequenceType.Generator.Element) throws -> T) rethrows -> [T] {
>> return try forwardedSequence.map(transform)
>> }
>> 
>> func filter(@noescape includeElement: 
>> (ForwardedSequenceType.Generator.Element) throws -> Bool) rethrows -> 
>> [ForwardedSequenceType.Generator.Element] {
>> return try forwardedSequence.filter(includeElement)
>> }
>> 
>> func forEach(@noescape body: (ForwardedSequenceType.Generator.Element) 
>> throws -> Void) rethrows {
>> return try forwardedSequence.forEach(body)
>> }
>> 
>> func dropFirst(n: Int) -> ForwardedSequenceType.SubSequence {
>> return forwardedSequence.dropFirst(n)
>> }
>> 
>> func dropLast(n: Int) -> ForwardedSequenceType.SubSequence {
>> return forwardedSequence.dropLast(n)
>> }
>> 
>> func prefix(maxLength: Int) -> ForwardedSequenceType.SubSequence {
>> return forwardedSequence.prefix(maxLength)
>> }
>> 
>> func suffix(maxLength: Int) -> ForwardedSequenceType.SubSequence {
>> return forwardedSequence.suffix(maxLength)
>> }
>> 
>> func split(maxSplit: Int, allowEmptySlices: Bool, @noescape isSeparator: 
>> (ForwardedSequenceType.Generator.Element) throws -> Bool) rethrows -> 
>> [ForwardedSequenceType.SubSequence] {
>> return try forwardedSequence.split(maxSplit, allowEmptySlices: 
>> allowEmptySlices, isSeparator: isSeparator)
>> }
>> }
>>  
>> With this protocol declared, I can then say something

Re: [swift-evolution] [Idea] Expression to retrieve the Objective-C selector of a method

2015-12-29 Thread James Campbell via swift-evolution
What if you could just refer to it by pointing to a special property ?

button.addTarget( class.prototype.handlePress)

If it has parameters these could be specified like so

button.addTarget(class.prototype.handlePress(sender:))


Sent from my iPhone

> On 29 Dec 2015, at 21:46, Joe Groff via swift-evolution 
>  wrote:
> 
> 
>> On Dec 29, 2015, at 12:19 PM, Douglas Gregor via swift-evolution 
>>  wrote:
>> 
>> 
>> 
>> Sent from my iPhone
>> 
>>> On Dec 27, 2015, at 12:07 AM, Jacob Bandes-Storch  
>>> wrote:
>>> 
>>> This is a neat idea. Here are some of my thoughts after initial readthrough:
>>> 
>>> - For symmetry with Obj-C code, how about using "@selector", such as 
>>> @selector(UIView.`insertSubview(_:at:)`) ?
>> 
>> @ means at-tribute in Swift, whereas this is a specific expression. 
>> 
>>> - Or, why bother with a new expression? Could the compiler just do this 
>>> automatically when it encounters an @objc function being passed as a 
>>> Selector? So, you'd simply be able to say "let sel1: Selector = 
>>> UIView.`frame.get`"
>> 
>> It could, but I don't think it should: the operation is not common enough 
>> that making it implicit would reduce overall syntactic noise, and it would 
>> introduce ambiguities between selector- and closure-based APIs. 
> 
> Maybe we can make constructor-like "Selector(Class.method)" syntax work (and 
> "Selector(getterFor:/setterFor: Class.property)" for property accessors) 
> instead of introducing a new magic function name.
> 
> -Joe
> 
>>> - Should the migrator offer to convert string-constant selectors to this 
>>> form?
>> 
>> Yes, absolutely.
>> 
>>> - It might be worth considering this in the context of the "type-safe 
>>> selectors" idea that was floating around a while back.
>> 
>> Yes, I should have referenced that. Apologies!
>> 
>>> - Would it be valid to qualify a function with a subclass's name, when it's 
>>> really only defined on the superclass? That is, would 
>>> "objc_selector(MyView.`frame.get`)" work even if MyView doesn't override 
>>> the `frame` property?
>> 
>> Yes. MyView still has that property even if it doesn't override it. 
>>> 
>>> I could see this last one as a potential source of user confusion, because 
>>> naming a particular class wouldn't actually tell you which implementation 
>>> gets called when performing the selector (that's just the nature of the 
>>> Obj-C runtime).
>> 
>> To some extent, that's the nature of overriding. But objective-c allows one 
>> to use a selector with an unrelated class, which can certainly be confusing. 
>> I feel like that comes from the runtime itself, and isn't something we can 
>> avoid with any syntax we pick. 
>> 
>>> Jacob Bandes-Storch
>>> 
 On Sat, Dec 26, 2015 at 11:48 PM, Douglas Gregor via swift-evolution 
  wrote:
 Hi all,
 
 Currently, producing an Objective-C selector in Swift is an error-prone 
 operation. One effectively just writes a string literal and uses it in a 
 context where an ObjectiveC.Selector is expected:
 
 control.sendAction(“doSomething:”, to: target, forEvent: event)
 
 There are many points of failure here:
 
 1) The compiler doesn’t syntax-check at all to make sure it’s a valid 
 spelling for a selector
 2) The compiler doesn’t look for existing methods with this selector 
 anywhere
 3) The mapping from a Swift method name to an Objective-C selector isn’t 
 always immediately obvious (especially for initializers), and will be 
 getting significantly more complicated with the renaming work for Swift 3 
 (https://github.com/apple/swift-evolution/blob/master/proposals/0005-objective-c-name-translation.md).
 
 I suggest that we add an expression ‘objc_selector(method-reference)` that 
 produces the Objective-C selector for the named method, and produces an 
 error if the method does not have an Objective-C entry point. For example:
 
 control.sendAction(objc_selector(MyApplication.doSomething), to: 
 target, forEvent: event)
 
 “doSomething” is a method of MyApplication, which might even have a 
 completely-unrelated name in Objective-C:
 
 extension MyApplication {
 @objc(jumpUpAndDown:)
 func doSomething(sender: AnyObject?) { … }
 }
 
 By naming the Swift method and having objc_selector do the work to form 
 the Objective-C selector, we free the programming from having to do the 
 naming translation manually and get static checking that the method exists 
 and is exposed to Objective-C.
 
 This proposal composes with my “Generalized Naming for Any Function” 
 proposal, which lets us name methods fully, including getters/setters:
 
 let sel1: Selector = objc_selector(UIView.`insertSubview(_:at:)`) 
 // produces the Selector “insertSubview:atIndex:"
 let sel2: Selector = objc_selector(UIView.`frame.get`) /

Re: [swift-evolution] [Proposal Draft] automatic protocol forwarding

2015-12-29 Thread Joe Groff via swift-evolution

> On Dec 29, 2015, at 12:06 PM, Kevin Ballard via swift-evolution 
>  wrote:
> 
> The downside to this is it needs to be manually declared for each protocol. 
> But I wager that most protocols actually aren't really amenable to forwarding 
> anyway.

At least from a language-mechanics perspective, the only fundamental blocker I 
can think of that makes a protocol difficult to forward are nontrivial `Self` 
requirements, since you need a way to map from Foo to Foo 
anywhere the protocol requires Foo. There's quite a bit of that in the 
standard library thanks to the collection APIs, to be sure, but I wonder what 
the breakdown is in the wild for Self-inflicting protocols versus non  outside 
of the stdlib.

I like the idea of using Forwarder protocols with default implementations, 
since it's amenable to macro generation and doesn't require new language 
features, but like Matt noted, it's easy to do the wrong thing from an API 
exposure standpoint by accidentally publishing your type's FooableForwarder 
conformance when you only wanted to promise that your type was Fooable.

-Joe___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal Draft] automatic protocol forwarding

2015-12-29 Thread Matthew Johnson via swift-evolution


Sent from my iPad

> On Dec 29, 2015, at 4:11 PM, Joe Groff  wrote:
> 
> 
>> On Dec 29, 2015, at 1:24 PM, Matthew Johnson via swift-evolution 
>>  wrote:
>> 
>> Hi Kevin,
>> 
>> Thanks for taking time to look at the proposal.
>> 
>> The technique you show here is not bad, but it has several deficiencies IMO 
>> which are addressed by the solution in the proposal.
>> 
>> 1. Forwarding should be an implementation detail, not exposed as it is with 
>> this method.
> 
> This could theoretically be managed by access control on protocol 
> conformances:
> 
> public struct Foo: internal SequenceTypeForwarder, public SequenceType { ... }
> 
> though that's even more boilerplatey, and makes it easy to accidentally 
> expose more API than you intended to.

Yep.  I'd like to see access control on protocol conformances for other 
reasons.  I've always figured that would be accomplished by allowing access 
control on extensions that declare protocol conformance rather than directly in 
the conformance itself.  Both seem like reasonable approaches and aren't 
mutually exclusive.

I also brought up in point #3:

> There is no way to specify access control for the synthesized methods and if 
> there were it would be coupled to the access control of the conformance.


The coupling in this approach would still exist even with access control on 
conformances.  The synthesized methods would always have the same visibility as 
the conformance, which may not always be desired.

We've talked in other threads about protocol forwarding a couple of times.  Do 
you have any general reaction to the approach in this proposal?


> 
> -Joe
> 
>> 2. As such, the getter for the forwardee is visible.  The forwardee is an 
>> implementation detail that should not be visible in most cases.
>> 3. There is no way to specify access control for the synthesized methods and 
>> if there were it would be coupled to the access control of the conformance.
>> 4. You can't forward to a type that doesn't conform to the protocol.  This 
>> is particularly important for existential forwardees (at least until they 
>> conform to their protocol).
>> 5. A type that can't conform to the protocol can't forward an implementation 
>> of the members of the protocol.  Specifically, non-final classes cannot 
>> automatically forward a group of methods to an implementer.
>> 6. This solution does not lay the foundation for a newtype feature. It would 
>> be possible to have a specialized newtype feature, but why not build it on 
>> top of a more general forwarding feature?
>> 
>> You may be right that many protocols are not amenable to forwarding.  The 
>> motivation for this proposal is that it enables delegation-based designs to 
>> be implemented succinctly.  In that use case the protocols will be designed 
>> alongside concrete implementations and types that forward to them.  A 
>> secondary motivation for this proposal is to lay a foundation for a newtype 
>> feature.  In that case the protocols to be forwarded would be specifically 
>> designed to represent the portion of the interface of the wrapped type which 
>> should be visible to users of the newtype.
>> 
>> I hope these points might be enough to convince you that it is worth a 
>> closer look.
>> 
>> Matthew
>> 
>>> On Dec 29, 2015, at 2:06 PM, Kevin Ballard via swift-evolution 
>>>  wrote:
>>> 
>>> I briefly skimmed your proposal, so I apologize if you already addressed 
>>> this, but it occurs to me that we could support automatic protocol 
>>> forwarding today on a per-protocol basis simply by declaring a separate 
>>> protocol that provides default implementations doing the forwarding. 
>>> Handling of Self return types can then be done by adding a required 
>>> initializer (or just not implementing that method, so the concrete type is 
>>> forced to deal with it even though everything else is forwarded).
>>>  
>>> For example, if I want to automatically forward SequenceType to a member, I 
>>> can do something like
>>>  
>>> protocol SequenceTypeForwarder : SequenceType {
>>> typealias ForwardedSequenceType : SequenceType
>>> 
>>> var forwardedSequence : ForwardedSequenceType { get }
>>> }
>>> 
>>> extension SequenceTypeForwarder {
>>> func generate() -> ForwardedSequenceType.Generator {
>>> return forwardedSequence.generate()
>>> }
>>> 
>>> func underestimateCount() -> Int {
>>> return forwardedSequence.underestimateCount()
>>> }
>>> 
>>> func map(@noescape transform: 
>>> (ForwardedSequenceType.Generator.Element) throws -> T) rethrows -> [T] {
>>> return try forwardedSequence.map(transform)
>>> }
>>> 
>>> func filter(@noescape includeElement: 
>>> (ForwardedSequenceType.Generator.Element) throws -> Bool) rethrows -> 
>>> [ForwardedSequenceType.Generator.Element] {
>>> return try forwardedSequence.filter(includeElement)
>>> }
>>> 
>>> func forEach(@noescape body: (ForwardedSequenceType.Generator.Element) 
>>> throws -> Vo

Re: [swift-evolution] [Proposal Draft] automatic protocol forwarding

2015-12-29 Thread Kevin Ballard via swift-evolution
On Tue, Dec 29, 2015, at 01:24 PM, Matthew Johnson wrote:
> Hi Kevin,
>
> Thanks for taking time to look at the proposal.
>
> The technique you show here is not bad, but it has several
> deficiencies IMO which are addressed by the solution in the proposal.
>
> 1. Forwarding should be an implementation detail, not exposed as it is
>with this method.
> 2. As such, the getter for the forwardee is visible.  The forwardee is
>an implementation detail that should not be visible in most cases.

I was tempted to call it `_forwardedSequence` instead, but I chose not
to do that because the _prefix convention right now means "stdlib
things that we don't want to expose but have to do so because of
implementation details".

> 3. There is no way to specify access control for the synthesized
>methods and if there were it would be coupled to the access control
>of the conformance.

I'm not sure what you mean by this. Access control for these
methods should work identically to access control for the original
protocol. The forwarder protocol would simply be declared with the
same access control.

> 4. You can't forward to a type that doesn't conform to the protocol.
>This is particularly important for existential forwardees (at least
>until they conform to their protocol).

It seems weird to me that your forwarding proposal allows you to forward
to a member that doesn't conform to the protocol. I suppose it makes
some sense if you only forward some methods and implement the others
yourself, but I'm not convinced there's actually a good reason to
support this. What circumstances are you thinking of where you'd
actually find yourself forwarding to a member that doesn't conform to
the protocol (that isn't an existential)? The only case that really
comes to mind is when the member is of a generic type that can't conform
to the protocol (e.g. Array doesn't conform to Equatable), but the
solution there is to allow for conditional protocol conformance (which
we already know is something we want in the language).

Forwarding to existentials is a valid concern, but I'm not actually sure
why Swift doesn't make existential protocol values conform to the
protocol anyway. That limitation would make sense if you could create
existential protocol values from protocols with Self/associated types
where the existential simply omits the relevant members (because then it
obviously doesn't conform to the protocol), but  Swift doesn't actually
let you create existentials in that situation anyway.

> 5. A type that can't conform to the protocol can't forward an
>implementation of the members of the protocol.  Specifically, non-
>final classes cannot automatically forward a group of methods to an
>implementer.

It sounds like you're talking here about the ability to forward members
that aren't actually associated with a protocol, right? I don't see why
you can't just declare a protocol in that case to represent the members
that you want to be able to forward.

> 6. This solution does not lay the foundation for a newtype feature. It
>would be possible to have a specialized newtype feature, but why
>not build it on top of a more general forwarding feature?

Barring a detailed newtype proposal, it's hard to see how forwarding
would actually interact with it. Are you thinking that a newtype would
have some member that provides the underlying value (e.g. a `var
rawValue`)? Given such a member, a generalized forwarding mechanism
would then interact with it. But if e.g. newtype works by letting you
cast (with `as`) to the underlying type, then your generalized
forwarding mechanism can't actually work unless it has two different
modes (one of which uses a member and the other uses a cast), which
means you're specializing for newtype anyway.

Besides, when using a newtype mechanism like that, since the newtype has
the same in-memory representation as the original type, you don't
actually want to generate new methods at all for forwarding, instead you
just want to re-use the exact same methods as the original type
(otherwise you're just bloating your code with a bunch of stubs that do
nothing more than bitcast the value and call the original method).

-Kevin Ballard

> You may be right that many protocols are not amenable to forwarding.
> The motivation for this proposal is that it enables delegation-based
> designs to be implemented succinctly.  In that use case the protocols
> will be designed alongside concrete implementations and types that
> forward to them.  A secondary motivation for this proposal is to lay a
> foundation for a newtype feature.  In that case the protocols to be
> forwarded would be specifically designed to represent the portion of
> the interface of the wrapped type which should be visible to users of
> the newtype.
>
> I hope these points might be enough to convince you that it is worth a
> closer look.
>
> Matthew
>
>> On Dec 29, 2015, at 2:06 PM, Kevin Ballard via swift-evolution > evolu

[swift-evolution] [Idea] Add AssociativeCollectionType to represent Dictionary-type relationships (was: Add an (Index, Element) sequence to CollectionType)

2015-12-29 Thread David Waite via swift-evolution

> Anyway, it would not be correct to ".enumerate()" returns (Index, Element) 
> instead of (n, Element)?
> 
> I believe that the current behavior was thought when Slices had indices 
> starting with zero.
> 

The behavior of enumerate is easiest to explain when you give everything a name 
and lay them all out on the table: In particular, there is a difference between 
a Counter, an Index, a Key, a Value, and an Element.

Enumerate always works in terms of adding a counter, not an index. It was 
perhaps better served as a global method, since one cannot really improve its 
default implementation.

The rest are as follows:

╔╦═╦═══╦═╦╗
║ Type   ║ Index*  ║ Key   ║ Value   ║ Element**
  ║
╠╬═╬═══╬═╬╣
║ Array  ║ 0-based offset  ║ N/A   ║ N/A ║ Generic "T"  
  ║
╠╬═╬═══╬═╬╣
║ ArraySlice ║ non-zero offset ║ N/A   ║ N/A ║ Generic "T"  
  ║
╠╬═╬═══╬═╬╣
║ Dictionary ║ DictionaryIndex ║ Generic "Key" ║ Generic "Value" ║ Tuple (Key, 
Value) ║
╚╩═╩═══╩═╩╝

* Index is declared on CollectionType
** Element is declared on GeneratorType and referenced by SequenceType

That Array [T] does not behave like a Dictionary [Int:T] is possibly a sign 
that an AssociativeCollectionType is needed, something like:

protocol AssociativeCollectionType : CollectionType {
typealias Key
typealias Value
typealias Element = (Key, Value)
typealias KeySequenceType = AnySequence
typealias ValueSequenceType = AnySequence

var keys: KeySequenceType { get }
var values: ValueSequenceType { get }
subscript (key: Key) -> Value? { get set }
func indexForKey(key:Key) -> Index

mutating func removeValueForKey(key: Key) -> Value?
mutating func updateValue(value: Value, forKey key: Key) -> Value?
}

Dictionary would support such a protocol directly. Array and ArraySlice (or 
even every CollectionType) might have a mapping function (lets bike shed 
“associative()” for now) to return an implementation of the interface, mapping:

- AssociativeCollectionType.Index = old Index
- AssociativeCollectionType.Key = old Index
- AssociativeCollectionType.Value = old Element
- AssociativeCollectionType.Element = old (Index, Element)

So maybe:

for (index, element) in someArray.associative() { … }

would do what the original idea requested: provide a (Index, Element) sequence 
for CollectionTypes.

-DW

___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal Draft] automatic protocol forwarding

2015-12-29 Thread Kevin Ballard via swift-evolution
On Tue, Dec 29, 2015, at 02:11 PM, Joe Groff wrote:
>
>> On Dec 29, 2015, at 1:24 PM, Matthew Johnson via swift-evolution > evolut...@swift.org> wrote:
>>
>> Hi Kevin,
>>
>> Thanks for taking time to look at the proposal.
>>
>> The technique you show here is not bad, but it has several
>> deficiencies IMO which are addressed by the solution in the proposal.
>>
>> 1. Forwarding should be an implementation detail, not exposed as it
>>is with this method.
>
> This could theoretically be managed by access control on protocol
> conformances:
>
>> public struct Foo: internal SequenceTypeForwarder, public
>> SequenceType { ... }
>
> though that's even more boilerplatey, and makes it easy to
> accidentally expose more API than you intended to.

That's an interesting approach.

Another workaround for this today is to use an operator (similar to how
the stdlib uses ~> internally for a lot of stuff) coupled with a phantom
type. As an example (using ~> because why not):

// phantom type

struct _SequenceTypeForwarder {}




protocol SequenceTypeForwarder : SequenceType {

typealias ForwardedSequenceType : SequenceType




func ~>(this: Self, _: _SequenceTypeForwarder) -> ForwardedSequenceType

}


The need for the phantom type is a bit unfortunate (you can't just use
SequenceTypeForwarder.Protocol because it complains about the Self or
associated type requirements issue).

-Kevin Ballard
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] rename dropFirst() and dropLast()

2015-12-29 Thread Kevin Ballard via swift-evolution
On Tue, Dec 29, 2015, at 01:33 PM, Daniel Duan wrote:
> For concrete types that conform to CollectionType:
> 
> [2, 1, 3].removeFirst()// => 2
> [2, 1, 3].removingFirst() // => [1, 3]
> 
> seems like what the “non-mutating counterpart” guideline is aiming for. As 
> another example, the guideline includes “stripNewlines()” and 
> “strippingNewlines()”.
> 
> For SequenceType conforming types that aren’t CollectionTypes, they would be 
> stuck with “removingFirst()”, which, technically, is a noun phrase (again, 
> not my personal favorite). I don’t this result is against anything in the 
> guidelines.

It's technically not a noun phrase at all. I believe you're thinking of 
gerunds, where a verb with an -ing ending is used as a noun. But "removing" in 
"removingFirst()" is not being used as a noun; the method does not represent 
the act of removing, but instead it returns a new value constructed "by 
removing first". I believe this is called the Present Participle.

-Kevin Ballard
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] RFC: Proposed rewrite of Unmanaged

2015-12-29 Thread Joe Groff via swift-evolution

> On Dec 19, 2015, at 1:09 PM, Dave Abrahams via swift-evolution 
>  wrote:
> 
> Please see my comment here 
> 

I'm open to changing how we import void* from C. I think it's pretty important 
that UnsafeReference's conversion APIs match the C importer's behavior in any 
case.

-Joe___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal Draft] automatic protocol forwarding

2015-12-29 Thread Charles Srstka via swift-evolution
Strong +1 on this proposal. I use Objective-C’s forwarding mechanisms quite 
often in my custom view code, in order to separate the code managing the outer 
view, the layout of subviews within the view, and business logic into separate 
classes, all while presenting a single, monolithic interface to the user. The 
loss of this ability without writing tons of boilerplate is one of the things 
about Swift that makes me sad.

The one thing I’d change is upgrading the partial forwarding synthesis to the 
original proposal, as that’s a rather important feature IMO.

Charles

> On Dec 29, 2015, at 10:37 AM, Matthew Johnson via swift-evolution 
>  wrote:
> 
> I have completed a first draft of a proposal to introduce automatic protocol 
> forwarding.  I’m looking forward to feedback from everyone!
> Automatic protocol forwarding
> 
> Proposal: SE- 
> 
> Author(s): Matthew Johnson 
> Status: Review
> Review manager: TBD
> Introduction
> 
> Automatic protocol forwarding introduces the ability to use delegation 
> without the need write forwarding member implementations manually. 
> 
> A preliminary mailing list thread on this topic had the subject protocol 
> based invocation forwarding 
> 
> Motivation
> 
> Delegation is a robust, composition oriented design technique that keeps 
> interface and implementation inheritance separate. The primary drawback to 
> this technique is that it requires a lot of manual boilerplate to forward 
> implemenation to the implementing member. This proposal eliminates the need 
> to write such boilerplate manually, thus making delegation-based designs much 
> more convenient and attractive.
> 
> This proposal may also serve as the foundation for a future enhancement 
> allowing a very concise “newtype” declaration.
> 
> Proposed solution
> 
> I propose introducing a forward declaration be allowed within a type 
> declaration or type extension. The forward declaration will cause the 
> compiler to synthesize implementations of the members required by the 
> forwarded protocols. The synthesized implementations will simply forward the 
> method call to the specified member.
> 
> The basic declaration looks like this:
> 
> forward Protocol, OtherProtocol to memberIdentifier
> The first clause contains a list of protocols to forward. 
> 
> The second clause specifies the identifier of the property to which the 
> protocol members will be forwarded. Any visible property that implements the 
> members required by the protocol is eligible for forwarding. It does not 
> matter whether it is stored, computed, lazy, etc.
> 
> It is also possible to include an access control declaration modifier to 
> specify the visibility of the synthesized members.
> 
> Self parameters
> 
> When a protocol member includes a Self parameter forwarding implementations 
> must accept the forwarding type but supply an argument of the forwardee type 
> when making the forwarding call. The most straightforward way to do this is 
> to simply use the same property getter that is used when forwarding. This is 
> the proposed solution.
> 
> Self return types
> 
> When a protocol member includes a Self return type forwarding implementations 
> must return the forwarding type. However, the forwardee implmentation will 
> return a value of the forwardee type. This result must be used to produce a 
> value of the forwarding type in some way.
> 
> The solution in this proposal is based on an ad-hoc overloading convention. A 
> protocol-based solution would probably be desirable if it were possible, 
> however it is not. This proposal supports forwarding to more than one member, 
> possibly with different types. A protocol-based solution would require the 
> forwarding type to conform to the “Self return value conversion” protocol 
> once for each forwardee type.
> 
> Static members
> 
> When a forwardee value is returned from a static member an initializer will 
> be used to produce a final return value. The initializer must be visible at 
> the source location of the forward declaration and must look like this:
> 
> struct Forwarder {
> let forwardee: Forwardee
> forward P to forwardee
> init(_ forwardeeReturnValue: Forwardee) { //... }
> }
> Instance members
> 
> When a forwardee value is returned from an instance member an instance method 
> will be used to transform the return value into a value of the correct type. 
> An instance method is necessary in order to allow the forwarding type to 
> access the state of the instance upon which the method was called when 
> performing the transformation.
> 
> If the instance method is not implemented the initializer used for static 
> members will be used instead.
> 
> The transformation has the form:
> 
> struct Forwarder {
> let forwardee: Forw

Re: [swift-evolution] Proposal: Implement a rotate algorithm, equivalent to std::rotate() in C++

2015-12-29 Thread Dave Abrahams via swift-evolution

> On Dec 29, 2015, at 7:30 AM, Sergey Bolshedvorsky  
> wrote:
> 
> Hi Dmitri,
> 
> Thank you for your feedback! I’ve updated a proposal based on your comments: 
> https://github.com/apple/swift-evolution/pull/77 
> 
> 
>> What jumps at me immediately is that the APIs are using integers to specify 
>> positions in the collection.  I think they should be using collection's 
>> indices instead.
> Yes you are right, the APIs should use collection indexes. 
> 
>> I'm unsure why we need `first` and `last` -- shouldn't the API operate on 
>> the whole collection?  We have slices to operate on subsequences.
> 
> The C++ implementation allows to rotate all elements of collection or only 
> some of them. A precondition of this function is that
> 0 <= first <= middle <= last < count

This should be handled by slicing and rotating a slice. In-place slice mutation 
is not yet efficient, but we have an open radar asking for the necessary core 
language feature to make it so (non-pointer proxy addressors).

>> Another point to consider is how the call site of these functions looks like:
> 
>  I’ve added 2 API usage examples to PR:
> 
> Example of rotating all elements of the collection:
> 
> let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
> let rotated = numbers.rotateFrom(0, middle: 3, last: 8)
> // rotated contains [4, 5, 6, 7, 8, 9, 1, 2, 3]

There should be an in-place rotation algorithm as well, and for both varieties 
we should have a way of getting back the index of the old start element in the 
rotated collection.  I would start with the in-place algorithms are likely more 
of a challenge.

> Example of rotating some elements of the collection:
> 
> let numbers = [10, 12, 13, 11, 15, 14]
> let rotated = numbers.rotateFrom(1, middle: 3, last: 4)
> // rotated contains [10, 11, 12, 13, 15, 14]
> 
> 
>> It is interesting that you are proposing that the new algorithms should 
>> produce lazy views.  I agree this is consistent with the rest of the 
>> library, but I'm worried about the performance implications.  Have you 
>> thought about this?  One point to keep in mind is that you can implement the 
>> `_copyToNativeArrayBuffer()` and `_initializeTo()` entry points in all new 
>> lazy collections, using the optimal eager algorithm.  This way, converting 
>> them to arrays will be fast.
> Thanks for pointing out the performance issue with lazy views. I will draft 
> the implementation of algorithms for regular collections at first and then I 
> will think how it can be reused with lazy views.

Err, I don’t think Dmitri pointed anything out; he merely asked you to consider 
performance.  But I must admit that I don’t understand the concern.  Many of 
our eager algorithms for are implemented by copying lazy views to an array.

Personally, I would implement a rotate as something like:

extension CollectionType {
  func rotatedAt(midPoint: Index) -> /* Return type */{
let result = c.lazy.flatten([ c[midPoint.. 
> Sergey
> 
> 
> 
>> On 29 Dec 2015, at 06:38, Dmitri Gribenko > > wrote:
>> 
>> On Mon, Dec 28, 2015 at 10:29 PM, Sergey Bolshedvorsky via swift-evolution 
>> mailto:swift-evolution@swift.org>> wrote:
>> Hi all,
>> 
>> I have created a PR with with a formal proposal for this feature: 
>> https://github.com/apple/swift-evolution/pull/77 
>> 
>> 
>> What are your thoughts?
>> 
>> Thank you for the proposal!
>> 
>> What jumps at me immediately is that the APIs are using integers to specify 
>> positions in the collection.  I think they should be using collection's 
>> indices instead.
>> 
>> I'm unsure why we need `first` and `last` -- shouldn't the API operate on 
>> the whole collection?  We have slices to operate on subsequences.
>> 
>> It is interesting that you are proposing that the new algorithms should 
>> produce lazy views.  I agree this is consistent with the rest of the 
>> library, but I'm worried about the performance implications.  Have you 
>> thought about this?  One point to keep in mind is that you can implement the 
>> `_copyToNativeArrayBuffer()` and `_initializeTo()` entry points in all new 
>> lazy collections, using the optimal eager algorithm.  This way, converting 
>> them to arrays will be fast.
>> 
>> Another point to consider is how the call site of these functions looks like:
>> 
>> collection.rotate(10, middle: 20, last: 30)
>> 
>> The first number hangs in the air, it is unclear what its meaning is.
>> 
>> Dmitri
>> 
>> -- 
>> main(i,j){for(i=2;;i++){for(j=2;j> (j){printf("%d\n",i);}}} /*Dmitri Gribenko > >*/
> 

___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal Draft] automatic protocol forwarding

2015-12-29 Thread Matthew Johnson via swift-evolution

> On Dec 29, 2015, at 4:29 PM, Kevin Ballard  wrote:
> 
> On Tue, Dec 29, 2015, at 01:24 PM, Matthew Johnson wrote:
>> Hi Kevin,
>>  
>> Thanks for taking time to look at the proposal.
>>  
>> The technique you show here is not bad, but it has several deficiencies IMO 
>> which are addressed by the solution in the proposal.
>>  
>> 1. Forwarding should be an implementation detail, not exposed as it is with 
>> this method.
>> 2. As such, the getter for the forwardee is visible.  The forwardee is an 
>> implementation detail that should not be visible in most cases.
>  
> I was tempted to call it `_forwardedSequence` instead, but I chose not to do 
> that because the _prefix convention right now means "stdlib things that we 
> don't want to expose but have to do so because of implementation details”.

Sure, but naming conventions are not access control.

>  
>> 3. There is no way to specify access control for the synthesized methods and 
>> if there were it would be coupled to the access control of the conformance.
>  
> I'm not sure what you mean by this. Access control for these methods should 
> work identically to access control for the original protocol. The forwarder 
> protocol would simply be declared with the same access control.

There are 3 things at play here:

1. The protocol that is forwarded
2. The forwarding methods implementing the protocol requirements
3. Conformance to the protocol

When you write code manually it is possible to specify distinct access control 
for 1 and 2, and as Joe noted it would be nice to be able to specify access 
control for 3 as well.  If this becomes possible all 3 could have distinct 
access levels.  

For example, a public protocol, internal implementing methods, but private 
conformance.  Or public implementing methods, an internal protocol, and private 
conformance.  Or a public protocol, and internal implementing methods and 
conformance.  Or public implementing methods, but an internal protocol and 
internal conformance.  

Some of these combinations might be unusual, but there may be use cases for 
them.  Ideally a forwarding mechanism would allow granular control, just as is 
possible with manual forwarding implementations.

>  
>> 4. You can't forward to a type that doesn't conform to the protocol.  This 
>> is particularly important for existential forwardees (at least until they 
>> conform to their protocol).
>  
> It seems weird to me that your forwarding proposal allows you to forward to a 
> member that doesn't conform to the protocol. I suppose it makes some sense if 
> you only forward some methods and implement the others yourself, but I'm not 
> convinced there's actually a good reason to support this. What circumstances 
> are you thinking of where you'd actually find yourself forwarding to a member 
> that doesn't conform to the protocol (that isn't an existential)? The only 
> case that really comes to mind is when the member is of a generic type that 
> can't conform to the protocol (e.g. Array doesn't conform to Equatable), 
> but the solution there is to allow for conditional protocol conformance 
> (which we already know is something we want in the language).

The proposal requires the forwardee to be *conformable* but not necessarily 
conforming.  The difference is admittedly subtle, but there may be good 
reasons.  It may be that it isn’t desriable for the forwardee to actually 
conform for one reason or another, maybe because you don’t want it to be 
possible to cast values of the forwardee type to the existential type of the 
protocol.  

The reason the proposal doesn’t require actual conformance is simply because it 
isn’t necessary to synthesize the forwarding members and there are potential 
use cases that could take advantage of the additional flexibility.  And again, 
because actual conformance would not be required to write the forwarding 
methods manually.

Protocols are an essential part of the forwarding mechanism because they are 
the only place in the language to differentiate between Self and a parameter or 
return value that should be always be of a specific type.  However, actual 
conformance to the protocol by either the forwarder or the forwardee is not 
necessary to implement forwarding.  Rather than arbitrarily require that it 
seems best to allow users control over whether, how, and where actual 
conformance is declared by both the forwarder and the forwardee.

The proposal specifically does not support “partial forwarding”.  That was 
noted as a possible future enhancement.  If such an enhancement were ever 
brought forward I would not support dropping the requirement for the forwardee 
to be “theoretically conformable” to the protocol.  Partial forwarding would 
only exist to enable forwarders to “override” specific member implementations.

>  
> Forwarding to existentials is a valid concern, but I'm not actually sure why 
> Swift doesn't make existential protocol values conform to the protocol 
> anyway. That l

Re: [swift-evolution] [Proposal Draft] automatic protocol forwarding

2015-12-29 Thread Dave Abrahams via swift-evolution

> On Dec 29, 2015, at 8:37 AM, Matthew Johnson via swift-evolution 
>  wrote:
> 
> Motivation
> 
> Delegation is a robust, composition oriented design technique that keeps 
> interface and implementation inheritance separate. The primary drawback to 
> this technique is that it requires a lot of manual boilerplate to forward 
> implemenation to the implementing member. This proposal eliminates the need 
> to write such boilerplate manually, thus making delegation-based designs much 
> more convenient and attractive.
> 
> This proposal may also serve as the foundation for a future enhancement 
> allowing a very concise “newtype” declaration.
> 
> 


Thanks for proposing this, Matthew!

The biggest thing missing here IMO (which has been missing from most of the 
other proposals I’ve seen) are examples of real-world problems solved by this 
proposal.  I have no doubt some forwarding mechanism would be a huge benefit, 
but without clear examples, how do I know that this proposal actually addresses 
the need?  One approach might be to show how the Lazy Collections subsystem in 
the standard library can be rewritten more simply using this mechanism.

-Dave

___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] rename dropFirst() and dropLast()

2015-12-29 Thread Daniel Duan via swift-evolution
I suppose it’s appropriate to go into grammars since we are in a language 
mailing list :)

Present Participle is just an official name for “verb in present tense”, as in 
“I am *writing* an email”. Let’s put the example from API Guideline to test. I 
hope you agree that “someText.strippingNewlines()” as a non-mutating method 
name is grammatical *somehow*. So, does it read as

self is *stripping newlines*, here’s X.

…or does this make more sense…

*stripping newlines* from self gives X.

?

I tend to think the latter. There’s a fancy name for it as well: gerund phrase.


> On Dec 29, 2015, at 2:55 PM, Kevin Ballard  wrote:
> 
> On Tue, Dec 29, 2015, at 01:33 PM, Daniel Duan wrote:
>> For concrete types that conform to CollectionType:
>> 
>> [2, 1, 3].removeFirst()// => 2
>> [2, 1, 3].removingFirst() // => [1, 3]
>> 
>> seems like what the “non-mutating counterpart” guideline is aiming for. As 
>> another example, the guideline includes “stripNewlines()” and 
>> “strippingNewlines()”.
>> 
>> For SequenceType conforming types that aren’t CollectionTypes, they would be 
>> stuck with “removingFirst()”, which, technically, is a noun phrase (again, 
>> not my personal favorite). I don’t this result is against anything in the 
>> guidelines.
> 
> It's technically not a noun phrase at all. I believe you're thinking of 
> gerunds, where a verb with an -ing ending is used as a noun. But "removing" 
> in "removingFirst()" is not being used as a noun; the method does not 
> represent the act of removing, but instead it returns a new value constructed 
> "by removing first". I believe this is called the Present Participle.
> 
> -Kevin Ballard


___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Proposal: CollectionType.cycle property for an infinite sequence

2015-12-29 Thread plx via swift-evolution

> On Dec 29, 2015, at 1:17 PM, Kevin Ballard via swift-evolution 
>  wrote:
> 
> On Tue, Dec 29, 2015, at 08:14 AM, plx via swift-evolution wrote:
>> Personally I’d say this should be a -1 for standard-library inclusion.
>> 
>> Swift’s not really built to handle infinite sequences right now; until they 
>> are handed better by the standard library convenience methods for creating 
>> them shouldn’t be in the standard library.
> 
> As far as I can tell, the only way in which it's "not really built" to handle 
> this is that there are multiple constructs that attempt to eagerly consume an 
> entire sequence, and using these with an infinite sequence would end up 
> looping forever. But I don't consider that to be a particularly serious 
> problem. You could "fix" it by refactoring SequenceType into two protocols, 
> SequenceType (for possibly-infinite sequences) and FiniteSequenceType (for 
> known-finite sequences) and then going over the entire standard library and 
> updating various spots to use FiniteSequenceType, except this would be very 
> limiting (sequences that are not known if they're infinite to the compiler 
> could still be valid for various eager algorithms if the programmer knows it 
> will be finite in practice).

Indeed, on my wishlist I would like to see the standard protocols refactored to 
something more like this:

SequenceType // can be iterated
FiniteSequenceType : SequenceType, // of finite length
StableSequenceType : SequenceType, // can be re-iterated identically
CollectionType : StableSequenceType, FiniteSequenceType, (etc.) // otherwise as 
it is now

…but can understand the wish to not overly-complicate the basic protocol 
hierarchy (and also to avoid baking-in nice-to-have, but 
impossible-to-really-enforce semantic requirements; I’d trust the standard 
library to use them properly, but not typical 3rd party code, somewhat 
defeating the purpose).

Everything else is a difference of outlook; we agree on the facts and differ in 
interpretation.

I consider concrete types that adopt a protocol only to simply call 
`fatalError` for most of the protocol methods to be pathological — often 
useful, but still pathological — and thus far the standard library doesn’t 
contain any such pathological types (to my knowledge).

`cycle` is useful but not useful enough to be the standard library’s first 
“pathological” type, so it’s still a -1 as proposed.

This is nothing specific to `cycle` and my opinion here could change were the 
language or the standard library to evolve in various ways.
> 
>> You’d also want to call `fatalError` for at least `reduce`, `reverse`, 
>> `sort`, `split`(?), `flatMap`, `dropLast`, `suffix`, and `forEach`.
> 
> You can only do it for the ones defined in the protocol, not ones defined in 
> extensions. This means map, filter, forEach, and suffix.
> 
> split is actually perfectly implementable for a CycleSequence, although it 
> does need a custom implementation. split is bounded by at most Int.max 
> splits, which means it is guaranteed to terminate even for an infinite 
> sequence (although the final subsequence does need to be infinite[1]). Even 
> if there are no separators in the cycle, it can just return the cycle itself.
> 
> [1] Interestingly, the current implementation actually dumps the remainder 
> into an Array and returns that (wrapped in AnySequence), which is curious 
> because it would be perfectly legal for it to just wrap the generator up in 
> AnySequence and return that instead. I'm tempted to submit a PR to change 
> that now, as it just seems like unnecessary work to use an array.
> 
>> `startsWith` and `elementsEqual` and `lexicographicComparison` are all 
>> broken if you call them like e.g. `self.startsWith(self)`.
> 
> That's true, but what do you really expect when you're calling them with two 
> infinite sequences? It's not so much that they're broken as it is that you're 
> creating an infinite loop without any way to break out. And FWIW, 
> lexicographicalCompare is actually something you might want to explicitly 
> support on infinite sequences if you know your sequences aren't equal and 
> want to find out which one is less than the other.
> 
> There are plenty of ways to shoot yourself in the foot. I don't think 
> infinite sequences are really the big problem you're making them out to be.
> 
>> You can conceivably implement a non-crashing `contains`, `minElement` and 
>> `maxElement` on `CycleSequence` by calling through to the wrapped 
>> collection, but that’ll seemingly evaporate as soon as your `CycleSequence` 
>> winds up hidden inside an `AnySequence`.
> 
> You can't override those anyway in a generic context, because they're not 
> members of the protocol, they're just extensions. You could implement them 
> such that your implementation is called when working on the concrete 
> CycleSequence type, but I'm not sure if that's a great idea to do that when 
> the actual behavior differs from calling it generically on Seque

Re: [swift-evolution] [Proposal Draft] automatic protocol forwarding

2015-12-29 Thread Matthew Johnson via swift-evolution

> On Dec 29, 2015, at 5:32 PM, Dave Abrahams  wrote:
> 
> 
>> On Dec 29, 2015, at 8:37 AM, Matthew Johnson via swift-evolution 
>> mailto:swift-evolution@swift.org>> wrote:
>> 
>> Motivation
>> 
>> Delegation is a robust, composition oriented design technique that keeps 
>> interface and implementation inheritance separate. The primary drawback to 
>> this technique is that it requires a lot of manual boilerplate to forward 
>> implemenation to the implementing member. This proposal eliminates the need 
>> to write such boilerplate manually, thus making delegation-based designs 
>> much more convenient and attractive.
>> 
>> This proposal may also serve as the foundation for a future enhancement 
>> allowing a very concise “newtype” declaration.
>> 
>> 
> 
> 
> Thanks for proposing this, Matthew!
> 
> The biggest thing missing here IMO (which has been missing from most of the 
> other proposals I’ve seen) are examples of real-world problems solved by this 
> proposal.  I have no doubt some forwarding mechanism would be a huge benefit, 
> but without clear examples, how do I know that this proposal actually 
> addresses the need?  One approach might be to show how the Lazy Collections 
> subsystem in the standard library can be rewritten more simply using this 
> mechanism.
> 
> -Dave
> 

Thanks for the feedback Dave!  I agree that the motivation section is a bit 
light and will work on filling it out with more detail, including specific 
examples of how it could be used to address specific problems.  ___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal Draft] automatic protocol forwarding

2015-12-29 Thread Dave Abrahams via swift-evolution

> On Dec 29, 2015, at 12:06 PM, Kevin Ballard via swift-evolution 
>  wrote:
> 
> I briefly skimmed your proposal, so I apologize if you already addressed 
> this, but it occurs to me that we could support automatic protocol forwarding 
> today on a per-protocol basis simply by declaring a separate protocol that 
> provides default implementations doing the forwarding. Handling of Self 
> return types can then be done by adding a required initializer (or just not 
> implementing that method, so the concrete type is forced to deal with it even 
> though everything else is forwarded).
>  
> For example, if I want to automatically forward SequenceType to a member, I 
> can do something like
>  
> protocol SequenceTypeForwarder : SequenceType {
> typealias ForwardedSequenceType : SequenceType
> 
> var forwardedSequence : ForwardedSequenceType { get }
> }
> 
> extension SequenceTypeForwarder {
> func generate() -> ForwardedSequenceType.Generator {
> return forwardedSequence.generate()
> }
> 
> func underestimateCount() -> Int {
> return forwardedSequence.underestimateCount()
> }
> 
> func map(@noescape transform: 
> (ForwardedSequenceType.Generator.Element) throws -> T) rethrows -> [T] {
> return try forwardedSequence.map(transform)
> }
> 
> func filter(@noescape includeElement: 
> (ForwardedSequenceType.Generator.Element) throws -> Bool) rethrows -> 
> [ForwardedSequenceType.Generator.Element] {
> return try forwardedSequence.filter(includeElement)
> }
> 
> func forEach(@noescape body: (ForwardedSequenceType.Generator.Element) 
> throws -> Void) rethrows {
> return try forwardedSequence.forEach(body)
> }
> 
> func dropFirst(n: Int) -> ForwardedSequenceType.SubSequence {
> return forwardedSequence.dropFirst(n)
> }
> 
> func dropLast(n: Int) -> ForwardedSequenceType.SubSequence {
> return forwardedSequence.dropLast(n)
> }
> 
> func prefix(maxLength: Int) -> ForwardedSequenceType.SubSequence {
> return forwardedSequence.prefix(maxLength)
> }
> 
> func suffix(maxLength: Int) -> ForwardedSequenceType.SubSequence {
> return forwardedSequence.suffix(maxLength)
> }
> 
> func split(maxSplit: Int, allowEmptySlices: Bool, @noescape isSeparator: 
> (ForwardedSequenceType.Generator.Element) throws -> Bool) rethrows -> 
> [ForwardedSequenceType.SubSequence] {
> return try forwardedSequence.split(maxSplit, allowEmptySlices: 
> allowEmptySlices, isSeparator: isSeparator)
> }
> }

FWIW,

https://github.com/apple/swift/blob/master/stdlib/public/core/SequenceWrapper.swift

Though I don’t know why we still have this; it’s not used anywhere and should 
probably be removed.  I think it was supposed to be part of the new lazy 
sequence/collection subsystem but it was never incorporated.

> With this protocol declared, I can then say something like
>  
> struct Foo {
> var ary: [Int]
> }
> 
> extension Foo : SequenceTypeForwarder {
> var forwardedSequence: [Int] { return ary }
> }
>  
> and my struct Foo now automatically implements SequenceType by forwarding to 
> its variable `ary`.
>  
> The downside to this is it needs to be manually declared for each protocol. 
> But I wager that most protocols actually aren't really amenable to forwarding 
> anyway.
>  
> -Kevin Ballard
> 
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal Draft] automatic protocol forwarding

2015-12-29 Thread Charles Srstka via swift-evolution
On Dec 29, 2015, at 5:38 PM, Matthew Johnson  wrote:
> 
> 
>> On Dec 29, 2015, at 5:25 PM, Charles Srstka > > wrote:
>> 
>> Strong +1 on this proposal. I use Objective-C’s forwarding mechanisms quite 
>> often in my custom view code, in order to separate the code managing the 
>> outer view, the layout of subviews within the view, and business logic into 
>> separate classes, all while presenting a single, monolithic interface to the 
>> user. The loss of this ability without writing tons of boilerplate is one of 
>> the things about Swift that makes me sad.
>> 
>> The one thing I’d change is upgrading the partial forwarding synthesis to 
>> the original proposal, as that’s a rather important feature IMO.
>> 
> 
> Thanks Charles.  Do you disagree with the reasons I decided not to include 
> partial forwarding in the initial proposal (it is discussed in alternatives 
> considered)?

I see it in Future Enhancements, but not in Alternatives Considered (unless I’m 
just missing it). However, my thinking is that this isn’t really that hard to 
implement; just have the forwarding mechanism forward only methods that aren’t 
already implemented in the class. This would be similar to the way protocol 
extensions work, where if you implement the method you get that, but if you 
don’t implement it, you get the protocol extension’s implementation.

Charles

___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Proposal: CollectionType.cycle property for an infinite sequence

2015-12-29 Thread Kevin Ballard via swift-evolution
On Tue, Dec 29, 2015, at 03:39 PM, plx via swift-evolution wrote:
>
>> On Dec 29, 2015, at 1:17 PM, Kevin Ballard via swift-evolution > evolut...@swift.org> wrote:
>>
>> On Tue, Dec 29, 2015, at 08:14 AM, plx via swift-evolution wrote:
>>> Personally I’d say this should be a -1 for standard-library
>>> inclusion.
>>>
>>> Swift’s not really built to handle infinite sequences right now;
>>> until they are handed better by the standard library convenience
>>> methods for creating them shouldn’t be in the standard library.
>>
>> As far as I can tell, the only way in which it's "not really built"
>> to handle this is that there are multiple constructs that attempt to
>> eagerly consume an entire sequence, and using these with an infinite
>> sequence would end up looping forever. But I don't consider that to
>> be a particularly serious problem. You could "fix" it by refactoring
>> SequenceType into two protocols, SequenceType (for possibly-infinite
>> sequences) and FiniteSequenceType (for known-finite sequences) and
>> then going over the entire standard library and updating various
>> spots to use FiniteSequenceType, except this would be very limiting
>> (sequences that are not known if they're infinite to the compiler
>> could still be valid for various eager algorithms if the programmer
>> knows it will be finite in practice).
>
> Indeed, on my wishlist I would like to see the standard protocols
> refactored to something more like this:
>
> SequenceType // can be iterated FiniteSequenceType : SequenceType, //
> of finite length StableSequenceType : SequenceType, // can be re-
> iterated identically CollectionType : StableSequenceType,
> FiniteSequenceType, (etc.) // otherwise as it is now
>
> …but can understand the wish to not overly-complicate the basic
> protocol hierarchy (and also to avoid baking-in nice-to-have, but 
> impossible-to-really-
> enforce semantic requirements; I’d trust the standard library to use
> them properly, but not typical 3rd party code, somewhat defeating the
> purpose).
>
> Everything else is a difference of outlook; we agree on the facts and
> differ in interpretation.
>
> I consider concrete types that adopt a protocol only to simply call
> `fatalError` for most of the protocol methods to be pathological —
> often useful, but still pathological — and thus far the standard
> library doesn’t contain any such pathological types (to my knowledge).

It only calls `fatalError` because the default implementation would loop
forever anyway (and consume more and more memory until this eventually
causes a crash). You can trivially remove the `fatalError()`
implementations and still have the CycleSequence type, the only reason
to have them is because we may as well tell the user exactly what they
did wrong instead of letting the program enter an infinite loop that
tries to eat all the memory in the system.

> `cycle` is useful but not useful enough to be the standard library’s
> first “pathological” type, so it’s still a -1 as proposed.

There's plenty of use for infinite sequences. And all infinite sequences
are "pathological" in the same sense. The fact that the stdlib doesn't
provide any convenient ways to produce infinite sequences right now is a
deficiency, not an advantage. As previously stated, the issues with
infinite sequences also manifest with extremely long finite sequences
(such as `(1.. or if you explicitly constrain the return value of
map()/filter() to Array (which will cause it to resolve to the
SequenceType version). But in both cases, the problems with Cycle are,
as I said before, the same problems you'd get with something like
`(1..>> You can conceivably implement a non-crashing `contains`,
>>> `minElement` and `maxElement` on `CycleSequence` by calling through
>>> to the wrapped collection, but that’ll seemingly evaporate as soon
>>> as your `CycleSequence` winds up hidden inside an `AnySequence`.
>>
>> You can't override those anyway in a generic context, because they're
>> not members of the protocol, they're just extensions. You could
>> implement them such that your implementation is called when working
>> on the concrete CycleSequence type, but I'm not sure if that's a
>> great idea to do that when the actual behavior differs from calling
>> it generically on SequenceType (well, triggering a fatalError()
>> instead of an infinite loop is fine because they're both Bottom, but
>> returning a valid result in one context and looping infinitely in the
>> other seems bad).
>>
>> Of course, these methods could actually be moved into the protocol
>> itself, which would let us override them. I'm not entirely sure why
>> they aren't in the protocol to begin with, I guess because there's
>> not much need for overriding these outside of infinite sequences
>> (well, finite sorted sequences could provide an optimized
>> min/maxElement, and an optimized version of contains(_:
>> Self.Generator.Element), but maybe there's tradeoffs to doing this,
>> e.g. maybe there's some reaso

Re: [swift-evolution] [Proposal Draft] automatic protocol forwarding

2015-12-29 Thread Brent Royal-Gordon via swift-evolution
>> * Does it have to be a protocol? Why not also allow the concrete type of the 
>> property you're forwarding to? Obviously you couldn't form a subtype 
>> relationship (unless you could...), but this might be useful to reduce 
>> boilerplate when you're proxying something.
> 
> This is addressed in the alternatives considered section.

Sorry, I missed that, probably because the sample code in that section didn't 
show such a forwarding.

> The short answer is that there the direct interface of the concrete type does 
> not contain sufficient information about potential Self parameters to do this 
> well.  This information does exist in the protocol declarations.  Allowing 
> this information to be specified in concrete interfaces would add enough 
> complexity to the language that I don’t think it is worthwhile.

That's a good point. You could perhaps add a way to tweak the forwarding of 
certain members, but that'd be a little tricky.

One of the things I'd like to see is the ability to proxy for an instance 
without the person writing the proxy knowing which instances it'll be used 
with. Think, for example, of the Cocoa animator proxy, or 
`NSUndoManager.prepareWithInvocationTarget(_:)`. It'd be nice if a Swift 
equivalent could return, say, `NSAnimatorProxy` or 
`NSUndoManager.InvocationTarget`, which has all the methods of the 
generic type but records the calls for later use.

Of course, what you really want is for only a particular subset of the methods 
to be available on the proxy (animated methods on `NSAnimatorProxy`, Void 
methods on `NSUndoManager.InvocationTarget`), and of course in these cases 
you're not calling directly through to the underlying methods. So I might just 
be barking up the wrong tree here.

>> * Why the method-based conversion syntax for return values, rather than 
>> something a little more like a property declaration?
>> 
>>  var number: Int
>>  forward IntegerType to number {
>>  static return(newValue: Int) {
>>  return NumberWrapper(newValue)
>>  }
>>  return(newValue: Int) {
>>  return NumberWrapper(newValue)
>>  }
>>  }
> 
> This is actually a really good idea to consider!  I didn’t consider something 
> like this mostly because I didn’t think of it.  I’m going to seriously 
> consider adopting an approach along these lines.

Great.

> One possible advantage of the approach I used is that the initializer may 
> already exist for other reasons and you would not need to do any extra work.

True. But it may also exist and *not* do what you want in the forwarding case. 
It's easier to explicitly use the right initializer than it is to work around 
the forwarding system implicitly using the wrong one.

> A big advantage of this approach is that it would work even when you are 
> forwarding different protocols to more than one member with the same type.

But again, if that's the wrong behavior, there's no good way to fix it.

>> * If you want to keep the method-based syntax, would it make sense to 
>> instead have an initializer for instance initializers too, and just have it 
>> take a second parameter with the instance?
>> 
>>  init(forwardedReturnValue: Int) {...}
>>  init(forwardedReturnValue: Int, from: NumberWrapper) {…}
> 
> Part of the reason the instance method was used is because sometimes the 
> right thing to do might be to mutate and then return self.  Using an instance 
> method gives you the flexibility to do that if necessary.

In practice, I'm not sure that's actually the case very often. How frequently 
will the internal type return a changed value, but your identically-named cover 
method ought to mutate the property? That completely changes the semantics of 
the underlying call.

I mean, what you're proposing would be something like this:

class ListOfThings {
private var actualList: [Thing]

func filter(predicate: Thing -> Bool) -> ListOfThings {
let returnValue = actualList.filter(predicate)
actualList = returnValue
return ListOfThings(returnValue)
}
}

Is that a thing you actually expect people to do?

>> * Does this mean that a `public forward` declaration would forward 
>> `internal` members through synthesized `public` interfaces, if the forwarder 
>> and forwardee happened to be in the same module?
>> 
>>> All synthesized members recieve access control modifiers matching the 
>>> access control modifier applied to the forward declaration.
> 
> Yes, if the forwardee had internal visibility and the forwarder was public 
> the forwarder could publicly forward the interface.  This is intentional 
> behavior.  The forwardee may well be an internal implementation detail while 
> the methods of the protocol are part of the public interface of the 
> forwarder.  It is possible to write code that d

Re: [swift-evolution] Proposal: CollectionType.cycle property for an infinite sequence

2015-12-29 Thread Dave Abrahams via swift-evolution

> On Dec 27, 2015, at 11:20 PM, Kevin Ballard via swift-evolution 
>  wrote:
> 
> ## Introduction
> 
> Add a new property `cycle` to CollectionType that returns an infinite 
> SequenceType that yields the elements of the collection in a loop.

The name should give an explicit indication that the result is infinite, e.g. 
“repeatedForever".  

> ## Motivation
> 
> It's sometimes useful to be able to have an infinite sequence. For example, 
> `CollectionOfOne(x).cycle` could be used to have an infinite sequence of a 
> single element (similar to Repeat but without a count). A common use for 
> infinite sequences is zipping with a finite sequence. As far as I'm aware, 
> the stdlib does not currently provide any way to create such an infinite 
> sequence.

If this is, as I suspect, the primary use case, I would prefer a much clearer 
incantation than CollectionOfOne(x).repeatedForever.  The part before the 
parentheses is mostly irrelevant.  I suppose [x].repeatedForever could work, 
but needing an array allocation makes me sad.  I wish I had something better to 
suggest… This may in fact be the best we can do.

> ## Proposed solution
> 
> Extend CollectionType with a new property `cycle` that yields a type that 
> conforms to SequenceType. This sequence yields each element of the collection 
> in an infinite loop.
> 
> ## Detailed design
> 
> 2 new types would be added:
> 
> struct CycleSequence : LazySequenceType { ... }
> struct CycleGenerator : GeneratorType { ... }
> 
> CollectionType would be extended with a property:
> 
> extension CollectionType {
>public var cycle: CycleSequence { get }
> }
> 
> This is an extension of CollectionType instead of SequenceType because it 
> requires a multi-pass sequence (and SequenceType does not provide that 
> guarantee).

You can copy the elements into an array in that case.  Whether or not we should 
provide that is an open question, but we do similar things for, e.g., reverse().

> The returned type conforms to SequenceType instead of CollectionType because 
> there is no possible `endIndex` that satisfies the requirement of being 
> reachable from `startIndex` by zero or more applications of `successor()`.

Yeah… I’m not sure we want to do so, but we should consider loosening that 
requirement.  After all, x.repeatedForever.prefix(1000) is in principle a 
perfectly cromulent collection that shouldn’t require copying x’s elements into 
new storage.

> Because the default eager versions of map and filter will execute forever on 
> an infinite sequence, CycleSequence conforms to LazySequenceType instead of 
> SequenceType in order to provide lazy versions of those functions.

It would arguably be more appropriate to only provide repeatedForever on 
instances of LazySequenceType.  The idea has always been that users are 
surprised when they see their map/filter closure’s side-effects happen multiple 
times, or at odd times, so we make them write “.lazy” to specifically opt into 
that behavior.  I’ve always had mixed feelings about this, thinking that maybe 
it would be better to educate people about laziness, but that’s what we 
currently do.  

We could weasel out of the “multiple side-effects” problem by declaring that 
since the result is not a collection you can only make one pass through any 
part of the result, so if your side-effect over-fires, it’s on you.  I wouldn’t 
be in favor of making this sequence *actually* single-pass though, and this 
doesn’t solve the “side-effects at odd times” issue.

> Additionally, it will provide implementations of the eager versions that 
> simply trigger a fatalError(), as the alternative is an infinite loop that 
> consumes more and more memory.

Why do this?  What would these eager APIs look like?

> 
> ## Impact on existing code
> 
> None
> 
> -Kevin Ballard
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Proposal: CollectionType.cycle property for an infinite sequence

2015-12-29 Thread Dave Abrahams via swift-evolution

> On Dec 27, 2015, at 11:35 PM, Developer via swift-evolution 
>  wrote:
> 
> +1.  Stream support is long overdue.

Could you define what you mean by “stream support?”  Whatever it is, I doubt 
simply adding an infinitely-repeating sequence type is enough to get you there.

-Dave

___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Closure Syntax

2015-12-29 Thread Ethan Diamond via swift-evolution
I guess the core of the question for me is why have the concept of a
closure at all when they're harder to read while acting the same way that
functions do? I'm not a huge fan of Javascript, but the consistancy between
function declarations and anonymous functions is something I feel they got
right. JS syntax for everything that receives parameters and possibly
returns a value is entirely consistent.

Let's take the anonymous function style:

func asyncWithCallback(_ : func (String) -> Bool)

asyncWithCallback(func (param) {
return param == "string"
})

Particularly for someone new to the language is both clearer and shorter
than this, which makes the caller rewrite the return type in the closure:

func asyncWithCallback(_ : String -> Bool)

asyncWithCallback {
  (param: String) -> Bool in
  return param == "string"
}

It still fits your unwritten rule to be able to compose language features
in Swift, assuming you leave the same syntactic sugar:

func if (_ control: Bool, _ path: func ()) {

  if (control) {

 path()

  }

}

if (a == b) {

  //LETS DO SOME STUFF

}

I know it's a big change to the language, but I feel like it's better
in just about every case I can think of without losing the Swiftiness
we all enjoy. It certainly makes this easier to read. Even in one of
the examples in the Swift guide
(https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html)
you're essentially using the syntax i'm proposing on the incrementer:

func makeIncrementer(forIncrement amount: Int) -> () -> Int {

var runningTotal = 0

func incrementer() -> Int {

runningTotal += amount

return runningTotal

}

return incrementer

}

I can't really fix the unclear chained return in the declaration, but
doesn't the return of the anonymous function look similar to the
above, just as you would expect?

func makeIncrementer(forIncrement amount: Int) -> func() -> Int {

   var runningTotal = 0

   return func () -> Int {

runningTotal += amount

return runningTotal

  }

}

But if I wanted to use closure syntax, It'd be different from the
example above in the Swift handbook for no real good reason:

func makeIncrementer(forIncrement amount: Int) -> () -> Int {

var runningTotal = 0

return {

() -> Int in

runningTotal += amount

return runningTotal

}

}

In the commonly rejected list, Jordan wrote:

"We thought a lot about this, and settled on the current syntax
(inside the braces) for several reasons, the main one being that it's
much easier to parse. Without this, the compiler would have to stop
whatever it's currently doing when it sees '->'."

I don't believe that's a problem when using the proposed func syntax,
since by definition "->" will only follow a func (param) statement in
all cases. The compiler can make more assumptions about what it's
parsing. I think it might limit what you have to work with to the
compilers benefit.

Thanks,

- Ethan


On Mon, Dec 28, 2015 at 5:44 PM, Chris Lattner  wrote:

>
> On Dec 27, 2015, at 2:30 PM, Ethan Diamond via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> I realize this is on the commonly rejected list, but I really find closure
> syntax to be one of the more unintuitive and unreadable parts of Swift so
> I'd like to try to influence it. "Clarity at the point of use" is one of
> the main stated goals of Swift, and the fact that
> http://goshdarnclosuresyntax.com/ exists shows me that it's not just me
> that thinks the syntax could be improved. I believe that we can get very
> close to the same results in line length and expressiveness while making
> the language much more readable and clear.
>
>
> FWIW, I think that web site exists as a continuation of the “blocks” web
> site.
>
> From your description, it sounds like you might want to try out nested
> functions.  They have a more explicit syntax, and still provide the same
> “closure” power as closure expressions.
>
> -Chris
>
>
> Let's start with a few use cases to illustrate what I mean when I say that
> reading closure syntax is difficult. Most programmers scan left to right,
> so when I see this property declaration:
>
> var thing: Int
>
> My brain reads that as a property of a class that's an integer. Unless of
> course there's this:
>
> var thing: Int -> Int
>
> Boom, context switch. If you've read "Int" than any following syntax
> should be a modifier on Int. For example, Int? works great, because in my
> head it's still an Integer, just an optional form of that Integer. While
> it's not a huge change in that example, lets take a more complicated one:
>
> var thing: (String -> (), Int, (Int, Int) -> Bool)) -> Bool
>
> Reading that left to right requires all sorts of context switching in my
> brain. I can't even tell at first glance how many params are in that
> closure. Reading left to right, you read "First parameter, string, no wait,
> closure that takes string, and returns v

Re: [swift-evolution] Proposal: CollectionType.cycle property for an infinite sequence

2015-12-29 Thread Craig Cruden via swift-evolution
> Could you define what you mean by “stream support?”  Whatever it is, I doubt 
> simply adding an infinitely-repeating sequence type is enough to get you 
> there.


I can guess — but it is only a guess.  

A function defines an infinite “set” of values (like the digits of pi).  A 
stream is just a special type of traversable (lazy) which does not evaluate 
until asked for the next in a sequence of the set.  A function defined in a 
stream will thus only continue calculating next digits when asked for them.  
Similarly you could have a collection (head/tail) and you ask for the head and 
you get it, but the rest (tail) is just the tail as a whole and none of the 
values in it are really defined until you traverse down to the next head of the 
rest of the tail.  Once it is evaluated it is stored in memory for future 
evaluations.  If you were to fully evaluate the function it would never finish, 
and if it were to finish — you would probably run out of memory.




As usual I created these examples with the Scala 2.8 REPL but I think most if 
not all should work in 2.7.
> On 2015-12-30, at 7:12:41, Dave Abrahams via swift-evolution 
>  wrote:
> 
> 
>> On Dec 27, 2015, at 11:35 PM, Developer via swift-evolution 
>>  wrote:
>> 
>> +1.  Stream support is long overdue.
> 
> Could you define what you mean by “stream support?”  Whatever it is, I doubt 
> simply adding an infinitely-repeating sequence type is enough to get you 
> there.
> 
> -Dave
> 
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] rename dropFirst() and dropLast()

2015-12-29 Thread Kevin Ballard via swift-evolution
On Tue, Dec 29, 2015, at 03:39 PM, Daniel Duan wrote:
> I suppose it’s appropriate to go into grammars since we are in a language 
> mailing list :)
> 
> Present Participle is just an official name for “verb in present tense”, as 
> in “I am *writing* an email”. Let’s put the example from API Guideline to 
> test. I hope you agree that “someText.strippingNewlines()” as a non-mutating 
> method name is grammatical *somehow*. So, does it read as
> 
>   self is *stripping newlines*, here’s X.
> 
> …or does this make more sense…
> 
>   *stripping newlines* from self gives X.
> 
> ?
> 
> I tend to think the latter. There’s a fancy name for it as well: gerund 
> phrase.

I don't read it either way. As suggested in my previous email, I'd read this as 
"transforms someText by *splitting newlines* (and returns the result)". It's 
not entirely clear how to classify this usage (since grammar is confusing), but 
it's kind of a moot point because Wikipedia says:

> The distinction between gerund and present participles is not recognised in 
> modern reference grammars, since many uses are ambiguous.

And it doesn't really matter anyway because the guidelines don't say that the 
non-mutating variant has to read as a noun phrase, it just says to name it 
using the appropriate -ed/-ing ending. And in the case of strippingNewlines(), 
this makes sense, as it's the non-mutating counterpart to stripNewlines().

But in the case of dropFirst(), this is not a non-mutating counterpart to 
removeFirst(). dropFirst() is defined on SequenceType, which has no 
removeFirst(). If anything, removeFirst() is a mutating version that's derived 
from dropFirst() (although not really, since removeFirst() is named after 
removeAtIndex() and the only naming relation it has to dropFirst() is re-using 
the same "First" suffix).

-Kevin
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Proposal: CollectionType.cycle property for an infinite sequence

2015-12-29 Thread Dave Abrahams via swift-evolution

> On Dec 29, 2015, at 3:39 PM, plx via swift-evolution 
>  wrote:
> 
>> 
>> On Dec 29, 2015, at 1:17 PM, Kevin Ballard via swift-evolution 
>> mailto:swift-evolution@swift.org>> wrote:
>> 
>> On Tue, Dec 29, 2015, at 08:14 AM, plx via swift-evolution wrote:
>>> Personally I’d say this should be a -1 for standard-library inclusion.
>>> 
>>> Swift’s not really built to handle infinite sequences right now; until they 
>>> are handed better by the standard library convenience methods for creating 
>>> them shouldn’t be in the standard library.
>> 
>> As far as I can tell, the only way in which it's "not really built" to 
>> handle this is that there are multiple constructs that attempt to eagerly 
>> consume an entire sequence, and using these with an infinite sequence would 
>> end up looping forever. But I don't consider that to be a particularly 
>> serious problem. You could "fix" it by refactoring SequenceType into two 
>> protocols, SequenceType (for possibly-infinite sequences) and 
>> FiniteSequenceType (for known-finite sequences) and then going over the 
>> entire standard library and updating various spots to use 
>> FiniteSequenceType, except this would be very limiting (sequences that are 
>> not known if they're infinite to the compiler could still be valid for 
>> various eager algorithms if the programmer knows it will be finite in 
>> practice).
> 
> Indeed, on my wishlist I would like to see the standard protocols refactored 
> to something more like this:
> 
> SequenceType // can be iterated
> FiniteSequenceType : SequenceType, // of finite length
> StableSequenceType : SequenceType, // can be re-iterated identically
> CollectionType : StableSequenceType, FiniteSequenceType, (etc.) // otherwise 
> as it is now

This is interesting. A few concerns:

First, we have tried not to create any distinct protocols with identical 
syntactic requirements, because we think it makes the world clearer; we think 
people are more likely to assign incorrect protocols when all the operations 
they want are available, but don’t have the right semantics.  That isn’t to say 
we shouldn’t start doing it, but it would be a break from the past.

Higher protocol granularity has a high comprehensibility cost.  Distinguishing 
protocols based on semantic requirements alone may make the library harder to 
understand.  I’ve heard some people’s heads have exploded from simply 
encountering CollectionType. 

Next, it’s a principle of generic programming that every protocol should be 
justified by both algorithms that exploit its requirements (e.g. extension 
methods) and some real-world models that can’t reasonably also conform to a 
more-refined protocol.  For example, we have a ForwardIndexType because a 
singly-linked list has multipass forward traversal and can’t do bidirectional 
traversal.  In order to evaluate any proposal for new protocols, we’d need to 
see all of these things.

> …but can understand the wish to not overly-complicate the basic protocol 
> hierarchy (and also to avoid baking-in nice-to-have, but 
> impossible-to-really-enforce semantic requirements; I’d trust the standard 
> library to use them properly, but not typical 3rd party code, somewhat 
> defeating the purpose).

Well, I guess I should have read ahead and most of my lecture above was 
needless!  I’m posting it anyway because I think it spells out some important 
principles we’ll need to refer to later.

> Everything else is a difference of outlook; we agree on the facts and differ 
> in interpretation.
> 
> I consider concrete types that adopt a protocol only to simply call 
> `fatalError` for most of the protocol methods to be pathological — often 
> useful, but still pathological — and thus far the standard library doesn’t 
> contain any such pathological types (to my knowledge).
> 
> `cycle` is useful but not useful enough to be the standard library’s first 
> “pathological” type, so it’s still a -1 as proposed.
> 
> This is nothing specific to `cycle` and my opinion here could change were the 
> language or the standard library to evolve in various ways.
>> 
>>> You’d also want to call `fatalError` for at least `reduce`, `reverse`, 
>>> `sort`, `split`(?), `flatMap`, `dropLast`, `suffix`, and `forEach`.
>> 
>> You can only do it for the ones defined in the protocol, not ones defined in 
>> extensions. This means map, filter, forEach, and suffix.
>> 
>> split is actually perfectly implementable for a CycleSequence, although it 
>> does need a custom implementation. split is bounded by at most Int.max 
>> splits, which means it is guaranteed to terminate even for an infinite 
>> sequence (although the final subsequence does need to be infinite[1]). Even 
>> if there are no separators in the cycle, it can just return the cycle itself.
>> 
>> [1] Interestingly, the current implementation actually dumps the remainder 
>> into an Array and returns that (wrapped in AnySequence), which is curious 
>> because it would be perfectly legal for i

Re: [swift-evolution] Proposal: CollectionType.cycle property for an infinite sequence

2015-12-29 Thread Dave Abrahams via swift-evolution

> On Dec 29, 2015, at 4:29 PM, Craig Cruden  wrote:
> 
>> Could you define what you mean by “stream support?”  Whatever it is, I doubt 
>> simply adding an infinitely-repeating sequence type is enough to get you 
>> there.
> 
> 
> I can guess — but it is only a guess.  
> 
> A function defines an infinite “set” of values (like the digits of pi).  A 
> stream is just a special type of traversable (lazy) which does not evaluate 
> until asked for the next in a sequence of the set.  A function defined in a 
> stream will thus only continue calculating next digits when asked for them.  
> Similarly you could have a collection (head/tail) and you ask for the head 
> and you get it, but the rest (tail) is just the tail as a whole and none of 
> the values in it are really defined until you traverse down to the next head 
> of the rest of the tail.  Once it is evaluated it is stored in memory for 
> future evaluations.  If you were to fully evaluate the function it would 
> never finish, and if it were to finish — you would probably run out of memory.

Yes, I understand the usual concept of a “stream," but it doesn’t help me 
understand what  stream *support* entails.

-Dave

___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] rename dropFirst() and dropLast()

2015-12-29 Thread Dave Abrahams via swift-evolution

> On Dec 28, 2015, at 5:35 PM, David Waite via swift-evolution 
>  wrote:
> 
> If one were to rename dropFirst/dropLast, I’d love for prefix and suffix to 
> be renamed also to better pair with the methods.

I prefer to address this by creating a unified EDSL for describing all of these 
operations as discussed in this thread: Re: Proposal: Python's indexing and 
slicing 


-Dave

___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Proposal: CollectionType.cycle property for an infinite sequence

2015-12-29 Thread Kevin Ballard via swift-evolution
On Tue, Dec 29, 2015, at 04:11 PM, Dave Abrahams wrote:
> 
> > On Dec 27, 2015, at 11:20 PM, Kevin Ballard via swift-evolution 
> >  wrote:
> > 
> > ## Introduction
> > 
> > Add a new property `cycle` to CollectionType that returns an infinite 
> > SequenceType that yields the elements of the collection in a loop.
> 
> The name should give an explicit indication that the result is infinite, e.g. 
> “repeatedForever".  

All of the precedent I'm aware of calls this operation "cycle".

Haskell: 
http://hackage.haskell.org/package/base-4.8.1.0/docs/Prelude.html#v:cycle
Rust: https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.cycle
Ruby: http://ruby-doc.org/core-2.2.3/Enumerable.html#method-i-cycle
Python: 
https://docs.python.org/3/library/itertools.html?highlight=cycle#itertools.cycle
D: http://dlang.org/phobos/std_range.html#cycle

I'm not sure offhand what other languages to even look to for this.

> > ## Motivation
> > 
> > It's sometimes useful to be able to have an infinite sequence. For example, 
> > `CollectionOfOne(x).cycle` could be used to have an infinite sequence of a 
> > single element (similar to Repeat but without a count). A common use for 
> > infinite sequences is zipping with a finite sequence. As far as I'm aware, 
> > the stdlib does not currently provide any way to create such an infinite 
> > sequence.
> 
> If this is, as I suspect, the primary use case, I would prefer a much clearer 
> incantation than CollectionOfOne(x).repeatedForever.  The part before the 
> parentheses is mostly irrelevant.  I suppose [x].repeatedForever could work, 
> but needing an array allocation makes me sad.  I wish I had something better 
> to suggest… This may in fact be the best we can do.

Honestly, I'd actually like to take Repeat and remove the count. I've never 
used this type and I've never seen any code that uses this type. The current 
counted behavior of Repeat could then be recovered by saying 
`Repeat(elt).prefix(count)`. Of course, this would only repeat a single 
element, so we'd still need Cycle to repeat sequences (which is why I suggested 
`CollectionOfOne(x).cycle` as that has the same behavior, although of course 
Repeat then just becomes a special case of 
`CollectionOfOne(x).cycle.prefix(count)`).

> > ## Proposed solution
> > 
> > Extend CollectionType with a new property `cycle` that yields a type that 
> > conforms to SequenceType. This sequence yields each element of the 
> > collection in an infinite loop.
> > 
> > ## Detailed design
> > 
> > 2 new types would be added:
> > 
> > struct CycleSequence : LazySequenceType { ... }
> > struct CycleGenerator : GeneratorType { ... }
> > 
> > CollectionType would be extended with a property:
> > 
> > extension CollectionType {
> >public var cycle: CycleSequence { get }
> > }
> > 
> > This is an extension of CollectionType instead of SequenceType because it 
> > requires a multi-pass sequence (and SequenceType does not provide that 
> > guarantee).
> 
> You can copy the elements into an array in that case.  Whether or not we 
> should provide that is an open question, but we do similar things for, e.g., 
> reverse().

You can, but I prefer not to hide array creation like that whenever possible. 
If I need to cycle some SequenceType I can just wrap it in Array myself, e.g. 
`Array(seq).cycle`.

> > The returned type conforms to SequenceType instead of CollectionType 
> > because there is no possible `endIndex` that satisfies the requirement of 
> > being reachable from `startIndex` by zero or more applications of 
> > `successor()`.
> 
> Yeah… I’m not sure we want to do so, but we should consider loosening that 
> requirement.  After all, x.repeatedForever.prefix(1000) is in principle a 
> perfectly cromulent collection that shouldn’t require copying x’s elements 
> into new storage.

Loosening this breaks the `count` property. There's no valid value of `count` 
that can be returned for an infinite sequence. The property could of course 
just loop infinitely (or fatalError), but that strikes me as being a much worse 
idea than e.g. map() looping forever, because with map() we have a lazy 
replacement but there is no lazy replacement for count.

We could of course give CycleSequence a separate prefix() function that returns 
a collection (but the prefix() from SequenceType must return SubSequence, which 
cannot be a collection).

> > Because the default eager versions of map and filter will execute forever 
> > on an infinite sequence, CycleSequence conforms to LazySequenceType instead 
> > of SequenceType in order to provide lazy versions of those functions.
> 
> It would arguably be more appropriate to only provide repeatedForever on 
> instances of LazySequenceType.  The idea has always been that users are 
> surprised when they see their map/filter closure’s side-effects happen 
> multiple times, or at odd times, so we make them write “.lazy” to 
> specifically opt into that behavior.  I’ve always had mixed feelings 

Re: [swift-evolution] [Proposal draft] Generalized Naming for Any Function

2015-12-29 Thread Patrick Smith via swift-evolution
Hi all, hope I’m not adding to what has already been said.
Instead of:
let fn = someView.insertSubview(_:at:)
Could you have:
let fn = someView.insertSubview(_ at: _)
Basically like unused parameters in reverse.
Filling out all parameters with _ would return a function to the method, like 
the behaviour proposed. The advantages would be consistency, readability, and 
compatibility with autocomplete.
Additionally this could possibly lead to partial parameter application, but 
that’s outside the scope of what is being discussed.
Patrick___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal Draft] automatic protocol forwarding

2015-12-29 Thread Matthew Johnson via swift-evolution

> On Dec 29, 2015, at 5:45 PM, Charles Srstka  wrote:
> 
> On Dec 29, 2015, at 5:38 PM, Matthew Johnson  > wrote:
>> 
>> 
>>> On Dec 29, 2015, at 5:25 PM, Charles Srstka >> > wrote:
>>> 
>>> Strong +1 on this proposal. I use Objective-C’s forwarding mechanisms quite 
>>> often in my custom view code, in order to separate the code managing the 
>>> outer view, the layout of subviews within the view, and business logic into 
>>> separate classes, all while presenting a single, monolithic interface to 
>>> the user. The loss of this ability without writing tons of boilerplate is 
>>> one of the things about Swift that makes me sad.
>>> 
>>> The one thing I’d change is upgrading the partial forwarding synthesis to 
>>> the original proposal, as that’s a rather important feature IMO.
>>> 
>> 
>> Thanks Charles.  Do you disagree with the reasons I decided not to include 
>> partial forwarding in the initial proposal (it is discussed in alternatives 
>> considered)?
> 
> I see it in Future Enhancements, but not in Alternatives Considered (unless 
> I’m just missing it). However, my thinking is that this isn’t really that 
> hard to implement; just have the forwarding mechanism forward only methods 
> that aren’t already implemented in the class. This would be similar to the 
> way protocol extensions work, where if you implement the method you get that, 
> but if you don’t implement it, you get the protocol extension’s 
> implementation.
> 

You are right, I included it in that section.  It is definitely something I 
want to see supported eventually.  I just don’t want it to hold up the initial 
proposal.  

I also want to make sure any subtleties have been thoroughly considered and 
addressed before it goes forward.  I understand that it is in some sense 
similar in some sense to protocol methods with default implementations.  
However I think it is actually closer to inheritance (this proposal can in some 
respects be considered a limited and controlled form of multiple inheritance).  

The author of a protocol understands and intends the default implementations to 
be just that - defaults.  The author of the type that is forwarded to may have 
expectations that it receives all calls for all members of a protocol it 
implements and the implementation may not work correctly or as expected if that 
does not happen.  IMO, it is important to think about the implications of 
partial forwarding, limitations that may be necessary, etc.

Despite my caution around partial forwarding, there is one reason that it might 
make sense to support partial forwarding in the initial proposal.  
Specifically, it would be easy to get around the limitation by simply declaring 
a new protocol that contains only the members you want to forward and use that 
in your forwarding declaration.  And of course you can also write manual 
forwarding code.  So a limitation of the automatic forwarding mechanism 
wouldn’t stop you from doing partial forwarding, it would just make it more 
annoying.  It might be better to “complete” the design from the start for this 
reason.  I will definitely give this further thought.

Do you have specific use cases in mind for partial forwarding?  If so, please 
share them.

Matthew___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Proposal: CollectionType.cycle property for an infinite sequence

2015-12-29 Thread Craig Cruden via swift-evolution
I have never tried to implement a “stream” in Swift, so I am not sure if there 
is an easy way to do it…. but I don’t see a collection of type stream as I have 
in Scala.  

http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Stream
 



> On 2015-12-30, at 7:39:54, Dave Abrahams  wrote:
> 
> 
>> On Dec 29, 2015, at 4:29 PM, Craig Cruden > > wrote:
>> 
>>> Could you define what you mean by “stream support?”  Whatever it is, I 
>>> doubt simply adding an infinitely-repeating sequence type is enough to get 
>>> you there.
>> 
>> 
>> I can guess — but it is only a guess.  
>> 
>> A function defines an infinite “set” of values (like the digits of pi).  A 
>> stream is just a special type of traversable (lazy) which does not evaluate 
>> until asked for the next in a sequence of the set.  A function defined in a 
>> stream will thus only continue calculating next digits when asked for them.  
>> Similarly you could have a collection (head/tail) and you ask for the head 
>> and you get it, but the rest (tail) is just the tail as a whole and none of 
>> the values in it are really defined until you traverse down to the next head 
>> of the rest of the tail.  Once it is evaluated it is stored in memory for 
>> future evaluations.  If you were to fully evaluate the function it would 
>> never finish, and if it were to finish — you would probably run out of 
>> memory.
> 
> Yes, I understand the usual concept of a “stream," but it doesn’t help me 
> understand what  stream *support* entails.
> 
> -Dave
> 

___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] rename dropFirst() and dropLast()

2015-12-29 Thread Daniel Duan via swift-evolution
The fact that SequenceType is non-mutable and does not have the remove* method 
has been clear from the start. In *effect*, however,  concrete CollectionTypes 
do have both .removeFirst() and dropFirst().

Replacing .dropFirst() with a “better” verb phrase such as .skipFirst() raises 
a new concern:

The API Guidelines *could* make Swift 3 users to expect consistency when it 
comes to mutating/non-mutating pair APIs *wherever applicable*. This is a great 
goal for a programming language. Taking this away from Array just because it 
happens to be a SequenceType? That’s Robbery. 

- Daniel

> On Dec 29, 2015, at 4:29 PM, Kevin Ballard  wrote:
> 
> On Tue, Dec 29, 2015, at 03:39 PM, Daniel Duan wrote:
>> I suppose it’s appropriate to go into grammars since we are in a language 
>> mailing list :)
>> 
>> Present Participle is just an official name for “verb in present tense”, as 
>> in “I am *writing* an email”. Let’s put the example from API Guideline to 
>> test. I hope you agree that “someText.strippingNewlines()” as a non-mutating 
>> method name is grammatical *somehow*. So, does it read as
>> 
>>  self is *stripping newlines*, here’s X.
>> 
>> …or does this make more sense…
>> 
>>  *stripping newlines* from self gives X.
>> 
>> ?
>> 
>> I tend to think the latter. There’s a fancy name for it as well: gerund 
>> phrase.
> 
> I don't read it either way. As suggested in my previous email, I'd read this 
> as "transforms someText by *splitting newlines* (and returns the result)". 
> It's not entirely clear how to classify this usage (since grammar is 
> confusing), but it's kind of a moot point because Wikipedia says:
> 
>> The distinction between gerund and present participles is not recognised in 
>> modern reference grammars, since many uses are ambiguous.
> 
> And it doesn't really matter anyway because the guidelines don't say that the 
> non-mutating variant has to read as a noun phrase, it just says to name it 
> using the appropriate -ed/-ing ending. And in the case of 
> strippingNewlines(), this makes sense, as it's the non-mutating counterpart 
> to stripNewlines().
> 
> But in the case of dropFirst(), this is not a non-mutating counterpart to 
> removeFirst(). dropFirst() is defined on SequenceType, which has no 
> removeFirst(). If anything, removeFirst() is a mutating version that's 
> derived from dropFirst() (although not really, since removeFirst() is named 
> after removeAtIndex() and the only naming relation it has to dropFirst() is 
> re-using the same "First" suffix).
> 
> -Kevin

___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal Draft] automatic protocol forwarding

2015-12-29 Thread Matthew Johnson via swift-evolution

> On Dec 29, 2015, at 6:10 PM, Brent Royal-Gordon  
> wrote:
> 
>>> * Does it have to be a protocol? Why not also allow the concrete type of 
>>> the property you're forwarding to? Obviously you couldn't form a subtype 
>>> relationship (unless you could...), but this might be useful to reduce 
>>> boilerplate when you're proxying something.
>> 
>> This is addressed in the alternatives considered section.
> 
> Sorry, I missed that, probably because the sample code in that section didn't 
> show such a forwarding.
> 
>> The short answer is that there the direct interface of the concrete type 
>> does not contain sufficient information about potential Self parameters to 
>> do this well.  This information does exist in the protocol declarations.  
>> Allowing this information to be specified in concrete interfaces would add 
>> enough complexity to the language that I don’t think it is worthwhile.
> 
> That's a good point. You could perhaps add a way to tweak the forwarding of 
> certain members, but that'd be a little tricky.

I gave this enough consideration to be leaning pretty strongly in the direction 
that protocols are the best way to do this.  

Doing this properly for the concrete interface would require an `InvariantSelf` 
type that could be used in any method signature.  It would also need to be 
actually used correctly in practice by types that were forwarded to.  The 
distinction is pretty subtle when you’re dealing with a concrete interface and 
my instinct is that people would get it wrong a lot of the time.  

Because protocols are inherently generic it is a little more straightforward to 
think about when you mean `Self` and when you mean a concrete type.

The good news is that you can declare a protocol containing the full interface 
of a concrete type if you really want or need to and use that for forwarding.  
The advantage of requiring a protocol here is that it requires you to 
consciously think about whether each parameter and return type is intended to 
be concrete or an abstract Self.  It also allows you to properly forward an 
interface even if the original author did not consider these issues when 
implementing the type.

In the following example, should the other parameter and the return type be 
`Self ` or `Double`?  It is not possible to know unless there is a protocol 
that declares foo.

extension Double {
func foo(other: Double) -> Double {
return self
}
}

> 
> One of the things I'd like to see is the ability to proxy for an instance 
> without the person writing the proxy knowing which instances it'll be used 
> with. Think, for example, of the Cocoa animator proxy, or 
> `NSUndoManager.prepareWithInvocationTarget(_:)`. It'd be nice if a Swift 
> equivalent could return, say, `NSAnimatorProxy` or 
> `NSUndoManager.InvocationTarget`, which has all the methods of the 
> generic type but records the calls for later use.
> 
> Of course, what you really want is for only a particular subset of the 
> methods to be available on the proxy (animated methods on `NSAnimatorProxy`, 
> Void methods on `NSUndoManager.InvocationTarget`), and of course in these 
> cases you're not calling directly through to the underlying methods. So I 
> might just be barking up the wrong tree here.

I can see how it might be desirable to forward to a type you receive as a 
generic parameter.  However, you would need to constrain that type to a 
protocol(s) in order to actually do anything useful with it.  That same 
protocol(s) could also be used in the forwarding declaration.

If you want is to be able to forward a set of methods that is determined by the 
generic parameter, that just isn’t going to be possible.  At least not without 
significant changes to other parts of the language providing capabilities that 
would allow you to implement something like that manually.

> 
>>> * Why the method-based conversion syntax for return values, rather than 
>>> something a little more like a property declaration?
>>> 
>>> var number: Int
>>> forward IntegerType to number {
>>> static return(newValue: Int) {
>>> return NumberWrapper(newValue)
>>> }
>>> return(newValue: Int) {
>>> return NumberWrapper(newValue)
>>> }
>>> }
>> 
>> This is actually a really good idea to consider!  I didn’t consider 
>> something like this mostly because I didn’t think of it.  I’m going to 
>> seriously consider adopting an approach along these lines.
> 
> Great.
> 
>> One possible advantage of the approach I used is that the initializer may 
>> already exist for other reasons and you would not need to do any extra work.
> 
> True. But it may also exist and *not* do what you want in the forwarding 
> case. It's easier to explicitly use the right initializer than it is to work 
> around the forwarding system implicitly using the wrong one.

Right, I am generally leaning pretty strongly towards changing the proposal t

Re: [swift-evolution] rename dropFirst() and dropLast()

2015-12-29 Thread Dave Abrahams via swift-evolution


> On Dec 29, 2015, at 2:55 PM, Kevin Ballard via swift-evolution 
>  wrote:
> 
>> On Tue, Dec 29, 2015, at 01:33 PM, Daniel Duan wrote:
>> For concrete types that conform to CollectionType:
>> 
>> [2, 1, 3].removeFirst()// => 2
>> [2, 1, 3].removingFirst() // => [1, 3]
>> 
>> seems like what the “non-mutating counterpart” guideline is aiming for. As 
>> another example, the guideline includes “stripNewlines()” and 
>> “strippingNewlines()”.
>> 
>> For SequenceType conforming types that aren’t CollectionTypes, they would be 
>> stuck with “removingFirst()”, which, technically, is a noun phrase (again, 
>> not my personal favorite). I don’t this result is against anything in the 
>> guidelines.
> 
> It's technically not a noun phrase at all. I believe you're thinking of 
> gerunds, where a verb with an -ing ending is used as a noun. But "removing" 
> in "removingFirst()" is not being used as a noun; the method does not 
> represent the act of removing, but instead it returns a new value constructed 
> "by removing first". I believe this is called the Present Participle.

Yes, we got a wad of technical corrections from an Apple linguist that have yet 
to be applied to the guidelines document.   That was one of them. 

Sent from my moss-covered three-handled family gradunza

___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


[swift-evolution] Proposal: Add function SequenceType.find()

2015-12-29 Thread Kevin Ballard via swift-evolution
I'm proposing a new extension method on SequenceType called find(). It's 
similar to CollectionType.indexOf() except it returns the element:

extension SequenceType {

/// Returns the first element where `predicate` returns `true`, or `nil`

/// if such value is not found.

public func find(@noescape predicate: (Self.Generator.Element) throws ->
Bool) rethrows -> Self.Generator.Element? {

for elt in self {

if try predicate(elt) {

return elt

}

}

return nil

}

}



-Kevin Ballard
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Proposal: Add function SequenceType.find()

2015-12-29 Thread Keith Smiley via swift-evolution
+1. We've added an extension for this and find it very useful.
On Tue, Dec 29, 2015 at 18:38 Kevin Ballard via swift-evolution <
swift-evolution@swift.org> wrote:

> I'm proposing a new extension method on SequenceType called find(). It's
> similar to CollectionType.indexOf() except it returns the element:
>
>
> extension SequenceType {
>
> /// Returns the first element where `predicate` returns `true`, or
> `nil`
>
> /// if such value is not found.
>
> public func find(@noescape predicate: (Self.Generator.Element) throws
> -> Bool) rethrows -> Self.Generator.Element? {
>
> for elt in self {
>
> if try predicate(elt) {
>
> return elt
>
> }
>
> }
>
> return nil
>
> }
>
> }
>
> -Kevin Ballard
>
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


[swift-evolution] [Proposal] Scoped resources (like C# using statement)

2015-12-29 Thread Trent Nadeau via swift-evolution
# Introduction

Add a new `Scoped` protocol and enhance the do statement to automatically
call enter/exit actions on resources.

# Motivation

Resources (e.g., locks, files, sockets, etc.) often need to be scoped to a
block, where some action is taken at the start of the block and another is
required at the end. Examples include locking and unlocking a lock in a
critical section or closing a file at the end of a block.

Doing this manually is possible using `defer` statements among other
options, but this is error prone as a `defer` can be forgotten,
`lock`/`unlock` calls for two locks can be switched due to a typo, etc.
Having a dedicated language construct for this common case makes it easier
to read and write while making code shorter and clearer.

# Language Survey

At least three major languages have widely used statements for this use
case.

## C#

C# has the `using` statement and the associated `IDisposable` interface.

```csharp
using (StreamReader sr = new StreamReader(filename)) {
txt = sr.ReadToEnd();
}
```

C#'s solution only handles close/exit actions via the
`IDisposable.Dispose()` method and so cannot easily be used with items such
as locks; however, C# has the additional `lock` statement for that use case.

## Java

Java has try-with-resources and the associated `AutoCloseable` interface.

```java
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
}
```

Java's solution only handles close/exit actions via the
`AutoCloseable.close()` method and so cannot easily be used with items such
as locks; however, Java has the additional `synchronized` statement for
that use case.

## Python

Python has with `with` statement and the associated `__enter__` and
`__exit__` special methods that classes may implement to become a "context
manager".

```python
with lock, open(path) as my_file:
contents = my_file.read()
# use contents
```

Python's solution handles both enter and exit actions and so this one
construct is usable for locks as well as resources like sockets and files.

# Proposed Solution

We add a new protocol called `Scoped` to the standard library. Types for
resources that have enter/exit actions will be extended to add conformance
to this protocol.

The `do` statement will be extended to allow a new `using `
"suffix".

# Detailed Design

The `Scoped` protocol shall be as follows:

```swift
public protocol Scoped {
func enterScope()
func exitScope()
}
```

The compiler statement will accept a new form for resources. For example,

```swift
do using lock, let file = try getFileHandle() {
// statements
}
```

As can be seen in the example above, the resources can be bindings that
already exist (like `lock`) or can be new bindings. Bindings created with
`do using` are not available outside of the scope of the `do using`. Only
types conforming to `Scoped` may be using with `do using`. Use of
non-conforming types will result in a compiler error.

The above example would be syntactic sugar for the following:

```swift
do {
lock.enterScope()
defer { lock.exitScope() }

let file = try getFileHandle()
file.enterScope()
defer { file.exitScope() }

// statements
}
```

# Framework Changes / Examples

As an example of some real-world classes that would be useful with
`Scoped`, from Foundation:

```swift
// Would be nice to extend the NSLocking protocol instead, but that's not
supported yet.
extension NSLock: Scoped {
func enterScope() {
self.lock()
}

func exitScope() {
self.unlock()
}
}

extension NSFileHandle: Scoped {
func enterScope() {}

func exitScope() {
self.closeFile()
}
}
```

# Questions and Concerns
 * Bikeshedding protocol naming and scoping syntax
 * Should the enter and exit actions be allowed to throw errors?

-- 
Trent Nadeau
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal] Scoped resources (like C# using statement)

2015-12-29 Thread Chris Lattner via swift-evolution
On Dec 29, 2015, at 8:02 PM, Trent Nadeau via swift-evolution 
 wrote:
> Doing this manually is possible using `defer` statements among other options, 
> but this is error prone as a `defer` can be forgotten, `lock`/`unlock` calls 
> for two locks can be switched due to a typo, etc. Having a dedicated language 
> construct for this common case makes it easier to read and write while making 
> code shorter and clearer.
> 
> ```swift
> do {
> lock.enterScope()
> defer { lock.exitScope() }
> 
> let file = try getFileHandle()
> file.enterScope()
> defer { file.exitScope() }
> 
> // statements
> }

We have another pattern that types can use, which is:

lock.withThisLockHeld {
  … stuff ...
}

This can be done today with trailing closures.  Other examples of this are 
“autoreleasepool” and withUnsafePointer (for other reasons).

-Chris

___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


  1   2   >