Re: [swift-evolution] [Pitch] Introduce user-defined dynamically "callable" types

2017-11-10 Thread Susan Cheng via swift-evolution
Hi all,

I have few problems with this proposal.

How we guarantee the arguments type are what we need?

If we passing the type to the dynamicCall that are not acceptable, what will 
happened?

Should we always write the dynamicCall as a throwing function to check the 
precondition?

Instead of introducing dynamic calls, I would like introducing mirror of 
instance methods.

> Joe Groff via swift-evolution  於 2017年11月11日 
> 上午8:20 寫道:
> 
> 
> 
>>> On Nov 10, 2017, at 4:12 PM, Charles Srstka  
>>> wrote:
>>> 
>>> On Nov 10, 2017, at 5:51 PM, Joe Groff  wrote:
>>> 
>>> 
>>> 
> On Nov 10, 2017, at 3:45 PM, Charles Srstka  
> wrote:
> 
> On Nov 10, 2017, at 5:36 PM, Joe Groff  wrote:
> 
> How `MyObject.foo(_:bar:)` gets implemented is its own business, as far 
> as the compiler is concerned. The compile-time name resolution for the 
> method isn't impacted.
> 
> -Joe
 
 The compile-time name resolution for the method doesn’t happen *at all.*
>>> 
>>> You declared the method in your @interface, and the compiler saw that and 
>>> brought it in as what Swift considers to be a regular method, and your call 
>>> on the Swift side was resolved to it by Swift's usual lookup rules. To do 
>>> what Chris is suggesting requires changing the way calls get resolved in 
>>> the compiler before the call is even formed.
>> 
>> The only thing that makes this the “usual lookup rules” is that the 
>> Objective-C bridge has already been implemented.
> 
> As I mentioned in my original reply, I personally think the "importer" 
> approach would be superior, and that in a perfect world we'd have type 
> providers to make writing something like the ObjC importer but for a 
> different language or other dynamic data source something that doesn't 
> require invasive compiler hackery. The importer puts all of this:
> 
>> - It’s changing the compile-time name resolution! The Swift name is 
>> foo(bar:), but it’s changing that to fooWithBar:!
>> 
>> - It’s changing the signature! The argument took a String, but now it’s 
>> passing an NSString!
>> 
>> - It’s not resolving the method at compile-time! It’s passing the modified 
>> method name and the arg list to some objc_msgSend() function, which resolves 
>> it dynamically in a way that user code can intercept and interpret at 
>> runtime!
>> 
>> I’m just not seeing the conceptual difference here.
> 
> below the fold as far as the rest of the language is concerned. You could 
> just as well written what the importer synths up in Swift directly:
> 
> func foo(bar: String) {
>  unsafeBitCast(objc_msgSend, to: @convention(c) (AnyObject, Selector, 
> NSString) -> ().self)(self, "fooWithBar:", NSString(bar))
> }
> 
> and the rest of the language would be none the wiser.
> 
> -Joe
> ___
> 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] Random Unification

2017-09-26 Thread Susan Cheng via swift-evolution
First of all, I like this proposal.

For a empty RandomAccessCollection, is it cause a fatal error with calling the 
random methods?

> Alejandro Alonso via swift-evolution  於 2017年9月26日 
> 下午12:57 寫道:
> 
> Hello evolution,
> 
> I am very thankful for all the feedback, and I’ve been working on a design 
> that tries to utilize everybody’s ideas. The link to what I have so far is 
> here: https://gist.github.com/Azoy/15f0518df38df9b722d4cb17bafea4c1. Please 
> keep in mind this is just a design, no actual implementation as I would most 
> likely need assistance in doing. The default source for randomness will use 
> the OS’s unseeded CSPRNG. This current setup exposes developers to an API 
> that lets them create their own RandomSources on the fly. I want to make the 
> distinction that any existing or new sources of randomness that conform to 
> UnsafeRandomSource are to be considered non cryptographically secure.
> 
> I would love to get this discussion flowing again, and I would love input on 
> the design. A few things I came across with this design is that some may want 
> to use ranges as an argument for the numeric types, RandomAccessCollection 
> returning an optional when getting a random, and how to incorporate an API 
> that allows distributions. I wanted to get input on how you feel about each 
> of these topics as I’m indifferent about them all. I’m in no way saying this 
> is the design we should go for, but I’m simply providing something I think we 
> should build on or talk about.
> 
> - Alejandro
> 
>> On Sep 8, 2017, 11:52 AM -0500, Alejandro Alonso via swift-evolution 
>> , wrote:
>> Hello swift evolution, I would like to propose a unified approach to 
>> `random()` in Swift. I have a simple implementation here 
>> https://gist.github.com/Azoy/5d294148c8b97d20b96ee64f434bb4f5. This 
>> implementation is a simple wrapper over existing random functions so 
>> existing code bases will not be affected. Also, this approach introduces a 
>> new random feature for Linux users that give them access to upper bounds, as 
>> well as a lower bound for both Glibc and Darwin users. This change would be 
>> implemented within Foundation.
>> 
>> I believe this simple change could have a very positive impact on new 
>> developers learning Swift and experienced developers being able to write 
>> single random declarations.
>> 
>> I’d like to hear about your ideas on this proposal, or any implementation 
>> changes if need be.
>> 
>> - Alejando
>> 
> ___
> 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] Random Unification

2017-09-10 Thread Susan Cheng via swift-evolution
Hello,

I have an implementation for reference
https://github.com/SusanDoggie/Doggie/blob/master/Sources/Doggie/Foundation/Random.swift

It's easy to remind that what's the range of random floating point number

Double.random(includeOne: true)
Double.random(includeOne: false)

2017-09-09 0:52 GMT+08:00 Alejandro Alonso via swift-evolution
:
> Hello swift evolution, I would like to propose a unified approach to
> `random()` in Swift. I have a simple implementation here
> https://gist.github.com/Azoy/5d294148c8b97d20b96ee64f434bb4f5. This
> implementation is a simple wrapper over existing random functions so
> existing code bases will not be affected. Also, this approach introduces a
> new random feature for Linux users that give them access to upper bounds, as
> well as a lower bound for both Glibc and Darwin users. This change would be
> implemented within Foundation.
>
> I believe this simple change could have a very positive impact on new
> developers learning Swift and experienced developers being able to write
> single random declarations.
>
> I’d like to hear about your ideas on this proposal, or any implementation
> changes if need be.
>
> - Alejando
>
>
> ___
> 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] [Concurrency] async/await + actors

2017-08-19 Thread Susan Cheng via swift-evolution
 > Hi all,
>
> As Ted mentioned in his email, it is great to finally kick off
discussions for what concurrency should look like in Swift. This will
surely be an epic multi-year journey, but it is more important to find the
right design than to get there fast.
>
> I’ve been advocating for a specific model involving async/await and
actors for many years now. Handwaving only goes so far, so some folks asked
me to write them down to make the discussion more helpful and concrete.
While I hope these ideas help push the discussion on concurrency forward,
this isn’t in any way meant to cut off other directions: in fact I hope it
helps give proponents of other designs a model to follow: a discussion
giving extensive rationale, combined with the long term story arc to show
that the features fit together.
>
> Anyway, here is the document, I hope it is useful, and I’d love to hear
comments and suggestions for improvement:
> https://gist.github.com/lattner/31ed37682ef1576b16bca1432ea9f782
>
> -Chris
>
>
>

Hi chris,

is a actor guarantee always process the messages in one by one?
so, can it assume that never being multiple threads try to modify the state
at the same time?


P.S. i have implemented similar idea before:

https://github.com/SusanDoggie/Doggie/blob/master/Sources/Doggie/Thread/Thread.swift
https://github.com/SusanDoggie/Doggie/blob/master/Sources/Doggie/SDTriggerNode.swift
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Swift 5: start your engines

2017-08-08 Thread Susan Cheng via swift-evolution
is it accept proposal for coroutine?
Just like the one i had proposed before:
https://github.com/apple/swift-evolution/pull/73

2017-08-09 0:23 GMT+08:00 Ted Kremenek via swift-evolution <
swift-evolution@swift.org>:

> Hi everyone,
>
> The proposal phase for Swift 4 is now officially over, and the release is
> now in endgame engineering convergence for an expected release later this
> year.  Swift 4 has turned out to be one of the highest quality,
> well-rounded releases of Swift, and I am grateful to everyone in the
> community who made this release come together!
>
> Now it is time to turn our attention to Swift 5.  I have just posted
> updates to the README.md file on the swift-evolution repository, which
> outlines the core themes and focus areas for Swift 5:
>
>   https://github.com/apple/swift-evolution
>
> and a more persistent URL (invariant to future README.md changes):
>
>   https://github.com/apple/swift-evolution/blob/
> 9cc90f33b6659adeaf92355c359e34e6fed73254/README.md
>
> I am not going to repeat all of that information here, but I wanted to
> highlight a few important things.
>
> ## ABI Stability
>
> First, ABI stability is the center focus of Swift 5 — and we will pivot
> much of our prioritization of efforts for Swift 5 around it.  With Swift 4,
> ABI stability was a strong goal.  In Swift 5, it is a *requirement* of the
> release.  Whatever ABI we have at the end of Swift 5 is the ABI that we
> will have.  ABI stability is an important inflection point for the maturity
> of the language, and it cannot be delayed any longer.
>
> Please note that there is a difference between ABI stability and module
> stability.   If you are not aware of the difference — which is rather
> important — please read the first few paragraphs of the ABI stability
> manifesto:
>
>   https://github.com/apple/swift/blob/master/docs/ABIStabilityManifesto.md
>
> Module stability is a stretch goal for Swift 5, but even without module
> stability we can still achieve the primary value of ABI stability.
>
> ##  Other focus areas (including laying the groundwork for concurrency)
>
> There are several other areas mentioned for Swift 5 which I won’t repeat
> here, but there is a general theme of refining and broadening out the core
> ergonomics of the language and standard library.
>
> One of those that I wanted to highlight is laying the groundwork for
> concurrency.  It is a non-goal of Swift 5 to roll out a full new
> concurrency model.  That is simply too large an effort to do alongside ABI
> stability.  However, it is important that we start making progress on
> discussing the directions for concurrency and laying some of the
> groundwork.  This may take the form of specific enhancements to the
> language that get implemented, depending on where the discussions for
> concurrency lead and how they align with the priorities for delivering ABI
> stability in Swift 5.
>
> ## Changes to the language evolution process
>
> Last, I want to highlight important changes to the evolution process:
>
>   https://github.com/apple/swift-evolution#evolution-process-for-swift-5
> 
>
> With Swift 4, the release period was divided up into “stage 1” and “stage
> 2” for setting guidelines for the kind of evolution proposals that were in
> scope for the release.  This was needed to establish focus — especially
> after the churn we saw during Swift 3 — on some core themes that were
> aligned with converging the language towards source & ABI stability.  One
> downside is that “stage 2” opened up discussion for potentially disruptive
> changes fairly late in the release.  Further, some proposals — such as
> SE-0155 — came in so late that there was little runway to actually
> implement them for Swift 4, let alone evaluate their impact in practice on
> real projects.  Related, there has been some desire  for a while to be able
> to better evaluate the impact of proposals on real code before they are
> locked into the release, and the best way to do that is to actually have an
> implementation that vets out the design in a proposal.
>
> With Swift 5, the focus on ABI stability will predominate priorities for
> both design and implementation work, but the Core Team did not want that
> focus to stifle all discussion on potential enhancements to the language
> that were not fundamentally tied to that primary goal.  After reflecting on
> the evolution process during both the Swift 3 and Swift 4 releases, the
> Core Team felt that we could strike a balance with not diluting attention
> from ABI stability while still enabling a broader range of proposals
> compared to Swift 4 by **requiring that all proposals have an
> implementation** before they are officially reviewed by the Core Team.  An
> implementation can come long after an idea has been pitched and after a
> proposal has been written.  However, before a pull request for an evolution
> proposal will be accept

Re: [swift-evolution] [Proposal] Introduces endianness specific type

2017-07-10 Thread Susan Cheng via swift-evolution
Thanks, but we can implement Codable for BEInteger and LEInteger types.


public struct BEInteger : FixedWidthInteger
{



public var bitPattern: BitPattern



public init(bitPattern: BitPattern)



public var bigEndian: BEInteger { get }



public var littleEndian: LEInteger { get }

}


public struct LEInteger : FixedWidthInteger
{



public var bitPattern: BitPattern



public init(bitPattern: BitPattern)



public var bigEndian: BEInteger { get }



public var littleEndian: LEInteger { get }

}


extension BEInteger : Encodable where BitPattern : Encodable {



public func encode(to encoder: Encoder) throws {

try self.bitPattern.encode(to: encoder)

}

}


extension BEInteger : Decodable where BitPattern : Decodable {



public init(from decoder: Decoder) throws {

self.init(bitPattern: try BitPattern(from: decoder))

}

}


extension LEInteger : Encodable where BitPattern : Encodable {



public func encode(to encoder: Encoder) throws {

try self.bitPattern.encode(to: encoder)

}

}


extension LEInteger : Decodable where BitPattern : Decodable {



public init(from decoder: Decoder) throws {

self.init(bitPattern: try BitPattern(from: decoder))

}

}


2017-07-09 0:27 GMT+08:00 Chris Lattner :

> Hi Susan,
>
> Swift does not currently specify a layout for Swift structs.  You
> shouldn’t be using them for memory mapped i/o or writing to a file, because
> their layout can change.  When ABI stability for fragile structs lands, you
> will be able to count on it, but until then something like this is probably
> a bad idea.
>
> -Chris
>
> On Jul 7, 2017, at 6:16 PM, Susan Cheng via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> Here are two problems being fixed.
>
> First, considering the example:
>
> struct MyRawDataStruct {
>
>   var size: UInt32
>   var signature: UInt32
>   var width: UInt32
>   var height: UInt32
> }
>
> The type UInt32 doesn't tall us the endianness of the value. Also, if we
> read the value of it, the value is being byte-swapped when endianness is
> not matching with the system.
>
> This causes us have to manual convert the value from/to correct endianness.
>
> struct MyRawDataStruct {
>
>   var size: BEInteger
>   var signature: BEInteger
>   var width: BEInteger
>   var height: BEInteger
> }
>
> So, my proposal fix the problem. We can easily to get the value.
>
> let header: MyRawDataStruct = data.withUnsafePointer { $0.pointee }
>
> print(header.size)  // print the representing value
>
> Second, it's misleading means of bigEndian and littleEndian from
> FixedWidthInteger
>
> if we do this
>
> let a = 1
>
> print(a.bigEndian.bigEndian)
>
> It's just swap bytes twice but not converting value to big-endian
>
> My proposal solves the problem
>
> let b = a.bigEndian   //BEInteger
>
> b.bigEndian// remain big-endian of a
>
> Max Moiseev  於 2017年7月8日 上午1:48 寫道:
>
> Hi Susan,
>
> Was there any motivation for this proposal that I missed? If not then, can
> you please provide it in a few sentences? Otherwise it’s not clear to me
> what problem it is supposed to fix.
>
> Thanks,
> Max
>
>
> On Jul 6, 2017, at 8:21 PM, Susan Cheng via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> IMO, it has unclear representation when FixedWidthInteger working with
> endianness specific type.
>
> so I want to introduce the endianness specific wrapper:
>
> public struct BEInteger : FixedWidthInteger {
>
> public var bigEndian: BEInteger { get }
>
> public var littleEndian: LEInteger { get }
> }
>
> public struct LEInteger : FixedWidthInteger {
>
> public var bigEndian: BEInteger { get }
>
> public var littleEndian: LEInteger { get }
> }
>
> also, we should change the FixedWidthInteger as follow:
>
> public protocol FixedWidthInteger : BinaryInteger {
>
> /// deprecated, we should use value.bigEndian instead
> init(bigEndian value: Self)
>
> /// deprecated, we should use value.littleEndian instead
> init(littleEndian value: Self)
>
> associatedtype EndianRepresentingValue : FixedWidthInteger
>
> var bigEndian: BEInteger { get }
>
> var littleEndian: LEInteger { get }
>
> }
>
> =
>
> this is my working alternative implementation:
>
>
> @_versioned
> protocol EndianInteger : FixedWidthInteger {
>
> associatedtype BitPattern : FixedWidthInteger
>
> associatedtype RepresentingValue : FixedWidthInteger
>
> var bitPattern: BitPattern { get }
>
> init(

Re: [swift-evolution] [Proposal] Introduces endianness specific type

2017-07-07 Thread Susan Cheng via swift-evolution
Here are two problems being fixed.

First, considering the example:

struct MyRawDataStruct {

  var size: UInt32
  var signature: UInt32
  var width: UInt32
  var height: UInt32
}

The type UInt32 doesn't tall us the endianness of the value. Also, if we read 
the value of it, the value is being byte-swapped when endianness is not 
matching with the system.

This causes us have to manual convert the value from/to correct endianness.

struct MyRawDataStruct {

  var size: BEInteger
  var signature: BEInteger
  var width: BEInteger
  var height: BEInteger
}

So, my proposal fix the problem. We can easily to get the value.

let header: MyRawDataStruct = data.withUnsafePointer { $0.pointee }

print(header.size)  // print the representing value

Second, it's misleading means of bigEndian and littleEndian from 
FixedWidthInteger

if we do this

let a = 1

print(a.bigEndian.bigEndian)

It's just swap bytes twice but not converting value to big-endian

My proposal solves the problem

let b = a.bigEndian   //BEInteger

b.bigEndian// remain big-endian of a

> Max Moiseev  於 2017年7月8日 上午1:48 寫道:
> 
> Hi Susan,
> 
> Was there any motivation for this proposal that I missed? If not then, can 
> you please provide it in a few sentences? Otherwise it’s not clear to me what 
> problem it is supposed to fix.
> 
> Thanks,
> Max 
> 
> 
>> On Jul 6, 2017, at 8:21 PM, Susan Cheng via swift-evolution 
>>  wrote:
>> 
>> IMO, it has unclear representation when FixedWidthInteger working with 
>> endianness specific type.
>> 
>> so I want to introduce the endianness specific wrapper:
>> 
>> public struct BEInteger : FixedWidthInteger {
>> 
>> public var bigEndian: BEInteger { get }
>> 
>> public var littleEndian: LEInteger { get }
>> }
>> 
>> public struct LEInteger : FixedWidthInteger {
>> 
>> public var bigEndian: BEInteger { get }
>> 
>> public var littleEndian: LEInteger { get }
>> }
>> 
>> also, we should change the FixedWidthInteger as follow:
>> 
>> public protocol FixedWidthInteger : BinaryInteger {
>> 
>> /// deprecated, we should use value.bigEndian instead
>> init(bigEndian value: Self)
>> 
>> /// deprecated, we should use value.littleEndian instead
>> init(littleEndian value: Self)
>> 
>> associatedtype EndianRepresentingValue : FixedWidthInteger
>> 
>> var bigEndian: BEInteger { get }
>> 
>> var littleEndian: LEInteger { get }
>> }
>> 
>> =
>> 
>> this is my working alternative implementation:
>> 
>> 
>> @_versioned
>> protocol EndianInteger : FixedWidthInteger {
>> 
>> associatedtype BitPattern : FixedWidthInteger
>> 
>> associatedtype RepresentingValue : FixedWidthInteger
>> 
>> var bitPattern: BitPattern { get }
>> 
>> init(bitPattern: BitPattern)
>> 
>> var representingValue : RepresentingValue { get set }
>> 
>> init(representingValue: RepresentingValue)
>> }
>> 
>> extension EndianInteger {
>> 
>> @_transparent
>> public init(integerLiteral value: RepresentingValue.IntegerLiteralType) {
>> self.init(representingValue: RepresentingValue(integerLiteral: 
>> value))
>> }
>> 
>> @_transparent
>> public init?(exactly source: T) where T : BinaryInteger {
>> guard let value = RepresentingValue(exactly: source) else { return 
>> nil }
>> self.init(representingValue: value)
>> }
>> 
>> @_transparent
>> public init?(exactly source: T) where T : FloatingPoint {
>> guard let value = RepresentingValue(exactly: source) else { return 
>> nil }
>> self.init(representingValue: value)
>> }
>> 
>> @_transparent
>> public init(_ value: RepresentingValue) {
>> self.init(representingValue: value)
>> }
>> 
>> @_transparent
>> public init(_ source: T) where T : FloatingPoint {
>> self.init(representingValue: RepresentingValue(source))
>> }
>> 
>> @_transparent
>> public init(_ source: T) where T : BinaryInteger {
>> self.init(representingValue: RepresentingValue(source))
>> }
>> 
>> @_transparent
>> public init(extendingOrTruncating source: T) where T : BinaryInteger {
>> self.init(representingValue: 
>> Repre

[swift-evolution] [Proposal] Introduces endianness specific type

2017-07-06 Thread Susan Cheng via swift-evolution
IMO, it has unclear representation when FixedWidthInteger working with
endianness specific type.


so I want to introduce the endianness specific wrapper:


public struct BEInteger : FixedWidthInteger {



public var bigEndian: BEInteger { get }



public var littleEndian: LEInteger { get }

}


public struct LEInteger : FixedWidthInteger {



public var bigEndian: BEInteger { get }



public var littleEndian: LEInteger { get }

}


also, we should change the FixedWidthInteger as follow:


public protocol FixedWidthInteger : BinaryInteger {



/// deprecated, we should use value.bigEndian instead

init(bigEndian value: Self)



/// deprecated, we should use value.littleEndian instead

init(littleEndian value: Self)



associatedtype EndianRepresentingValue : FixedWidthInteger



var bigEndian: BEInteger { get }



var littleEndian: LEInteger { get }

}

=


this is my working alternative implementation:



@_versioned

protocol EndianInteger : FixedWidthInteger {



associatedtype BitPattern : FixedWidthInteger



associatedtype RepresentingValue : FixedWidthInteger



var bitPattern: BitPattern { get }



init(bitPattern: BitPattern)



var representingValue : RepresentingValue { get set }



init(representingValue: RepresentingValue)

}


extension EndianInteger {



@_transparent

public init(integerLiteral value: RepresentingValue.IntegerLiteralType)
{

self.init(representingValue: RepresentingValue(integerLiteral:
value))

}



@_transparent

public init?(exactly source: T) where T : BinaryInteger {

guard let value = RepresentingValue(exactly: source) else { return
nil }

self.init(representingValue: value)

}



@_transparent

public init?(exactly source: T) where T : FloatingPoint {

guard let value = RepresentingValue(exactly: source) else { return
nil }

self.init(representingValue: value)

}



@_transparent

public init(_ value: RepresentingValue) {

self.init(representingValue: value)

}



@_transparent

public init(_ source: T) where T : FloatingPoint {

self.init(representingValue: RepresentingValue(source))

}



@_transparent

public init(_ source: T) where T : BinaryInteger {

self.init(representingValue: RepresentingValue(source))

}



@_transparent

public init(extendingOrTruncating source: T) where T : BinaryInteger
 {

self.init(representingValue: RepresentingValue(extendingOrTruncating:
source))

}



@_transparent

public init(clamping source: T) where T : BinaryInteger {

self.init(representingValue: RepresentingValue(clamping: source))

}



@_transparent

public init(_truncatingBits bits: UInt) {

self.init(representingValue: RepresentingValue(_truncatingBits:
bits))

}

}


extension EndianInteger {



@_transparent

public static var isSigned: Bool {

return RepresentingValue.isSigned

}



@_transparent

public static var bitWidth: Int {

return RepresentingValue.bitWidth

}



@_transparent

public static var max: Self {

return Self(representingValue: RepresentingValue.max)

}



@_transparent

public static var min: Self {

return Self(representingValue: RepresentingValue.min)

}

}


extension EndianInteger {



@_transparent

public var hashValue: Int {

return representingValue.hashValue

}



@_transparent

public var description: String {

return representingValue.description

}



@_transparent

public var bitWidth: Int {

return representingValue.bitWidth

}



@_transparent

public var magnitude: RepresentingValue.Magnitude {

return representingValue.magnitude

}



@_transparent

public var trailingZeroBitCount: Int {

return representingValue.trailingZeroBitCount

}



@_transparent

public var nonzeroBitCount: Int {

return representingValue.nonzeroBitCount

}



@_transparent

public var leadingZeroBitCount: Int {

return representingValue.leadingZeroBitCount

}



@_transparent

public var byteSwapped: Self {

return Self(representingValue: representingValue.byteSwapped)

}

}


extension EndianInteger {



@_transparent

public func _word(at n: Int) -> UInt {

return representingValue._word(at: n)

}



@_transparent

public func distance(to other: Self) -> RepresentingValue.Stride {

return self.representingValue.distance(to: other.representingValue)

}



@_transparent

public func advanced(by n: RepresentingValue.Stride) -> Self {

return Self(representingValue: self.representingValue.advanced(by:
n))

}



@_transparent

public func addingReportingOverflow(_ rhs: S

Re: [swift-evolution] History and future of Swift's parentheses

2017-06-09 Thread Susan Cheng via swift-evolution
It may make things more terrible. The solution introduces two separated type 
system and one is Swift 3 mode for asterisk syntax.

> Robert Bennett via swift-evolution  於 2017年6月10日 
> 上午6:02 寫道:
> 
> I see. My ideal solution to this would be an explicit tuple packing and 
> unpacking API, as opposed to implicitly flexible functions. Something akin to 
> (borrowing Python’s asterisk syntax):
> 
> func compose(_ g: (*U)->*V, _ f: (*T)->*U) -> (*T)->*V {...}
> 
> The asterisks indicate that the arguments to the function will be packed into 
> a tuple (or not, in the case of a single-argument function) whose type is 
> denoted by T, U, V, or conversely that the functions take/return argument 
> lists that look like *T, *U, *V where T, U, V are tuple types. Then the 
> function definition would look like
> 
> {
> return { x: *T in g(f(x)) }
> }
> 
> This would in essence create a new non nominal type: function argument lists. 
> These would be distinct from tuples, although the two may freely be converted 
> into one another using the asterisk. This type would be structurally distinct 
> from tuples by virtue of the fact that single-element argument lists exist 
> while single-element tuples do not. (An asterisk will convert a 
> single-element argument list into a single (non-tuple) element and vice 
> versa.)
> 
> To users, argument lists would be accessed solely through tuples with the 
> asterisk syntax. The identity **T == T would hold whenever T is a tuple or 
> argument list. Their usefulness would lie in the ability to call f(*x) when f 
> takes multiple arguments and x is a tuple.
> 
> I acknowledge that this is probably not going to happen for Swift 4 but I 
> would sure like it if it did.
> 
>> On Jun 9, 2017, at 5:10 PM, Jens Persson via swift-evolution 
>>  wrote:
>> 
>> The point of exercise 1 is to show that it is impossible (in Swift 4) to 
>> write a generic function composition operator (or function) which works as 
>> expected for any reasonable functions.
>> This was possible in Swift 3, but in Swift 4 it will only work for functions 
>> with exactly one parameter. You'd have to special-case it for every 
>> combination of parameter counts of f and g that it should be able to handle.
>> 
>> The following program demonstrates how it can be done in Swift 3.1 and 3.2:
>> 
>> func compose(_ g: @escaping (U) -> V, _ f: @escaping (T) -> U) -> 
>> (T) -> V {
>> return { x in g(f(x)) }
>> }
>> func sum(_ a: Int, _ b: Int) -> Int { return a + b }
>> func square(_ a: Int) -> Int { return a * a }
>> let squaredSum = compose(square, sum)
>> let result = squaredSum((3, 4)) // A bit unexepected with a tuple here but 
>> ok ...
>> print(result) // 49
>> // Well, it worked, not flawlessly but we did manage to write
>> // a function composition function and we composed sum
>> // and square, and we could call it and get a correct result.
>> 
>>  
>> And this program demonstrates what happens if you try it in Swift 4:
>> 
>> func compose(_ g: @escaping (U) -> V, _ f: @escaping (T) -> U) -> 
>> (T) -> V {
>> return { x in g(f(x)) }
>> }
>> func sum(_ a: Int, _ b: Int) -> Int { return a + b }
>> func square(_ a: Int) -> Int { return a * a }
>> // let squaredSum = compose(square, sum) // Error! (without the 
>> compose-variant below)
>> 
>> // The error message is:
>> // Cannot convert value of type `(Int, Int) -> Int` to
>> // expected argument type `(_) -> _`
>> 
>> // That's it, it is simply not possible!
>> 
>> // You'd have to write special variants of the compose func for every 
>> combination
>> // of parameter counts! For example, in order to get this sum and square
>> // example working, this specific variant must be written:
>> func compose(_ g: @escaping (V) -> W, _ f: @escaping (T, U) -> 
>> V) -> (T, U) -> W {
>> return { (x, y) in g(f(x, y)) }
>> }
>> // Now it will work:
>> let squaredSum = compose(square, sum)
>> // But only thanks to that awfully specific compose func variant ...
>> // We would have to write a lot more variants for it to be practically 
>> usable on pretty much any common function.
>> 
>> I'm sure some will say:
>> "no regular developers use function composition anyway so why ..."
>> or
>> "It's not very swifty to use free functions and higher order functions like 
>> that."
>> 
>> My answer is that this is just a simple but telling example. The issue (as I 
>> see it) exists in all situations involving generics and function types.
>> 
>> I'm a regular programmer and I like to be able to write basic, useful 
>> abstractions.
>> It's no fun when the language forces you to write lots of specific variants 
>> of your generic code.
>> 
>> I would feel less worried about the parentheses situation if the language 
>> was going in a direction where you could see how this simple exercise would 
>> be a no brainer.
>> 
>> Can Swift's parentheses-situation be sorted out before ABI stability?
>> Otherwise it would be a bit like if Swift had kept the special rule for the 
>>

Re: [swift-evolution] Proposal: Always flatten the single element tuple

2017-06-08 Thread Susan Cheng via swift-evolution

> Vladimir.S via swift-evolution  於 2017年6月9日 上午5:05 
> 寫道:
> 
> On 08.06.2017 21:17, Gwendal Roué via swift-evolution wrote:
>>> Le 8 juin 2017 à 19:40, Brent Royal-Gordon via swift-evolution 
>>> mailto:swift-evolution@swift.org>> a écrit :
>>> 
 On Jun 7, 2017, at 3:03 AM, Adrian Zubarev via swift-evolution 
 mailto:swift-evolution@swift.org>> wrote:
 
 Well please no:
 
> |let fn2: ((Int, Int)) -> Void = { lhs, rhs in }|
 
 Instead use destructuring sugar pitched by Chris Lattner on the other 
 thread:
 
 |let fn2: ((Int, Int)) -> Void = { ((lhs, rhs)) in }|
 
>>> I think this suggestion is better than the status quo. I'm wondering, 
>>> though, if we should just drop the outer set of parentheses entirely, 
>>> unless you're also putting types on the parameters. That is, a closure of 
>>> type `(Int, Int) -> T` can look like this:
>>> 
>>> { (x: Int, y: Int) in … }
>>> 
>>> Or it can look like this:
>>> 
>>> { x, y in … }
>>> 
>>> But it *cannot* look like this:
>>> 
>>> { (x, y) in … }
>>> 
>>> The `(x, y)` form can instead be a closure of a type like `((Int, Int)) -> 
>>> T`, which immediately destructures the tuple parameter into separate 
>>> constants.
>>> 
>>> -- 
>>> Brent Royal-Gordon
>>> Architechies
>> Hello,
>> There's a difference, in the mind of people here that try to show how bad 
>> were the recent changes, between:
>> 1: closures defined independently
>> 2: closures given as a parameter to a function.
>> I think that we all agree that the type of a closure that is defined 
>> independently should be well defined:
>> // Choose between (Int, Int) -> () or ((x: Int, y: Int)) -> ()
>> leta = { (x: Int, y: Int) -> Intin... }
>> letb = { ((x: Int, y: Int)) -> Intin... }
>> However, when a closure is given as an argument of a function that expects a 
>> closure, we ask for the maximum possible flexibility, as Swift 3 did:
>> funcwantsTwoArguments(_closure: (Int, Int) -> Int) { closure(1, 2) }
>> wantsTwoArguments{ a, b ina + b }
>> wantsTwoArguments{ (a, b) ina + b }
>> wantsTwoArguments{ t int.0+ t.1} // OK, maybe not
>> funcwantsATupleArgument(_closure: ((Int, Int)) -> Int) { closure((1, 2)) }
>> wantsATupleArgument{ a, b ina + b }
>> wantsATupleArgument{ (a, b) ina + b }
>> wantsATupleArgument{ t int.0+ t.1}
>> funcwantsANamedTupleArgument(_closure: ((lhs: Int, rhs: Int)) -> Int) { 
>> closure((lhs: 1, rhs: 2)) }
>> wantsANamedTupleArgument{ a, b ina + b }
>> wantsANamedTupleArgument{ (a, b) ina + b }
>> wantsANamedTupleArgument{ t int.lhs + t.rhs }
> 
> It's nice to see that we are agreed that func/closures declared separately 
> should have clearly defined type and (at least for now) can't be 
> interchangeable.
> 
> And personally I agree that this could be a solution to migration problem, 
> compiler can generate closure of correct(requested) type if such closure:
> 1. declared inplace of func call as parameter of that func
> 2. has no type annotations for its arguments
> 3. (probably, can discuss) has no parenthesis for its arguments, because one 
> pair of parenthesis in argument list declares closure of type (list of 
> arguments)->T in other situations.
> 
> So, we can have
> 
> wantsTwoArguments{ a, b in a + b } // (Int,Int)->() will be generated
> wantsTwoArguments{ (a, b) in a + b } // syntax of (Int,Int)->() closure
> 
> wantsATupleArgument{ a, b in a + b } // ((Int,Int))->() will be generated
> wantsATupleArgument{ t in t.0+ t.1 } // syntax of ((Int,Int))->() closure
> 
> wantsANamedTupleArgument{ a, b in a + b } // ((Int,Int))->() will be generated
> wantsANamedTupleArgument{ t in t.lhs + t.rhs } // syntax of ((Int,Int))->() 
> closure

That's what Swift 3 has done now, but forbidden by Swift 4. Isn't it?

> So, { a,b in ...} will be a special syntax for closure which type will be 
> defined by compiler by type of func's parameter.
> 
> The question is if community and core team will support this idea, if that 
> idea is better than other ideas like {((a,b)) in ..} for tuple 
> deconstruction, and if this could be implemented before Swift 4 release.
> 
>> *This gives us the ability to deal with unfitted function signatures.* For 
>> example, most Dictionary methods. Yes, they are usually unfitted:
>> extensionDictionary{
>> funcforEach(_body: ((key: Key, value: Value)) throws-> Void) rethrows
>> }
>> Who cares about this named (key:value:) tuple? Absolutely nobody, as 
>> exemplified by this remarquable Swift 3 snippet below, where no tuple, no 
>> `key`, and no `value` is in sight:
>> letscores: [String: Int] = ... // [playerName: score]
>> scores.forEach { name, score in
>> print("\(name): \(score)")
>> }
>> Do you see?
> 
>let scores: [String: Int] = ["a":1, "b":2]
> 
>scores.forEach { (score: (name:String, value:Int)) in
>print("\(score.name): \(score.value)")
>}
> 
> I'm not saying that this syntax as good as in your example, but it is not as 
> bad/ugly as you say.
> 
>> Gwendal
>> 

Re: [swift-evolution] Pitch: Support for map and flatMap with smart key paths

2017-06-07 Thread Susan Cheng via swift-evolution
this work,


prefix operator *


prefix func *(keyPath: KeyPath) -> (Root) -> Value
{

return { $0[keyPath: keyPath] }

}


["Hello, World"].map(*\String.count)// [12]


2017-06-08 12:19 GMT+08:00 Paul Cantrell via swift-evolution <
swift-evolution@swift.org>:

> It should be possible to achieve Ruby-like generality in Swift with a
> protocol for “thing that can converted to a transform function.” That
> wouldn’t need a special & operator.
>
> Here’s a sketch. This sketch doesn’t compile — maybe not enough of Swift 4
> is there yet for it to work, or maybe I am missing something obvious and
> need to go to sleep now — but it’s close enough to suggest the approach:
>
> public protocol TransformConvertible {  // or whatever you want to
> call it
>   associatedtype From
>   associatedtype To
>
>
>   var transform: (From) -> To { get }
> }
>
> extension KeyPath: TransformConvertible {
>   public typealias From = Root
>   public typealias To = Value
>
>
>   public var transform: (Root) -> Value {
> return { $0[keypath: self] }
>   }
> }
>
> extension Sequence {
>   public func map(_ transformSource: U) -> [T]
>where U: TransformConvertible,
>  U.From == Element,
>  U.To == T {
> return map(transformSource.transform)
>   }
> }
>
> This seems a bit more ambitious, perhaps not suitable for this round of
> Swift evolution work. But I throw it out there at least to show that
> supporting people.map(\.firstName) today *would not preclude* a generic
> keypath → function mechanism in the future:
>
>
>- A flavor of map that accepts a keypath today could be generalized to
>accept TransformConvertible in the future without breaking existing code.
>- When calling a function that doesn’t know how to work
>with TransformConvertible, you could use (Foo.bar).transform, no special
>operator needed.
>
>
> Cheers,
>
> Paul
>
> P.S. Largely irrelevant Ruby aside: Ruby’s & is not a free-floating
> operator, but part of the method invocation syntax indicating that the
> following arg should be treated as a block. Ruby calls a to_proc method on
> whatever is in that position. Symbol implements to_proc by returning a
> lambda that calls the method named by the symbol on the lambda’s first arg.
> Very much the duck-typed version of TransformConvertible above.
>
>
> On Jun 7, 2017, at 10:21 PM, Stephen Celis via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> -1
>
> A -1 from me may be surprising. I'm excited about key path composition and
> generic solutions, e.g. this experiment with lenses: https://twitter.com/
> stephencelis/status/863916921577758721
>
> But I'd prefer a reusable solution for converting key paths into functions.
>
> Heaven help me for this Rubyism, but a prefix "&" operator (or, maybe
> better yet, some implicit mechanism) could convert a key-path to a function
> that passes a root value to a key path...
>
>   people.map(&\.firstName)
>
> This way any function that takes a transformation from "whole" to "part"
> could take a key path. Requiring an overload per instance is less flexible.
>
> Stephen
>
> On Jun 7, 2017, at 10:58 PM, Tony Allevato via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> +1, I really like this. It would also align nicely with the method type
> flattening in SE-0042 (once it gets implemented), because passing keypaths
> (i.e., unbound property references) and unbound parameterless method
> references to map/flatMap would look nearly the same:
>
> ```
> struct Person {
>  let firstName: String
>  let lastName: String
>  func fullName() -> String { return "\(firstName) \(lastName)" }
> }
>
> let people: [Person]
> let firstNames = people.map(\.firstName)
> let fullNames = people.map(Person.fullName)  // because after SE-0042,
> this will be (Person) -> String, not (Person) -> () -> String
> ```
>
> Especially if there's a move in the future to also use \. to denote
> unbound methods references, which was discussed during the keypath reviews.
> (Even with that, I believe it would be more work though to get rid of the
> explicit type name in the function case.)
>
>
> On Wed, Jun 7, 2017 at 6:11 PM Xiaodi Wu via swift-evolution <
> swift-evolution@swift.org> wrote:
> +1. Would think that all variants should exist on Optional too unless it
> would be harmful.
> On Wed, Jun 7, 2017 at 20:13 Michael J LeHew Jr via swift-evolution <
> swift-evolution@swift.org> wrote:
> This is a great idea, and ought to be easy enough to bring forward!  +1
> from me!
>
> -Michael
>
> On Jun 7, 2017, at 11:18 AM, Matt Diephouse via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> 💯
>
> On Jun 7, 2017, at 10:35 AM, Adam Sharp via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> The new smart key path feature is really lovely, and feels like a great
> addition to Swift.
>
> It seems like it might be straightforward to add overloads of `m

Re: [swift-evolution] Proposal: Always flatten the single element tuple

2017-06-07 Thread Susan Cheng via swift-evolution
that makes sense to me ;P

2017-06-08 12:07 GMT+08:00 Gwendal Roué :

> Le 8 juin 2017 à 05:15, Susan Cheng via swift-evolution <
> swift-evolution@swift.org> a écrit :
>
> Just a thought
>
> if parentheses is important, why the tuples are not?
>
> var tuple1: (Int, Int) = (0, 0)
> var tuple2: Int, Int = (0, 0)
>
> type(of: tuple1) == type(of: tuple2)// true
>
> var void: ((())) = ()
>
> type(of: void) == type(of: Void())  // true
>
>
> I think is is because Swift doesn't have tuples with a single value: those
> parenthesis are just parenthesis around an expression:
>
> let a = 1 + 2
> let b = (1 + 2)
> let c = (1 + 2) * 3
> let d = ((1 + 2)) * 3
>
> Many languages behave like that, Swift is no exception.
>
> It also allows some fancy/legacy/foreign programming styles :-)
>
> // C-style if
> if (a && b) {
> ...
> }
> // "return function"
> return(a && b)
>
> Languages that have single-valued tuples need a special syntax so that
> they are distinguished from parenthesised expressions. In Python, this is a
> trailing comma:
>
> 1# 1
> (1)  # 1
> (1,) # (1,)
>
> Swift currently disallows trailing commas inside parenthesis.
>
> Gwendal
>
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Proposal: Always flatten the single element tuple

2017-06-07 Thread Susan Cheng via swift-evolution
if it's necessary to distinct argument list and tuple, what about the enum?


enum Foo {

case tuple(a: Int, b: Int)

}


let tuple = Foo.tuple((1, 2))


if case let .tuple(a, b) = tuple {



(a, b)//  (1, 2)

}


if case let .tuple(tuple) = tuple {



tuple//  (1, 2)

}




2017-06-08 11:36 GMT+08:00 Xiaodi Wu :

> On Wed, Jun 7, 2017 at 10:15 PM, Susan Cheng via swift-evolution <
> swift-evolution@swift.org> wrote:
>
>> Just a thought
>>
>> if parentheses is important, why the tuples are not?
>>
>
> It is not parentheses that are important; it is the distinction between an
> argument list and a tuple. They both happen to be written with parentheses.
>
> var tuple1: (Int, Int) = (0, 0)
>>
>> var tuple2: Int, Int = (0, 0)
>>
>>
>> type(of: tuple1) == type(of: tuple2)// true
>>
>>
>> var void: ((())) = ()
>>
>>
>> type(of: void) == type(of: Void())  // true
>>
>>
>> 2017-06-07 10:15 GMT+08:00 Susan Cheng :
>>
>>> Introduction
>>>
>>> Because the painful of SE-0110, here is a proposal to clarify the tuple
>>> syntax.
>>>
>>> Proposed solution
>>> 1. single element tuple always be flattened
>>>
>>> let tuple1: (((Int))) = 0  // TypeOf(tuple1) == Int
>>>
>>>
>>> let tuple2: Int))), Int) = (0, 0)  // TypeOf(tuple2) == (Int, Int)
>>>
>>> 2. function arguments list also consider as a tuple, which means the
>>> function that accept a single tuple should always be flattened.
>>>
>>> let fn1: (Int, Int) -> Void = { _, _ in }
>>>
>>>
>>> let fn2: ((Int, Int)) -> Void = { _, _ in }  // always flattened
>>>
>>> let fn3: (Int, Int) -> Void = { _ in }  // not allowed, here are two
>>> arguments
>>>
>>> let fn4: ((Int, Int)) -> Void = { _ in }  // not allowed, here are two
>>> arguments
>>>
>>>
>>
>> ___
>> 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: Always flatten the single element tuple

2017-06-07 Thread Susan Cheng via swift-evolution
Just a thought

if parentheses is important, why the tuples are not?


var tuple1: (Int, Int) = (0, 0)

var tuple2: Int, Int = (0, 0)


type(of: tuple1) == type(of: tuple2)// true


var void: ((())) = ()


type(of: void) == type(of: Void())  // true


2017-06-07 10:15 GMT+08:00 Susan Cheng :

> Introduction
>
> Because the painful of SE-0110, here is a proposal to clarify the tuple
> syntax.
>
> Proposed solution
> 1. single element tuple always be flattened
>
> let tuple1: (((Int))) = 0  // TypeOf(tuple1) == Int
>
>
> let tuple2: Int))), Int) = (0, 0)  // TypeOf(tuple2) == (Int, Int)
>
> 2. function arguments list also consider as a tuple, which means the
> function that accept a single tuple should always be flattened.
>
> let fn1: (Int, Int) -> Void = { _, _ in }
>
>
> let fn2: ((Int, Int)) -> Void = { _, _ in }  // always flattened
>
> let fn3: (Int, Int) -> Void = { _ in }  // not allowed, here are two
> arguments
>
> let fn4: ((Int, Int)) -> Void = { _ in }  // not allowed, here are two
> arguments
>
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Proposal: Always flatten the single element tuple

2017-06-07 Thread Susan Cheng via swift-evolution
`((Int, Int)) -> Void` will be same type as `(Int, Int) -> Void`

2017-06-07 18:09 GMT+08:00 Adrian Zubarev :

> Keep in mind there is also SE–0111 cometary which promises sugar for
> parameter labels for closures:
>
> // **
> let foo(tuple:): ((Int, Int)) -> Void
>
> // Sugar for **
> let foo: (tuple: (Int, Int)) -> Void
>
> What will happen if you’d always flatten here?
>
>
>
> --
> Adrian Zubarev
> Sent with Airmail
>
> Am 7. Juni 2017 um 12:03:08, Adrian Zubarev (adrian.zubarev@devandartist.
> com) schrieb:
>
> Well please no:
>
> let fn2: ((Int, Int)) -> Void = { lhs, rhs in }
>
> Instead use destructuring sugar pitched by Chris Lattner on the other
> thread:
>
> let fn2: ((Int, Int)) -> Void = { ((lhs, rhs)) in }
>
> That’s a correct error:
>
> let fn3: (Int, Int) -> Void = { _ in }
>
> This should be allowed, because we might want to work with the whole tuple
> and not a desctructured elements only:
>
> let fn4: ((Int, Int)) -> Void = { tuple in }
>
>
>
> --
> Adrian Zubarev
> Sent with Airmail
>
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Proposal: Always flatten the single element tuple

2017-06-07 Thread Susan Cheng via swift-evolution
Replacement for fn4 is just make a tuple inside the closure

let workWithTuple: (Int, Int) -> Void = { doSomething(withTuple: ($0, $1)) }

2017-06-07 18:03 GMT+08:00 Adrian Zubarev :

> Well please no:
>
> let fn2: ((Int, Int)) -> Void = { lhs, rhs in }
>
> Instead use destructuring sugar pitched by Chris Lattner on the other
> thread:
>
> let fn2: ((Int, Int)) -> Void = { ((lhs, rhs)) in }
>
> That’s a correct error:
>
> let fn3: (Int, Int) -> Void = { _ in }
>
> This should be allowed, because we might want to work with the whole tuple
> and not a desctructured elements only:
>
> let fn4: ((Int, Int)) -> Void = { tuple in }
>
>
>
> --
> Adrian Zubarev
> Sent with Airmail
>
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Proposal: Always flatten the single element tuple

2017-06-07 Thread Susan Cheng via swift-evolution
Argument lists should or shouldn't be tuples. I think the question likes a
concept more than a technical question.

2017-06-07 14:56 GMT+08:00 Xiaodi Wu :

> On Wed, Jun 7, 2017 at 01:51 Susan Cheng  wrote:
>
>> I don't think it's a roll back change.
>>
>
> Function argument lists were once tuples, but they have not been for many
> years. All of the proposals I listed above proceed on the basis that these
> are not the same. Your proposal says that function argument lists should be
> tuples: that is rolling back a >5 year old change, is it not?
>
> The proposal is not proposing allow to reorder the parameters by using the
>> tuple or implicit tuple splat to fit the function parameters.
>> It's just clarify the relationship of tuples and argument lists.
>>
>> as the grammar of Swift 3, it's allowed wrapping the argument with a
>> single tuple to a function with two argument.
>>
>> [(1, 2)].map(+)
>>
>> and SE-0110 is the proposal make the distinguished and not allowed this
>> line of code.
>>
>> although we fix the compiler to accept the destructuring of tuples
>>
>> [(1, 2)].map({ ((lhs, rhs)) in lhs + rhs })
>>
>> it's not accepting the code of [(1, 2)].map(+) which the operator + are
>> not function with accepting the tuple of two elements.
>>
>> the only way we can thought is that the arguments with single tuple is
>> flattened and it's most compatible with Swift 3.
>>
>> 2017-06-07 13:05 GMT+08:00 Xiaodi Wu :
>>
>>> This is not what was meant during discussion about re-evaluating
>>> SE-0110. Tuples already behave as described, but function argument lists
>>> are not tuples and have not been for a very long time: see SE-0029, SE-0066.
>>>
>>> Also, consider SE-0046, which makes possible labels in single-argument
>>> argument lists (not possible in tuples), and SE-0060, which prohibits
>>> arbitrary reordering (although still possible in tuples). This is to say
>>> that the whole direction of Swift since version 2 has been to erase the
>>> historical relationship between tuples and argument lists.
>>>
>>> The question is how to accommodate some common use cases for
>>> destructuring as a matter of syntactic sugar after having carefully
>>> distinguished argument lists and tuples in the compiler, which is a given,
>>> not how to roll back a change that was settled in 2011, by Chris’s telling.
>>>
>>> On Tue, Jun 6, 2017 at 23:14 Susan Cheng via swift-evolution <
>>> swift-evolution@swift.org> wrote:
>>>
>>>>
>>>> func add2(_ pair: (Int, Int)) -> Int {
>>>> return pair.0 + pair.1
>>>> }
>>>>
>>>> consider the follows
>>>>
>>>> let _add2 =  add2 // add2 have the typeof `((Int, Int)) -> Int`,
>>>> it should flatten to `(Int, Int) -> Int`
>>>>
>>>> so these two lines are also acceptable
>>>> [(1, 2)].map(add1)
>>>> [(1, 2)].map(add2)
>>>>
>>>> this proposal is not just changing the behaviour of closure, this
>>>> proposal also changing the tuple type
>>>>
>>>> (((Int, Int)))   flatten to   (Int, Int)
>>>> (Int, (((Int, Int))), Int)   flatten to   (Int, (Int, Int), Int)
>>>>
>>>>
>>>> 2017-06-07 12:03 GMT+08:00 Stephen Celis :
>>>>
>>>>> The inline cases make sense to me, but my concern for ambiguity are
>>>>> because we can define both of these functions:
>>>>>
>>>>> func add1(_ x: Int, _ y: Int) -> Int {
>>>>>   return x + y
>>>>> }
>>>>> func add2(_ pair: (Int, Int)) -> Int {
>>>>>   return pair.0 + pair.1
>>>>> }
>>>>>
>>>>> // What's the behavior here?
>>>>> [(1, 2)].map(add1)
>>>>> [(1, 2)].map(add2)
>>>>>
>>>>> What comes to mind, though, is, Swift already prevents single-element
>>>>> tuples, so why not prevent functions that take a single tuple as the only
>>>>> argument?
>>>>>
>>>>> Swift could provide a fix-it for functions that take single tuples and
>>>>> say: "Swift functions cannot take a single tuple. Please write a function
>>>>> that takes as many arguments as the tuple specified."
>>>>>
>>>>> Considering the fact 

Re: [swift-evolution] Proposal: Always flatten the single element tuple

2017-06-06 Thread Susan Cheng via swift-evolution
I don't think it's a roll back change.

The proposal is not proposing allow to reorder the parameters by using the
tuple or implicit tuple splat to fit the function parameters.
It's just clarify the relationship of tuples and argument lists.

as the grammar of Swift 3, it's allowed wrapping the argument with a single
tuple to a function with two argument.

[(1, 2)].map(+)

and SE-0110 is the proposal make the distinguished and not allowed this
line of code.

although we fix the compiler to accept the destructuring of tuples

[(1, 2)].map({ ((lhs, rhs)) in lhs + rhs })

it's not accepting the code of [(1, 2)].map(+) which the operator + are not
function with accepting the tuple of two elements.

the only way we can thought is that the arguments with single tuple is
flattened and it's most compatible with Swift 3.

2017-06-07 13:05 GMT+08:00 Xiaodi Wu :

> This is not what was meant during discussion about re-evaluating SE-0110.
> Tuples already behave as described, but function argument lists are not
> tuples and have not been for a very long time: see SE-0029, SE-0066.
>
> Also, consider SE-0046, which makes possible labels in single-argument
> argument lists (not possible in tuples), and SE-0060, which prohibits
> arbitrary reordering (although still possible in tuples). This is to say
> that the whole direction of Swift since version 2 has been to erase the
> historical relationship between tuples and argument lists.
>
> The question is how to accommodate some common use cases for destructuring
> as a matter of syntactic sugar after having carefully distinguished
> argument lists and tuples in the compiler, which is a given, not how to
> roll back a change that was settled in 2011, by Chris’s telling.
>
> On Tue, Jun 6, 2017 at 23:14 Susan Cheng via swift-evolution <
> swift-evolution@swift.org> wrote:
>
>>
>> func add2(_ pair: (Int, Int)) -> Int {
>> return pair.0 + pair.1
>> }
>>
>> consider the follows
>>
>> let _add2 =  add2 // add2 have the typeof `((Int, Int)) -> Int`, it
>> should flatten to `(Int, Int) -> Int`
>>
>> so these two lines are also acceptable
>> [(1, 2)].map(add1)
>> [(1, 2)].map(add2)
>>
>> this proposal is not just changing the behaviour of closure, this
>> proposal also changing the tuple type
>>
>> (((Int, Int)))   flatten to   (Int, Int)
>> (Int, (((Int, Int))), Int)   flatten to   (Int, (Int, Int), Int)
>>
>>
>> 2017-06-07 12:03 GMT+08:00 Stephen Celis :
>>
>>> The inline cases make sense to me, but my concern for ambiguity are
>>> because we can define both of these functions:
>>>
>>> func add1(_ x: Int, _ y: Int) -> Int {
>>>   return x + y
>>> }
>>> func add2(_ pair: (Int, Int)) -> Int {
>>>   return pair.0 + pair.1
>>> }
>>>
>>> // What's the behavior here?
>>> [(1, 2)].map(add1)
>>> [(1, 2)].map(add2)
>>>
>>> What comes to mind, though, is, Swift already prevents single-element
>>> tuples, so why not prevent functions that take a single tuple as the only
>>> argument?
>>>
>>> Swift could provide a fix-it for functions that take single tuples and
>>> say: "Swift functions cannot take a single tuple. Please write a function
>>> that takes as many arguments as the tuple specified."
>>>
>>> Considering the fact that Swift generally operates in a multi-argument
>>> world, and given that functions taking a single tuple are the minority, I
>>> think this would be a good way to move forward.
>>>
>>> Stephen
>>>
>>> > On Jun 6, 2017, at 11:21 PM, Susan Cheng 
>>> wrote:
>>> >
>>> >  [(1, 2)].map({ x, y in x + y })  // this line is correct
>>> >  [(1, 2)].map({ tuple in tuple.0 + tuple.1 })  // this line should not
>>> accepted
>>> >
>>> > or
>>> >
>>> >  [(1, 2)].map({ $0 + $1 })  // this line is correct
>>> >  [(1, 2)].map({ $0.0 + $0.1 })  // this line should not accepted
>>> >
>>> > it's because `((Int, Int)) -> Int` always flatten to `(Int, Int) ->
>>> Int`
>>> > so, it should only accept the function with two arguments
>>> >
>>> >
>>> >
>>> > 2017-06-07 11:07 GMT+08:00 Stephen Celis :
>>> > I like this a lot, but how do we solve for the function case?
>>> >
>>> > func add(_ x: Int, _ y: Int) -> Int {
>>> >   return x + y
>>> > }
>

Re: [swift-evolution] Proposal: Always flatten the single element tuple

2017-06-06 Thread Susan Cheng via swift-evolution
func add2(_ pair: (Int, Int)) -> Int {
return pair.0 + pair.1
}

consider the follows

let _add2 =  add2 // add2 have the typeof `((Int, Int)) -> Int`, it
should flatten to `(Int, Int) -> Int`

so these two lines are also acceptable
[(1, 2)].map(add1)
[(1, 2)].map(add2)

this proposal is not just changing the behaviour of closure, this proposal
also changing the tuple type

(((Int, Int)))   flatten to   (Int, Int)
(Int, (((Int, Int))), Int)   flatten to   (Int, (Int, Int), Int)


2017-06-07 12:03 GMT+08:00 Stephen Celis :

> The inline cases make sense to me, but my concern for ambiguity are
> because we can define both of these functions:
>
> func add1(_ x: Int, _ y: Int) -> Int {
>   return x + y
> }
> func add2(_ pair: (Int, Int)) -> Int {
>   return pair.0 + pair.1
> }
>
> // What's the behavior here?
> [(1, 2)].map(add1)
> [(1, 2)].map(add2)
>
> What comes to mind, though, is, Swift already prevents single-element
> tuples, so why not prevent functions that take a single tuple as the only
> argument?
>
> Swift could provide a fix-it for functions that take single tuples and
> say: "Swift functions cannot take a single tuple. Please write a function
> that takes as many arguments as the tuple specified."
>
> Considering the fact that Swift generally operates in a multi-argument
> world, and given that functions taking a single tuple are the minority, I
> think this would be a good way to move forward.
>
> Stephen
>
> > On Jun 6, 2017, at 11:21 PM, Susan Cheng  wrote:
> >
> >  [(1, 2)].map({ x, y in x + y })  // this line is correct
> >  [(1, 2)].map({ tuple in tuple.0 + tuple.1 })  // this line should not
> accepted
> >
> > or
> >
> >  [(1, 2)].map({ $0 + $1 })  // this line is correct
> >  [(1, 2)].map({ $0.0 + $0.1 })  // this line should not accepted
> >
> > it's because `((Int, Int)) -> Int` always flatten to `(Int, Int) -> Int`
> > so, it should only accept the function with two arguments
> >
> >
> >
> > 2017-06-07 11:07 GMT+08:00 Stephen Celis :
> > I like this a lot, but how do we solve for the function case?
> >
> > func add(_ x: Int, _ y: Int) -> Int {
> >   return x + y
> > }
> > [(1, 2)].map(add)
> >
> > Where does `map` with a function of `((Int, Int)) -> Int` fit in?
> >
> > > On Jun 6, 2017, at 10:15 PM, Susan Cheng via swift-evolution <
> swift-evolution@swift.org> wrote:
> > >
> > > Introduction
> > >
> > >
> > > Because the painful of SE-0110, here is a proposal to clarify the
> tuple syntax.
> > >
> > > Proposed solution
> > >
> > > 1. single element tuple always be flattened
> > >
> > > let tuple1: (((Int))) = 0  // TypeOf(tuple1) == Int
> > >
> > > let tuple2: Int))), Int) = (0, 0)  // TypeOf(tuple2) == (Int, Int)
> > >
> > > 2. function arguments list also consider as a tuple, which means the
> function that accept a single tuple should always be flattened.
> > >
> > > let fn1: (Int, Int) -> Void = { _, _ in }
> > >
> > > let fn2: ((Int, Int)) -> Void = { _, _ in }  // always flattened
> > >
> > > let fn3: (Int, Int) -> Void = { _ in }  // not allowed, here are two
> arguments
> > >
> > > let fn4: ((Int, Int)) -> Void = { _ in }  // not allowed, here are two
> arguments
> > >
> > > ___
> > > 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: Always flatten the single element tuple

2017-06-06 Thread Susan Cheng via swift-evolution
a PR is create: https://github.com/apple/swift-evolution/pull/722

2017-06-07 10:15 GMT+08:00 Susan Cheng :

> Introduction
>
> Because the painful of SE-0110, here is a proposal to clarify the tuple
> syntax.
>
> Proposed solution
> 1. single element tuple always be flattened
>
> let tuple1: (((Int))) = 0  // TypeOf(tuple1) == Int
>
>
> let tuple2: Int))), Int) = (0, 0)  // TypeOf(tuple2) == (Int, Int)
>
> 2. function arguments list also consider as a tuple, which means the
> function that accept a single tuple should always be flattened.
>
> let fn1: (Int, Int) -> Void = { _, _ in }
>
>
> let fn2: ((Int, Int)) -> Void = { _, _ in }  // always flattened
>
> let fn3: (Int, Int) -> Void = { _ in }  // not allowed, here are two
> arguments
>
> let fn4: ((Int, Int)) -> Void = { _ in }  // not allowed, here are two
> arguments
>
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Proposal: Always flatten the single element tuple

2017-06-06 Thread Susan Cheng via swift-evolution
 [(1, 2)].map({ x, y in x + y })  // this line is correct
 [(1, 2)].map({ tuple in tuple.0 + tuple.1 })  // this line should not
accepted

or

 [(1, 2)].map({ $0 + $1 })  // this line is correct
 [(1, 2)].map({ $0.0 + $0.1 })  // this line should not accepted

it's because `((Int, Int)) -> Int` always flatten to `(Int, Int) -> Int`
so, it should only accept the function with two arguments



2017-06-07 11:07 GMT+08:00 Stephen Celis :

> I like this a lot, but how do we solve for the function case?
>
> func add(_ x: Int, _ y: Int) -> Int {
>   return x + y
> }
> [(1, 2)].map(add)
>
> Where does `map` with a function of `((Int, Int)) -> Int` fit in?
>
> > On Jun 6, 2017, at 10:15 PM, Susan Cheng via swift-evolution <
> swift-evolution@swift.org> wrote:
> >
> > Introduction
> >
> >
> > Because the painful of SE-0110, here is a proposal to clarify the tuple
> syntax.
> >
> > Proposed solution
> >
> > 1. single element tuple always be flattened
> >
> > let tuple1: (((Int))) = 0  // TypeOf(tuple1) == Int
> >
> > let tuple2: Int))), Int) = (0, 0)  // TypeOf(tuple2) == (Int, Int)
> >
> > 2. function arguments list also consider as a tuple, which means the
> function that accept a single tuple should always be flattened.
> >
> > let fn1: (Int, Int) -> Void = { _, _ in }
> >
> > let fn2: ((Int, Int)) -> Void = { _, _ in }  // always flattened
> >
> > let fn3: (Int, Int) -> Void = { _ in }  // not allowed, here are two
> arguments
> >
> > let fn4: ((Int, Int)) -> Void = { _ in }  // not allowed, here are two
> arguments
> >
> > ___
> > 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: Always flatten the single element tuple

2017-06-06 Thread Susan Cheng via swift-evolution
it's also clear that these code will never be ambiguous

 [(1, 2)].map({ $0 }) // $0 always not a tuple, because arguments should be
flattened

2017-06-07 11:21 GMT+08:00 Susan Cheng :

>  [(1, 2)].map({ x, y in x + y })  // this line is correct
>  [(1, 2)].map({ tuple in tuple.0 + tuple.1 })  // this line should not
> accepted
>
> or
>
>  [(1, 2)].map({ $0 + $1 })  // this line is correct
>  [(1, 2)].map({ $0.0 + $0.1 })  // this line should not accepted
>
> it's because `((Int, Int)) -> Int` always flatten to `(Int, Int) -> Int`
> so, it should only accept the function with two arguments
>
>
>
> 2017-06-07 11:07 GMT+08:00 Stephen Celis :
>
>> I like this a lot, but how do we solve for the function case?
>>
>> func add(_ x: Int, _ y: Int) -> Int {
>>   return x + y
>> }
>> [(1, 2)].map(add)
>>
>> Where does `map` with a function of `((Int, Int)) -> Int` fit in?
>>
>> > On Jun 6, 2017, at 10:15 PM, Susan Cheng via swift-evolution <
>> swift-evolution@swift.org> wrote:
>> >
>> > Introduction
>> >
>> >
>> > Because the painful of SE-0110, here is a proposal to clarify the tuple
>> syntax.
>> >
>> > Proposed solution
>> >
>> > 1. single element tuple always be flattened
>> >
>> > let tuple1: (((Int))) = 0  // TypeOf(tuple1) == Int
>> >
>> > let tuple2: Int))), Int) = (0, 0)  // TypeOf(tuple2) == (Int, Int)
>> >
>> > 2. function arguments list also consider as a tuple, which means the
>> function that accept a single tuple should always be flattened.
>> >
>> > let fn1: (Int, Int) -> Void = { _, _ in }
>> >
>> > let fn2: ((Int, Int)) -> Void = { _, _ in }  // always flattened
>> >
>> > let fn3: (Int, Int) -> Void = { _ in }  // not allowed, here are two
>> arguments
>> >
>> > let fn4: ((Int, Int)) -> Void = { _ in }  // not allowed, here are two
>> arguments
>> >
>> > ___
>> > 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: Always flatten the single element tuple

2017-06-06 Thread Susan Cheng via swift-evolution
Introduction

Because the painful of SE-0110, here is a proposal to clarify the tuple
syntax.

Proposed solution
1. single element tuple always be flattened

let tuple1: (((Int))) = 0  // TypeOf(tuple1) == Int


let tuple2: Int))), Int) = (0, 0)  // TypeOf(tuple2) == (Int, Int)

2. function arguments list also consider as a tuple, which means the
function that accept a single tuple should always be flattened.

let fn1: (Int, Int) -> Void = { _, _ in }


let fn2: ((Int, Int)) -> Void = { _, _ in }  // always flattened

let fn3: (Int, Int) -> Void = { _ in }  // not allowed, here are two
arguments

let fn4: ((Int, Int)) -> Void = { _ in }  // not allowed, here are two
arguments
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal]Allow constraints on associatedtype and shorten type constraints list in function

2016-07-29 Thread Susan Cheng via swift-evolution
Thanks.

I found this proposal in pull requests after the email sent.

Anders Ha  於 2016年7月29日星期五 寫道:

> It is one of the items in the Generics Manifesto, and we had a discussion
> thread with a proposal on this already, however halted for being an
> addictive feature. Anyway, aren't discussions on post Swift 3 matters
> preferred to start on Aug 1?
>
>
>
> Hart's proposal
>
> https://github.com/hartbit/swift-evolution/blob/master/proposals/-powerful-constraints-associated-types.md
>
> [swift-evolution] [Proposal] More Powerful Constraints for Associated Types
>
> https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160502/016354.html
>
>
>
> Regards,
> Anders
>
>
> On 29 Jul 2016, at 10:17 AM, Susan Cheng via swift-evolution <
> swift-evolution@swift.org
> > wrote:
>
> Hello swift community,
>
> I want to introduce a proposal to allow constraints on associatedtype.
> I found a bug report(https://bugs.swift.org/browse/SR-1466) and it's due
> to without constraints on associatedtype itself.
>
> This force us always have to write the redundant constraints like 
> Indices.Iterator.Element
> == Index or Indices.SubSequence.Iterator.Element == Index on type
> constraints in function:
>
> public extension MutableCollection where Self : RandomAccessCollection,
> Indices.Index == Index, Indices.SubSequence : RandomAccessCollection,
> Indices.SubSequence.Iterator.Element == Index {
>
>
> /// Shuffle `self` in-place.
> mutating func shuffle() {
> for i in self.indices.dropLast() {
> let j = self.indices.suffix(from: i).random()!
> if i != j {
> swap(&self[i], &self[j])
> }
> }
> }
> }
>
> Besides this, we also can write some odd definitions but allowed by swift
> compiler.
>
> struct MyArray : Collection {
>
>
> typealias Indices = CountableRange
>
>
> var base: [Int]
>
>
> var startIndex: Int {
> return base.startIndex
> }
> var endIndex: Int {
> return base.endIndex
> }
>
> func index(after: Int) -> Int {
> return after + 1
> }
>
>
> var indices: CountableRange {
> return CountableRange(uncheckedBounds: (lower: Int32(startIndex),
> upper: Int32(endIndex)))
> }
>
>
> subscript(position: Int) -> Int {
> get {
> return base[position]
> }
> set {
> base[position] = newValue
> }
> }
> }
>
> as a reference:
> http://stackoverflow.com/questions/37581234/can-an-associated-type-be-restricted-by-protocol-conformance-and-a-where-clause
>
> it's clearly that we need a syntax like this:
>
> public protocol Collection : Indexable, Sequence {
>
>
> /// A sequence that represents a contiguous subrange of the
> collection's
> /// elements.
> ///
> /// This associated type appears as a requirement in the `Sequence`
> /// protocol, but it is restated here with stricter constraints. In a
> /// collection, the subsequence should also conform to `Collection`.
> associatedtype SubSequence : IndexableBase, Sequence where
> SubSequence.Iterator.Element == Iterator.Element = Slice
>
>
> /// A type that can represent the indices that are valid for
> subscripting the
> /// collection, in ascending order.
> associatedtype Indices : IndexableBase, Sequence where
> Indices.Iterator.Element == Index = DefaultIndices
>
> }
>
> This  harmless and brings huge benefits to swift.
> ___
> 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]Allow constraints on associatedtype and shorten type constraints list in function

2016-07-28 Thread Susan Cheng via swift-evolution
Hello swift community,

I want to introduce a proposal to allow constraints on associatedtype.
I found a bug report(https://bugs.swift.org/browse/SR-1466) and it's due to
without constraints on associatedtype itself.

This force us always have to write the redundant constraints like
Indices.Iterator.Element
== Index or Indices.SubSequence.Iterator.Element == Index on type
constraints in function:


public extension MutableCollection where Self : RandomAccessCollection,
Indices.Index == Index, Indices.SubSequence : RandomAccessCollection,
Indices.SubSequence.Iterator.Element == Index {



/// Shuffle `self` in-place.

mutating func shuffle() {

for i in self.indices.dropLast() {

let j = self.indices.suffix(from: i).random()!

if i != j {

swap(&self[i], &self[j])

}

}

}

}

Besides this, we also can write some odd definitions but allowed by swift
compiler.


struct MyArray : Collection {



typealias Indices = CountableRange



var base: [Int]



var startIndex: Int {

return base.startIndex

}

var endIndex: Int {

return base.endIndex

}


func index(after: Int) -> Int {

return after + 1

}



var indices: CountableRange {

return CountableRange(uncheckedBounds: (lower: Int32(startIndex),
upper: Int32(endIndex)))

}



subscript(position: Int) -> Int {

get {

return base[position]

}

set {

base[position] = newValue

}

}

}


as a reference:
http://stackoverflow.com/questions/37581234/can-an-associated-type-be-restricted-by-protocol-conformance-and-a-where-clause


it's clearly that we need a syntax like this:


public protocol Collection : Indexable, Sequence {



/// A sequence that represents a contiguous subrange of the collection's

/// elements.

///

/// This associated type appears as a requirement in the `Sequence`

/// protocol, but it is restated here with stricter constraints. In a

/// collection, the subsequence should also conform to `Collection`.

associatedtype SubSequence : IndexableBase, Sequence where
SubSequence.Iterator.Element == Iterator.Element = Slice



/// A type that can represent the indices that are valid for
subscripting the

/// collection, in ascending order.

associatedtype Indices : IndexableBase, Sequence where
Indices.Iterator.Element == Index = DefaultIndices


}


This  harmless and brings huge benefits to swift.
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Proposals: (1) Forbidding custom `==` for value types, (2) `dispatch` keyword, (3) `default`-result for methods with `Self`, and (4) Poor-Mans-Existentials

2016-07-20 Thread Susan Cheng via swift-evolution
I know and I want to point out that you said value type don't have any
thread safety issues is wrong.

Johannes Neubauer  於 2016年7月20日星期三 寫道:

> Dear Susan,
>
> > Am 20.07.2016 um 14:14 schrieb Susan Cheng  >:
> >
> > I forgot to reply, a shared value type can capture by multiple closures.
> >
> > func twoThreads() -> (Thread, Thread) {
> > var shared_int = 0
> > return (Thread { shared_int = 1 }, Thread { shared_int = 2 })
> > }
>
> You are not sharing the value type, but the reference to it (so you share
> the surrounding function context *by reference* or more precisely via *call
> by sharing*). I use an array as example (and synchronous dispatch queues,
> to get a reliable answer), because its value is less „atomic“:
>
> ```swift
> var shared_array = [Int]()
> var not_shared_array = shared_array
> dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
> 0)) {
> var not_shared_array = shared_array
> not_shared_array.append(1)
> print("not shared 1: \(not_shared_array)")
> shared_array.append(2)
> print("shared 2: \(shared_array)")
> }
>
> dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
> 0)) {
> var not_shared_array = shared_array
> not_shared_array.append(3)
> print("not shared 3: \(not_shared_array)")
> shared_array.append(4)
> print("shared 4: \(shared_array)")
> }
>
> not_shared_array.append(5)
> shared_array.append(6)
> print("not shared: \(not_shared_array)")
> print("shared: \(shared_array)“)
>
> // prints:
> // not shared 1: [1]
> // shared 2: [2]
> // not shared 3: [2, 3]
> // shared 4: [2, 4]
> // not shared: [5]
> // shared: [2, 4, 6]
> ```
>
> You could do this without closures using a reference type as a wrapper,
> but you still do not share the value instance but the wrapper:
>
> ```swift
> class Wrapper {
> var shared_array = [Int]()
> }
>
> func appendNumber(w: Wrapper, n: Int) {
> w.shared_array.append(n)
> }
>
> func appendNumber(var v: [Int], n: Int) {
> v.append(n)
> }
>
> let wi = Wrapper(),
> vi = [Int]()
>
> appendNumber(wi, n: 1)
> appendNumber(vi, n: 2)
> print(wi.shared_array)
> print(vi)
>
> // prints:
> // [1]
> // []
> ```
>
> All the best
> Johannes
>
> >
> > Johannes Neubauer > 於
> 2016年7月18日星期一 寫道:
> >
> > > Am 18.07.2016 um 06:47 schrieb Susan Cheng  >:
> > >
> > > so, you want to propose default == operator but not forbidding all
> peoples to custom == operator?
> > > Why don't just adding the following function to std library?
> > >
> > > public func == (lhs: T, rhs: T) -> Bool {
> > > var lhs = lhs
> > > var rhs = rhs
> > > return memcmp(&lhs, &rhs, sizeof(T.self)) == 0
> > > }
> >
> > This does not work, because method parameters are statically dispatched.
> This function will never be executed for any type, that has a custom
> equality implementation. So this would not enforce this check upfront. You
> would need to copy this code to every custom implementation (which can be
> forgotten). Or you have to implement it like this
> >
> > ```swift
> > public func isSame(lhs: Any, rhs: Any) -> Bool {
> >   // like above in your code
> > }
> >
> > public func ==(lhs: MyType, rhs: MyType) -> Bool {
> >   if isSame(lhs, rhs: rhs) {
> > return true
> >   }
> >   // do custom behavior
> > }
> > ```
> >
> > > Thread safety can't fixed by std library. Value type only can atomic
> compared when additional mutex provided.
> >
> > Value types are either on the stack or they are **copied** to the heap
> (for protocol types with large value types). So, you don’t have any thread
> safety issues (as they are copied before they are changed in the new
> thread) as long as you don’t do (or check) anything on a property of a
> reference type, because the latter has shared **state**.
>
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Proposals: (1) Forbidding custom `==` for value types, (2) `dispatch` keyword, (3) `default`-result for methods with `Self`, and (4) Poor-Mans-Existentials

2016-07-20 Thread Susan Cheng via swift-evolution
I forgot to reply, a shared value type can capture by multiple closures.

func twoThreads() -> (Thread, Thread) {
var shared_int = 0
return (Thread { shared_int = 1 }, Thread { shared_int = 2 })
}

Johannes Neubauer  於 2016年7月18日星期一 寫道:

>
> > Am 18.07.2016 um 06:47 schrieb Susan Cheng  >:
> >
> > so, you want to propose default == operator but not forbidding all
> peoples to custom == operator?
> > Why don't just adding the following function to std library?
> >
> > public func == (lhs: T, rhs: T) -> Bool {
> > var lhs = lhs
> > var rhs = rhs
> > return memcmp(&lhs, &rhs, sizeof(T.self)) == 0
> > }
>
> This does not work, because method parameters are statically dispatched.
> This function will never be executed for any type, that has a custom
> equality implementation. So this would not enforce this check upfront. You
> would need to copy this code to every custom implementation (which can be
> forgotten). Or you have to implement it like this
>
> ```swift
> public func isSame(lhs: Any, rhs: Any) -> Bool {
>   // like above in your code
> }
>
> public func ==(lhs: MyType, rhs: MyType) -> Bool {
>   if isSame(lhs, rhs: rhs) {
> return true
>   }
>   // do custom behavior
> }
> ```
>
> > Thread safety can't fixed by std library. Value type only can atomic
> compared when additional mutex provided.
>
> Value types are either on the stack or they are **copied** to the heap
> (for protocol types with large value types). So, you don’t have any thread
> safety issues (as they are copied before they are changed in the new
> thread) as long as you don’t do (or check) anything on a property of a
> reference type, because the latter has shared **state**.
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Proposals: (1) Forbidding custom `==` for value types, (2) `dispatch` keyword, (3) `default`-result for methods with `Self`, and (4) Poor-Mans-Existentials

2016-07-19 Thread Susan Cheng via swift-evolution
But I don't want swift force using default equal comparator before my
implementation when I knew it was redundant that everything checking twice.

I have wrote lots of structure type with cache object for lazy evaluation.
All of them dose not need to compare the cache object.

Johannes Neubauer  於 2016年7月18日星期一 寫道:

>
> > Am 18.07.2016 um 06:47 schrieb Susan Cheng  >:
> >
> > so, you want to propose default == operator but not forbidding all
> peoples to custom == operator?
> > Why don't just adding the following function to std library?
> >
> > public func == (lhs: T, rhs: T) -> Bool {
> > var lhs = lhs
> > var rhs = rhs
> > return memcmp(&lhs, &rhs, sizeof(T.self)) == 0
> > }
>
> This does not work, because method parameters are statically dispatched.
> This function will never be executed for any type, that has a custom
> equality implementation. So this would not enforce this check upfront. You
> would need to copy this code to every custom implementation (which can be
> forgotten). Or you have to implement it like this
>
> ```swift
> public func isSame(lhs: Any, rhs: Any) -> Bool {
>   // like above in your code
> }
>
> public func ==(lhs: MyType, rhs: MyType) -> Bool {
>   if isSame(lhs, rhs: rhs) {
> return true
>   }
>   // do custom behavior
> }
> ```
>
> > Thread safety can't fixed by std library. Value type only can atomic
> compared when additional mutex provided.
>
> Value types are either on the stack or they are **copied** to the heap
> (for protocol types with large value types). So, you don’t have any thread
> safety issues (as they are copied before they are changed in the new
> thread) as long as you don’t do (or check) anything on a property of a
> reference type, because the latter has shared **state**.
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Proposals: (1) Forbidding custom `==` for value types, (2) `dispatch` keyword, (3) `default`-result for methods with `Self`, and (4) Poor-Mans-Existentials

2016-07-17 Thread Susan Cheng via swift-evolution
so, you want to propose default == operator but not forbidding all peoples
to custom == operator?
Why don't just adding the following function to std library?


public func == (lhs: T, rhs: T) -> Bool {

var lhs = lhs

var rhs = rhs

return memcmp(&lhs, &rhs, sizeof(T.self)) == 0

}


Thread safety can't fixed by std library. Value type only can atomic
compared when additional mutex provided.

2016-07-16 19:50 GMT+08:00 Johannes Neubauer :

> Dear Susan,
>
> I wrote the former mail in a hurry: the URI example from before is a
> *false-positive* either and can be handled like the `Polar` example. But
> the problem with false-negatives are still valid. Example:
>
> ```swift
> func ==(lhs: A, rhs: B) {
>   if(globalBooleanVarIsDayEven) {
> return false
>   }
>   // do a normal check
> }
> ```
>
> This would not be possible, if you check for equality upfront and omitting
> executing the custom code above if the standard check returns `true`
> already.
>
> Another **big** problem with using `==` for properties to reference types
> implementing `Equatable` is race conditions and as Matt Wright pointed out
> in his talk [Concurrent Programming with GCD in Swift 3][0] on WWDC 2016,
> there are no harmless cases of concurrency issues. Rationale:
>
> Reference types share state possible with code that runs concurrently in
> different threads. So if you compare via `==` to value types and use `==`
> to compare the object(s) of a reference type property this object(s) may
> change during the check (even if the machine has only one core, if the OS
> is preemptive). And this may happen even if it is the very same (by
> identity and `===`) object that is referenced. A (future) automatic value
> pool for indirect storage with copy-on-write for value semantics would not
> share this problem, of course, since their storage is only shared for reads
> and not for writes (the `===` check on this indirect storage would by
> definition suffice and be much faster than executing the check). This does
> not hold for properties of references types in that indirect storage.
>
> [0]:
> http://devstreaming.apple.com/videos/wwdc/2016/720w6g8t9zhd23va0ai/720/720_concurrent_programming_with_gcd_in_swift_3.pdf
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Proposals: (1) Forbidding custom `==` for value types, (2) `dispatch` keyword, (3) `default`-result for methods with `Self`, and (4) Poor-Mans-Existentials

2016-07-15 Thread Susan Cheng via swift-evolution
How about Polar(r: 0, phi: 0) ?
It should all equal with any angles if r == 0.

2016-07-16 0:41 GMT+08:00 Johannes Neubauer via swift-evolution <
swift-evolution@swift.org>:

>
> > Am 15.07.2016 um 18:29 schrieb Saagar Jha :
> >
> > Here's a value type that uses custom equality (at least, I think so):
> String. Since it uses extended grapheme clusters, internally two Strings
> may be composed of different Unicode scalars, but if they create the same
> Characters they are considered to be equal.
>
> Good point. But shouldn’t this be another type of equality then or do they
> behave exactly the same and are just implemented differently? Because if
> not, this seems to be introducing mixed-type comparisons like `5l == 5` or
> `Point2D(0, 0) == Point3D(0, 0, 0) which are bad since they make it
> impossible to guarantee reflexivity, symmetry, and transitivity. Swift does
> a hard job to enforce this from the programmer. If this is really intended,
> then there should be a fixed implementation for equality of value types,
> which can be overridden, but which leads to a warning (which has to be
> suppressed with some kind of annotation or so). Because, these custom
> implementations can do harm.
>
> ___
> 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]Simple pattern matching with Horspool algorithm

2016-05-16 Thread Susan Cheng via swift-evolution
public extension CollectionType where Index : RandomAccessIndexType {



@warn_unused_result

func matchWith(pattern: C, @noescape
isEquivalent: (Generator.Element, Generator.Element) throws -> Bool)
rethrows -> Index? {



let pattern_count = pattern.count.toIntMax()

if count.toIntMax() < pattern_count {

return nil

}

let reverse_pattern = pattern.reverse()

var cursor = startIndex.advancedBy(numericCast(pattern_count - 1))

while cursor < endIndex {

let left = startIndex...cursor

let pair = zip(left.reverse(), reverse_pattern)

guard let not_match = try pair.firstOf({ try
!isEquivalent(self[$0],
$1) }) else {

return cursor.advancedBy(numericCast(1 - pattern_count))

}

if let pos = try reverse_pattern.dropFirst().indexOf({ try
isEquivalent(self[not_match.0], $0) }) {

let offset = reverse_pattern.startIndex.distanceTo(pos).
toIntMax()

cursor = not_match.0.advancedBy(numericCast(offset), limit:
endIndex)

} else {

cursor = not_match.0.advancedBy(numericCast(pattern_count),
limit: endIndex)

}

}

if try self.reverse().startsWith(reverse_pattern, isEquivalent:
isEquivalent) {

return endIndex.advancedBy(numericCast(-pattern_count))

}

return nil

}

}


public extension CollectionType where Index : RandomAccessIndexType,
Generator.Element : Equatable {



@warn_unused_result

func matchWith(pattern: C) -> Index? {

return self.matchWith(pattern) { $0 == $1 }

}

}


with this simplify version of Horspool algorithm, it can speed up searching
in any random access CollectionType (better than brute force searching).
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Proposal: Add SequenceType.first

2016-01-02 Thread Susan Cheng via swift-evolution
Consider this,

struct RandomGenerator : GeneratorType, SequenceType {



mutating func next() -> UInt32? {

return arc4random()

}

}

what's the expected result of follows??


let random = RandomGenerator()


let resultA = random.first

let resultB = random.first

let resultC = Array(random.prefix(4))

let resultD = Array(random.prefix(4))

all should agree that resultC and resultD will get different array. what's
about with resultA and resultB?

Gwendal Roué  於 2016年1月2日 下午8:13 寫道:

Hello,

My two cents: I feel uncomfortable with SequenceType.first since
SequenceType clearly states that it may be destructed on iteration.

Compare :

seq.generate().next() // clear that it may give another result if called
twice
seq.first // unclear that it may give another result if called
twice

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


Re: [swift-evolution] About the PermutationGenerator

2015-12-31 Thread Susan Cheng via swift-evolution
I didn't explain correctly.

let's take this:

let c = Multipass(Fib(a: 1, b: -1, limit: 10))

this sequences should have results with [1, -1, 0, -1, -1, ...]
So is c.startIndex.successor() equal to
c.startIndex.successor().successor().successor()??

Dave Abrahams  於 2016年1月1日星期五 寫道:

>
> On Dec 31, 2015, at 8:22 PM, 鄭齊峯 via swift-evolution <
> swift-evolution@swift.org
> > wrote:
>
> if you try my modification, it will crash.
>
>
> Only because your Sequence genereates an arithmetic underflow.  I don’t
> understand what point you’re trying to make
>
>
> struct Fib : SequenceType {
>
> var a: Int
> var b: Int
>
> var limit: Int
>
> func generate() -> FibGenerator {
> return Generator(a: a, b: b, limit: limit)
> }
> }
>
> let c = Multipass(Fib(a: 1, b: -1, limit: 10))
>
> A SequenceType becomes a CollectionType only work by adding a Index. that
> the most significantly different of sequence and collection.
>
>
> I think I understand that pretty well, having designed both of those
> abstractions, but still don’t get your point.  Sorry, I’m trying here, but
> I can’t figure out what you’re trying to tell me.
>
>
> /// A `CollectionType` containing the same elements as `Base`, without
> storing them.
> ///
> /// - Requires: `Base` supports multiple passes (traversing it does not
> ///   consume the sequence), and `Base.Generator` has value semantics
> public struct Multipass : CollectionType {
> public var startIndex: MultipassIndex {
> var g = _base.enumerate().generate()
> if let (idx, val) = g.next() {
> return MultipassIndex(index: idx, buffer: val, generator: g)
> }
> return MultipassIndex(index: nil, buffer: nil, generator: g)
> }
>
> public var endIndex: MultipassIndex {
> return MultipassIndex(index: nil, buffer: nil, generator: _base.
> enumerate().generate())
> }
>
> public subscript(position: MultipassIndex) -> Base.Generator.
> Element {
> return position.buffer!
> }
>
> public init(_ base: Base) {
> _base = base
> }
>
> var _base: Base
> }
>
> // Note: Requires T.Generator has value semantics
> public struct MultipassIndex : ForwardIndexType {
> public func successor() -> MultipassIndex {
> var r = self
> if let (idx, val) = r.generator.next() {
> r.index = idx
> r.buffer = val
> } else {
> r.index = nil
> r.buffer = nil
> }
> return r
> }
> var index: Int?
> var buffer: T.Generator.Element?
> var generator: EnumerateSequence.Generator
> }
>
> public func == (x: MultipassIndex, y: MultipassIndex) -> Bool {
> return x.index == y.index
> }
>
> //===--- An example fibonacci sequence
> ===//
> struct FibGenerator : GeneratorType {
> mutating func next() -> Int? {
> let c = a + b
> a = b
> b = c
> return a < limit ? a : nil
> }
> var a, b, limit: Int
> }
>
>
> struct Fib : SequenceType {
> var limit = 100
>
> func generate() -> FibGenerator {
> return Generator(a: 0, b: 1, limit: limit)
> }
> }
>
> It's true that ForwardIndexType is also run-through the base one by one
> but it also correct that getting specific value with specific index.
>
> c[c.startIndex.successor().successor().successor()] // it's a defined
> behave
>
>
> Again, not sure what you’re trying to say here.
>
>
>
> Dave Abrahams  > 於 2016年1月1日
> 下午12:00 寫道:
>
>
> On Dec 31, 2015, at 7:46 PM, Susan Cheng  > wrote:
>
>
> How GeneratorType confirm to Equatable??
>
>
> I don’t understand the question.  In the code I posted there’s a working
> example of how a GeneratorType model can conform to Equatable..
>
>
> struct Fib : SequenceType {
>
> var a: Int
> var b: Int
>
> var limit: Int
>
> func generate() -> FibGenerator {
> return Generator(a: a, b: b, limit: limit)
> }
> }
>
> let c = Multipass(Fib(a: 1, b: -1, limit: 10))
>
> -Susan
>
>
> 2016-01-01 11:17 GMT+08:00 Dave Abrahams  >:
>
>> FWIW, Indexable is an implementation artifact that will go away when
>> Swift’s generics system is improved.
>>
>> But if your real objection is that you have to come up with an Index and
>> a subscripting operator, I can understand that.  Part of the reason for
>> this is our reluctance to create any distinct protocols with identical
>> syntactic requirements <
>> http://news.gmane.org/find-root.php?message_id=2a3e0c76-1c88-4752-8a70-aa64bb142...@apple.com>.
>> To justify having a separate multi-pass sequence protocol, there would have
>> to be a significant/important class of multi-pass sequences for which
>> CollectionType was unimplementable without serious costs.
>>
>> In principle there’s a way to ease the pain of creating CollectionType
>> conformances for multipass SequenceTypes…if only it didn’t crash the
>> compiler  ;-).  Here’s a variation
>

Re: [swift-evolution] About the PermutationGenerator

2015-12-31 Thread Susan Cheng via swift-evolution
How GeneratorType confirm to Equatable??

struct Fib : SequenceType {

var a: Int
var b: Int

var limit: Int

func generate() -> FibGenerator {
return Generator(a: a, b: b, limit: limit)
}
}

let c = Multipass(Fib(a: 1, b: -1, limit: 10))

-Susan


2016-01-01 11:17 GMT+08:00 Dave Abrahams :

> FWIW, Indexable is an implementation artifact that will go away when
> Swift’s generics system is improved.
>
> But if your real objection is that you have to come up with an Index and a
> subscripting operator, I can understand that.  Part of the reason for this
> is our reluctance to create any distinct protocols with identical syntactic
> requirements <
> http://news.gmane.org/find-root.php?message_id=2a3e0c76-1c88-4752-8a70-aa64bb142...@apple.com>.
> To justify having a separate multi-pass sequence protocol, there would have
> to be a significant/important class of multi-pass sequences for which
> CollectionType was unimplementable without serious costs.
>
> In principle there’s a way to ease the pain of creating CollectionType
> conformances for multipass SequenceTypes…if only it didn’t crash the
> compiler  ;-).  Here’s a variation
> that uses a generic adapter instead of a protocol conformance declaration:
>
> /// A `CollectionType` containing the same elements as `Base`, without
> storing them.
> ///
> /// - Requires: `Base` supports multiple passes (traversing it does not
> ///   consume the sequence), and `Base.Generator` has value semantics
> public struct Multipass Equatable> : CollectionType {
>   public var startIndex: MultipassIndex {
> var g = _base.generate()
> return MultipassIndex(buffer: g.next(), generator: g)
>   }
>
>   public var endIndex: MultipassIndex {
> return MultipassIndex(buffer: nil, generator: _base.generate())
>   }
>
>   public subscript(position: MultipassIndex) ->
> Base.Generator.Element {
> return position.buffer!
>   }
>
>   public init(_ base: Base) {
> _base = base
>   }
>
>   var _base: Base
> }
>
> // Note: Requires T.Generator has value semantics
> public struct MultipassIndex
> : ForwardIndexType {
>   public func successor() -> MultipassIndex {
> var r = self
> r.buffer = r.generator.next()
> return r
>   }
>   var buffer: T.Generator.Element?
>   var generator: T.Generator
> }
>
> public func == (x: MultipassIndex, y: MultipassIndex) -> Bool {
>   return x.buffer == nil && y.buffer == nil || x.generator == y.generator
> }
>
> //===--- An example fibonacci sequence
> ===//
> struct FibGenerator : GeneratorType {
>   mutating func next() -> Int? {
> let c = a + b
> a = b
> b = c
> return a < limit ? a : nil
>   }
>   var a, b, limit: Int
> }
>
>
> struct Fib : SequenceType {
>   var limit = 1000
>
>   func generate() -> FibGenerator {
> return Generator(a: 0, b: 1, limit: limit)
>   }
> }
>
> //===--- Adapt Fib for use with Multipass
> -===//
> extension FibGenerator : Equatable {}
> func == (x: Fib.Generator, y: Fib.Generator) -> Bool {
>   return x.a == y.a
> }
>
> //===--- Demonstration
> ===//
> let c = Multipass(Fib())
> print(c.first)
> print(c.count)
> print(c.lazy.map { $0 + 1 })
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] sortBy, minElementBy and maxElementBy methods

2015-12-31 Thread Susan Cheng via swift-evolution
What's problem of overloading? We only have four methods to do so.

Dave Abrahams  於 2016年1月1日星期五 寫道:

>
> On Dec 31, 2015, at 4:14 AM, Tino Heth <2...@gmx.de
> > wrote:
>
>
> func byComparing(getComparisonKey: (T)->U) -> (T, T) ->
> Bool {
>   return { getComparisonKey($0) < getComparisonKey($1) }
> }
>
> I've written something similar to bring file URLs into the order of their
> creation dates.
> It is a small extension for collection types, and its only downside will
> disappear as soon as properties are accessible via method calls (afair
> there is a proposal in the making).
>
> It was quite a lot fiddling with generics, and I don't have the tiny piece
> of code on my own computer, but it works in a way that you can do
> let sorted =
> array.sortUsingAccessor(ElementType.methodThatReturnsComparable)
> Beside the problems with properties, I really liked that approach.
>
>
> This seems to be essentially the same design as Susan’s, and has the same
> problem: it requires a new overload for every algorithm that takes a
> comparison predicate.
>
> -Dave
>
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] About the PermutationGenerator

2015-12-31 Thread Susan Cheng via swift-evolution
sequence can have more methods with it, we can find first five values of
a sequence.

but we don't do this with a generator

struct Fibonacci: SequenceType {



var first, second: Int



func generate() -> AnyGenerator {



var a = first

var b = second



return anyGenerator {

let temp = a

(a, b) = (b, a + b)

return temp

}

}

}


Array(Fibonacci(first: 1, second: 1).prefix(10))

Happy new year to all


2015-12-31 21:57 GMT+08:00 Dmitri Gribenko :

> On Thu, Dec 31, 2015 at 3:36 PM, Susan Cheng 
> wrote:
> > I don't think so.
> >
> > As we don't say "Fibonacci collection", we know Fibonacci numbers are in
> > order. But we can't tell the number immediately if I asked a specific
> index
> > of Fibonacci sequence. The only way is calculate the sequence one by one
> > from start.
>
> That's OK, collections can have Forward indices which have exactly
> these properties.
>
> 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] About the PermutationGenerator

2015-12-31 Thread Susan Cheng via swift-evolution
I don't think so.

As we don't say "Fibonacci collection", we know Fibonacci numbers are in
order. But we can't tell the number immediately if I asked a specific index
of Fibonacci sequence. The only way is calculate the sequence one by one
from start.

So we need the collection, and collection do the jobs. But it true that
collections are sequences.
Swift is also have this definition, in concrete implementation way.

Dmitri Gribenko  於 2015年12月31日星期四 寫道:

> On Thu, Dec 31, 2015 at 3:04 PM, Susan Cheng  > wrote:
> > yes for sequences are not immutable. I get confused.
> >
> > no for sequences should be definition of lists of values. Just like
> > Fibonacci sequence, we can calculate the values form the start of the
> > Fibonacci sequence one by one. But we are not accessing the values of
> > Fibonacci sequence.
>
> Those are collections.  Collections can be iterated over multiple times.
>
> 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] About the PermutationGenerator

2015-12-31 Thread Susan Cheng via swift-evolution
yes for sequences are not immutable. I get confused.

no for sequences should be definition of lists of values. Just
like Fibonacci sequence, we can calculate the values form the start of
the Fibonacci sequence one by one. But we are not accessing the values
of Fibonacci sequence.

A socket can be modeled as a sequence of bytes but socket(itself) is not
the sequence. It's just provide method to access the bytes sequences.

Dmitri Gribenko  於 2015年12月31日星期四 寫道:

> On Thu, Dec 31, 2015 at 2:01 PM, Susan Cheng via swift-evolution <
> swift-evolution@swift.org
> > wrote:
>
>> As I know SequenceType should have behaved as immutable structure and it
>> provides method to get a mutable GeneratorType which generates value from
>> start of sequence.
>
>
> Sequences are not immutable.  A sequence is allowed to be consumed by
> iterating over its generator.  If the type you have is a sequence, you can
> only assume that you can access the elements only once.  For example, a
> socket can be modeled as a sequence of bytes.  Once the bytes are consumed
> from the corresponding generator, they are gone from the sequence.
>
> 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: Add SequenceType.first

2015-12-31 Thread Susan Cheng via swift-evolution
Generator should always generates value from start of sequence. I don't see
any problems with this implementation.

Dave Abrahams via swift-evolution  於
2015年12月31日星期四 寫道:

> On Dec 30, 2015, at 3:57 PM, Kevin Ballard via swift-evolution <
> swift-evolution@swift.org
> > wrote:
>
> It's sometimes useful to get the first element of a sequence. To that end
> I'd like to propose
>
> extension SequenceType {
> /// Returns the first element of `self`, or `nil` if `self` is empty.
> /// - Complexity: O(1)
> var first: Self.Generator.Element? {
> var gen = generate()
> return gen.next()
> }
> }
>
> I think it makes sense to add this property to the definition of
> SequenceType as well, so various sequences can override it to avoid
> constructing a generator.
>
> With this added to SequenceType, we can remove it from CollectionType, as
> the behavior will be the same.
>
>
> Property accesses should not mutate the receiver, and because of how
> Sequences work, inspecting first may consume the first element. I suggest
> you consider adding a BufferedSequence that has a
> stable first property (at least until it is iterated)
>
> Another related adapter I’d like to add is a model of CollectionType that
> is backed by a sequence and lazily populated in fixed-sized chunks.
>
>
> -Dave
>
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] About the PermutationGenerator

2015-12-31 Thread Susan Cheng via swift-evolution
As I know SequenceType should have behaved as immutable structure and it
provides method to get a mutable GeneratorType which generates value from
start of sequence.
But the PermutationGenerator break this rule, every time it changes it's
state, it cannot get the generator with the start of sequence.
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] sortBy, minElementBy and maxElementBy methods

2015-12-31 Thread Susan Cheng via swift-evolution
It's a choice with overriding methods or provide a global function which's
missing @noescape version and has to write documentation to telling people
what's it doing.

However, sortBy method is common in other languages.

Dave Abrahams  於 2015年12月31日星期四 寫道:

> You don’t.  Is that a problem for the intended use-cases?
>
> -Dave
>
> On Dec 31, 2015, at 12:11 AM, Susan Cheng  > wrote:
>
> And how do you write a @noescape version with this function?
>
> Dave Abrahams  > 於 2015年12月31日星期四
> 寫道:
>
>> I don’t understand that argument.  Obviously the function would be
>> documented and there would be examples showing how to use it.  Why would it
>> confuse people?
>>
>> I think you’d need much stronger reasons to justify adding an unbounded
>> set of overloads (is every algorithm that takes a comparison closure going
>> to get one of these?) when we can handle the problem economically with a
>> single function.
>>
>> -Dave
>>
>> On Dec 31, 2015, at 12:04 AM, Susan Cheng  wrote:
>>
>> It confuses people if provide a global function byComparing in stdlib
>> which's doing nothing alone.
>>
>> Dave Abrahams  於 2015年12月31日星期四 寫道:
>>
>>> Why add all those algorithms when you can write this
>>>
>>> func byComparing(getComparisonKey: (T)->U) -> (T, T)
>>> -> Bool {
>>>   return { getComparisonKey($0) < getComparisonKey($1) }
>>> }
>>>
>>> peoples.sort(byComparing { $0.name })
>>>
>>> ?
>>>
>>> -Dave
>>>
>>> On Dec 30, 2015, at 10:38 PM, Susan Cheng via swift-evolution <
>>> swift-evolution@swift.org> wrote:
>>>
>>>
>>> Consider the follows:
>>>
>>> struct Person {
>>>
>>> var name: String
>>> var age: Int
>>> }
>>>
>>> let peoples = [Person(name: "Hawk", age: 24), Person(name: "Andrew",
>>> age: 23)]
>>>
>>> let youngest = peoples.minElement { $0.age < $1.age }
>>>
>>> print(youngest?.name)
>>>
>>> it's silly that we always have to write the code like { $0.some < $1.
>>> some } or { some($0) < some($1) }
>>>
>>> so, we should add those methods to stdlib:
>>>
>>> extension SequenceType {
>>> /// Returns the minimum element in `self` or `nil` if the sequence
>>> is empty.
>>> ///
>>> /// - Complexity: O(`elements.count`).
>>> ///
>>> @warn_unused_result
>>> public func minElement(@noescape by:
>>> (Generator.Element) throws -> R) rethrows -> Generator.Element? {
>>> return try self.minElement { try by($0) < by($1) }
>>> }
>>> /// Returns the maximum element in `self` or `nil` if the sequence
>>> is empty.
>>> ///
>>> /// - Complexity: O(`elements.count`).
>>> ///
>>> @warn_unused_result
>>> public func maxElement(@noescape by:
>>> (Generator.Element) throws -> R) rethrows -> Generator.Element? {
>>> return try self.maxElement { try by($0) < by($1) }
>>> }
>>> }
>>>
>>> public extension MutableCollectionType {
>>>
>>> /// Return an `Array` containing the sorted elements of `source`.
>>> /// according to `by`.
>>> ///
>>> /// The sorting algorithm is not stable (can change the relative
>>> order of
>>> /// elements that compare equal).
>>> @warn_unused_result(mutable_variant="sortInPlace")
>>> func sort(@noescape by: (Generator.Element) -> R)
>>> -> [Generator.Element] {
>>> return self.sort { by($0) < by($1) }
>>> }
>>> }
>>>
>>> public extension MutableCollectionType where Self.Index :
>>> RandomAccessIndexType {
>>>
>>> /// Sort `self` in-place according to `by`.
>>> ///
>>> /// The sorting algorithm is not stable (can change the relative
>>> order of
>>> /// elements that compare equal).
>>> mutating func sortInPlace(@noescape by: (Generator.
>>> Element) -> R) {
>>> self.sortInPlace { by($0) < by($1) }
>>> }
>>> }
>>>
>>> ___
>>> 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] sortBy, minElementBy and maxElementBy methods

2015-12-31 Thread Susan Cheng via swift-evolution
yes.
Shouldn't have shorter names to replace the minElementBy, maxElementBy and
sortInPlaceBy

minBy and maxBy?

Jacob Bandes-Storch  於 2015年12月31日星期四 寫道:

> +1, although I wonder if the method names should be distinct (such as
> minElementBy, sortBy, etc.)
>
> On Wed, Dec 30, 2015 at 10:38 PM, Susan Cheng via swift-evolution <
> swift-evolution@swift.org
> > wrote:
>
>>
>> Consider the follows:
>>
>>
>> struct Person {
>>
>>
>>
>> var name: String
>>
>> var age: Int
>>
>> }
>>
>>
>> let peoples = [Person(name: "Hawk", age: 24), Person(name: "Andrew",
>> age: 23)]
>>
>>
>> let youngest = peoples.minElement { $0.age < $1.age }
>>
>>
>> print(youngest?.name)
>>
>>
>> it's silly that we always have to write the code like { $0.some < $1.some }
>> or { some($0) < some($1) }
>>
>>
>> so, we should add those methods to stdlib:
>>
>>
>> extension SequenceType {
>>
>> /// Returns the minimum element in `self` or `nil` if the sequence
>> is empty.
>>
>> ///
>>
>> /// - Complexity: O(`elements.count`).
>>
>> ///
>>
>> @warn_unused_result
>>
>> public func minElement(@noescape by:
>> (Generator.Element) throws -> R) rethrows -> Generator.Element? {
>>
>> return try self.minElement { try by($0) < by($1) }
>>
>> }
>>
>> /// Returns the maximum element in `self` or `nil` if the sequence
>> is empty.
>>
>> ///
>>
>> /// - Complexity: O(`elements.count`).
>>
>> ///
>>
>> @warn_unused_result
>>
>> public func maxElement(@noescape by:
>> (Generator.Element) throws -> R) rethrows -> Generator.Element? {
>>
>> return try self.maxElement { try by($0) < by($1) }
>>
>> }
>>
>> }
>>
>>
>> public extension MutableCollectionType {
>>
>>
>>
>> /// Return an `Array` containing the sorted elements of `source`.
>>
>> /// according to `by`.
>>
>> ///
>>
>> /// The sorting algorithm is not stable (can change the relative
>> order of
>>
>> /// elements that compare equal).
>>
>> @warn_unused_result(mutable_variant="sortInPlace")
>>
>> func sort(@noescape by: (Generator.Element) -> R) ->
>> [Generator.Element] {
>>
>> return self.sort { by($0) < by($1) }
>>
>> }
>>
>> }
>>
>>
>> public extension MutableCollectionType where Self.Index :
>> RandomAccessIndexType {
>>
>>
>>
>> /// Sort `self` in-place according to `by`.
>>
>> ///
>>
>> /// The sorting algorithm is not stable (can change the relative
>> order of
>>
>> /// elements that compare equal).
>>
>> mutating func sortInPlace(@noescape by: (Generator.
>> Element) -> R) {
>>
>> self.sortInPlace { by($0) < by($1) }
>>
>> }
>>
>> }
>>
>>
>> ___
>> 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] sortBy, minElementBy and maxElementBy methods

2015-12-31 Thread Susan Cheng via swift-evolution
And how do you write a @noescape version with this function?

Dave Abrahams  於 2015年12月31日星期四 寫道:

> I don’t understand that argument.  Obviously the function would be
> documented and there would be examples showing how to use it.  Why would it
> confuse people?
>
> I think you’d need much stronger reasons to justify adding an unbounded
> set of overloads (is every algorithm that takes a comparison closure going
> to get one of these?) when we can handle the problem economically with a
> single function.
>
> -Dave
>
> On Dec 31, 2015, at 12:04 AM, Susan Cheng  > wrote:
>
> It confuses people if provide a global function byComparing in stdlib
> which's doing nothing alone.
>
> Dave Abrahams  > 於 2015年12月31日星期四
> 寫道:
>
>> Why add all those algorithms when you can write this
>>
>> func byComparing(getComparisonKey: (T)->U) -> (T, T) ->
>> Bool {
>>   return { getComparisonKey($0) < getComparisonKey($1) }
>> }
>>
>> peoples.sort(byComparing { $0.name })
>>
>> ?
>>
>> -Dave
>>
>> On Dec 30, 2015, at 10:38 PM, Susan Cheng via swift-evolution <
>> swift-evolution@swift.org> wrote:
>>
>>
>> Consider the follows:
>>
>> struct Person {
>>
>> var name: String
>> var age: Int
>> }
>>
>> let peoples = [Person(name: "Hawk", age: 24), Person(name: "Andrew",
>> age: 23)]
>>
>> let youngest = peoples.minElement { $0.age < $1.age }
>>
>> print(youngest?.name)
>>
>> it's silly that we always have to write the code like { $0.some < $1.some }
>> or { some($0) < some($1) }
>>
>> so, we should add those methods to stdlib:
>>
>> extension SequenceType {
>> /// Returns the minimum element in `self` or `nil` if the sequence
>> is empty.
>> ///
>> /// - Complexity: O(`elements.count`).
>> ///
>> @warn_unused_result
>> public func minElement(@noescape by:
>> (Generator.Element) throws -> R) rethrows -> Generator.Element? {
>> return try self.minElement { try by($0) < by($1) }
>> }
>> /// Returns the maximum element in `self` or `nil` if the sequence
>> is empty.
>> ///
>> /// - Complexity: O(`elements.count`).
>> ///
>> @warn_unused_result
>> public func maxElement(@noescape by:
>> (Generator.Element) throws -> R) rethrows -> Generator.Element? {
>> return try self.maxElement { try by($0) < by($1) }
>> }
>> }
>>
>> public extension MutableCollectionType {
>>
>> /// Return an `Array` containing the sorted elements of `source`.
>> /// according to `by`.
>> ///
>> /// The sorting algorithm is not stable (can change the relative
>> order of
>> /// elements that compare equal).
>> @warn_unused_result(mutable_variant="sortInPlace")
>> func sort(@noescape by: (Generator.Element) -> R) ->
>> [Generator.Element] {
>> return self.sort { by($0) < by($1) }
>> }
>> }
>>
>> public extension MutableCollectionType where Self.Index :
>> RandomAccessIndexType {
>>
>> /// Sort `self` in-place according to `by`.
>> ///
>> /// The sorting algorithm is not stable (can change the relative
>> order of
>> /// elements that compare equal).
>> mutating func sortInPlace(@noescape by: (Generator.
>> Element) -> R) {
>> self.sortInPlace { by($0) < by($1) }
>> }
>> }
>>
>> ___
>> 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] sortBy, minElementBy and maxElementBy methods

2015-12-31 Thread Susan Cheng via swift-evolution
It confuses people if provide a global function byComparing in stdlib
which's doing nothing alone.

Dave Abrahams  於 2015年12月31日星期四 寫道:

> Why add all those algorithms when you can write this
>
> func byComparing(getComparisonKey: (T)->U) -> (T, T) ->
> Bool {
>   return { getComparisonKey($0) < getComparisonKey($1) }
> }
>
> peoples.sort(byComparing { $0.name })
>
> ?
>
> -Dave
>
> On Dec 30, 2015, at 10:38 PM, Susan Cheng via swift-evolution <
> swift-evolution@swift.org
> > wrote:
>
>
> Consider the follows:
>
> struct Person {
>
>
> var name: String
> var age: Int
> }
>
> let peoples = [Person(name: "Hawk", age: 24), Person(name: "Andrew", age:
> 23)]
>
> let youngest = peoples.minElement { $0.age < $1.age }
>
> print(youngest?.name)
>
> it's silly that we always have to write the code like { $0.some < $1.some }
> or { some($0) < some($1) }
>
> so, we should add those methods to stdlib:
>
> extension SequenceType {
> /// Returns the minimum element in `self` or `nil` if the sequence is
> empty.
> ///
> /// - Complexity: O(`elements.count`).
> ///
> @warn_unused_result
> public func minElement(@noescape by:
> (Generator.Element) throws -> R) rethrows -> Generator.Element? {
> return try self.minElement { try by($0) < by($1) }
> }
> /// Returns the maximum element in `self` or `nil` if the sequence is
> empty.
> ///
> /// - Complexity: O(`elements.count`).
> ///
> @warn_unused_result
> public func maxElement(@noescape by:
> (Generator.Element) throws -> R) rethrows -> Generator.Element? {
> return try self.maxElement { try by($0) < by($1) }
> }
> }
>
> public extension MutableCollectionType {
>
>
> /// Return an `Array` containing the sorted elements of `source`.
> /// according to `by`.
> ///
> /// The sorting algorithm is not stable (can change the relative
> order of
> /// elements that compare equal).
> @warn_unused_result(mutable_variant="sortInPlace")
> func sort(@noescape by: (Generator.Element) -> R) -> [
> Generator.Element] {
> return self.sort { by($0) < by($1) }
> }
> }
>
> public extension MutableCollectionType where Self.Index :
> RandomAccessIndexType {
>
>
> /// Sort `self` in-place according to `by`.
> ///
> /// The sorting algorithm is not stable (can change the relative
> order of
> /// elements that compare equal).
> mutating func sortInPlace(@noescape by: (Generator.
> Element) -> R) {
> self.sortInPlace { by($0) < by($1) }
> }
> }
>
> ___
> 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] missing proposal about missing @noescape of 'SequenceType.flatMap'

2015-12-30 Thread Susan Cheng via swift-evolution
Hi,

I found the thread about missing attribute @noescape of
'SequenceType.flatMap' but it doesn't have a proposal in swift-evolution:
https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151207/001025.html

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


[swift-evolution] sortBy, minElementBy and maxElementBy methods

2015-12-30 Thread Susan Cheng via swift-evolution
Consider the follows:


struct Person {



var name: String

var age: Int

}


let peoples = [Person(name: "Hawk", age: 24), Person(name: "Andrew", age: 23
)]


let youngest = peoples.minElement { $0.age < $1.age }


print(youngest?.name)


it's silly that we always have to write the code like { $0.some < $1.some }
or { some($0) < some($1) }


so, we should add those methods to stdlib:


extension SequenceType {

/// Returns the minimum element in `self` or `nil` if the sequence is
empty.

///

/// - Complexity: O(`elements.count`).

///

@warn_unused_result

public func minElement(@noescape by:
(Generator.Element) throws -> R) rethrows -> Generator.Element? {

return try self.minElement { try by($0) < by($1) }

}

/// Returns the maximum element in `self` or `nil` if the sequence is
empty.

///

/// - Complexity: O(`elements.count`).

///

@warn_unused_result

public func maxElement(@noescape by:
(Generator.Element) throws -> R) rethrows -> Generator.Element? {

return try self.maxElement { try by($0) < by($1) }

}

}


public extension MutableCollectionType {



/// Return an `Array` containing the sorted elements of `source`.

/// according to `by`.

///

/// The sorting algorithm is not stable (can change the relative order
of

/// elements that compare equal).

@warn_unused_result(mutable_variant="sortInPlace")

func sort(@noescape by: (Generator.Element) -> R) -> [
Generator.Element] {

return self.sort { by($0) < by($1) }

}

}


public extension MutableCollectionType where Self.Index :
RandomAccessIndexType {



/// Sort `self` in-place according to `by`.

///

/// The sorting algorithm is not stable (can change the relative order
of

/// elements that compare equal).

mutating func sortInPlace(@noescape by: (Generator.
Element) -> R) {

self.sortInPlace { by($0) < by($1) }

}

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


[swift-evolution] About the PermutationGenerator

2015-12-30 Thread Susan Cheng via swift-evolution
PermutationGenerator confuses me that it's confirm to both of SequenceType
and GeneratorType. Should it replace by PermutationSequence and
PermutationGenerator?


Also, we should have a PermutationCollection because we can:


public struct PermutationCollection : CollectionType {



public typealias Generator = PermutationGenerator



public typealias Index = I.Index

public typealias Element = C.Generator.Element



private let _base: C

private let _indices: I



public subscript(idx: Index) -> Element {

return _base[_indices[idx]]

}



public var startIndex : Index {

return _indices.startIndex

}

public var endIndex : Index {

return _indices.endIndex

}



public var count : Index.Distance {

return _indices.count

}



public func generate() -> Generator {

return PermutationGenerator(elements: _base, indices: _indices)

}

}


and some methods provide:


public extension CollectionType {



@warn_unused_result

func collect(indices:
I) -> PermutationGenerator {

return PermutationGenerator(elements: self, indices: indices)

}



@warn_unused_result

func collect(indices:
I) -> PermutationCollection {

return PermutationCollection(_base: self, _indices: indices)

}

}


public extension LazyCollectionType {



@warn_unused_result

func collect(indices: I) -> LazySequence> {

return self.elements.collect(indices).lazy

}



@warn_unused_result

func collect(indices: I) -> LazyCollection> {

return self.elements.collect(indices).lazy

}

}
___
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 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] Proposal: Add scan, takeWhile, dropWhile, and iterate to the stdlib

2015-12-28 Thread Susan Cheng via swift-evolution
Consider:

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
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Coroutine for Swift

2015-12-22 Thread Susan Cheng via swift-evolution
Hi,

I just want a wide public concern in swift community with this
implementation.
Should we have a proposal about @goto and @label as workaround? Just a joke
;)

Chris Lattner  於 2015年12月23日星期三 寫道:

> Hi Susan,
>
> As I mentioned on your original pull request, coroutines are closely
> related to async and other concurrency forms.  That entire space is out of
> scope for Swift 3, so we should wait until fall 2016 to pick up discussion
> on this and related topics.
>
> -Chris
>
> On Dec 22, 2015, at 12:16 PM, Andrew Bennett via swift-evolution <
> swift-evolution@swift.org
> > wrote:
>
> Hi Daniel,
>
> I've heard many great things about goroutines, and I definitively think
> their advantages should be considered in the design of Swift's concurrency.
>
> I haven't used goroutines much so I may be incorrect, but I don't think
> they can be used to efficiently represent a generator like the proposal
> suggests.
>
> The generator described in the proposal has the following properties:
>  * it is basically just syntactic sugar
>  * new elements are generated lazily
>  * the length doesn't need to be known at initialisation
>  * it uses existing function syntax in the caller
>  * it can all run on one thread
>  * concurrency considerations may be limited to safely updating the state
> variable from more than one thread
>
> Maybe goroutines can be equivalent if the compiler can optimise it down to
> a generator. This proposal is basically syntactic sugar to concisely define
> a generator. Goroutines probably aren't a concise replacement for that
> sugar.
>
>
> On Wednesday, 23 December 2015, Daniel Valls Estella  > wrote:
>
>>
>> Ok,
>>
>> But I think goroutines are not really threads (are faster and cheaper
>> enought to make a diference) and channels are more like filedescriptors
>> than signals, you stream data throught these.
>>
>> Thanks for your answer!
>>
>> Daniel
>>
>> Daniel Valls Estella · tel. 659.910.830 · dan...@upzzle.com
>>
>> El 22 des 2015, a les 11:50, Susan Cheng  va
>> escriure:
>>
>> It's a little difference with goroutine. Go using threads and signal.
>> My implementation is following C# methods that MS staff tells me.
>>
>> Daniel Valls Estella  於 2015年12月22日星期二 寫道:
>>
>>> I think it’s better to take as a reference the *Go* language and his
>>> *goroutines* and *channels*.
>>>
>>> Not just to face these type of problems but also to take new
>>> architectural aproches to build software solutions.
>>>
>>>
>>> refs:
>>>
>>> https://tour.golang.org/concurrency/1
>>> https://tour.golang.org/concurrency/2
>>> https://tour.golang.org/concurrency/5
>>> https://youtu.be/f6kdp27TYZs
>>>
>>>
>>> What you think?
>>>
>>> Daniel
>>>
>>> Daniel Valls Estella · tel. 659.910.830 · dan...@upzzle.com
>>>
>>> El 22 des 2015, a les 8:33, Andrew Bennett via swift-evolution <
>>> swift-evolution@swift.org> va escriure:
>>>
>>> Great proposal! I'm all for this, I think your proposed implementation
>>> is pretty good too.
>>>
>>> It would be interesting to expand the proposal to consider more cases in
>>> more detail:
>>>  * Concurrency
>>>  * SequenceType versus GeneratorType
>>>  * Should a language feature depend on the Standard Library
>>> (GeneratorType)? Alternatives:
>>>  + func myFunction -> () -> T?
>>>  + func myFunction -> () -> (myFunction_State, myFunction_State ->
>>> T?)
>>>  * What happens if you write: guard ... else { yield ... }
>>>  * Use an enum for the state that encapsulates all possible variables in
>>> each state
>>>
>>> If you're not familiar with it, there's another thread that discussed
>>> similar here:
>>>
>>> https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151207/001872.html
>>>
>>> In particular you may be interested in Chris Lattner's comment:
>>>
>>> I’m very interested in this, but it is clearly out of scope for Swift 3.
>>> It should also be considered alongside whatever async/concurrency approach
>>> we tackle (likely in swift 4).
>>>
>>>
>>> Either way it's worth discussing and working towards :)
>>>
>>> On Tue, Dec 22, 2015 at 6:03 PM, Félix Cloutier <
>>> swift-evolution@swift.org> wrote:
>>>
>>>> Th

Re: [swift-evolution] Coroutine for Swift

2015-12-22 Thread Susan Cheng via swift-evolution
It's a little difference with goroutine. Go using threads and signal.
My implementation is following C# methods that MS staff tells me.

Daniel Valls Estella  於 2015年12月22日星期二 寫道:

> I think it’s better to take as a reference the *Go* language and his
> *goroutines* and *channels*.
>
> Not just to face these type of problems but also to take new architectural
> aproches to build software solutions.
>
>
> refs:
>
> https://tour.golang.org/concurrency/1
> https://tour.golang.org/concurrency/2
> https://tour.golang.org/concurrency/5
> https://youtu.be/f6kdp27TYZs
>
>
> What you think?
>
> Daniel
>
> Daniel Valls Estella · tel. 659.910.830 · dan...@upzzle.com
> 
>
> El 22 des 2015, a les 8:33, Andrew Bennett via swift-evolution <
> swift-evolution@swift.org
> > va escriure:
>
> Great proposal! I'm all for this, I think your proposed implementation is
> pretty good too.
>
> It would be interesting to expand the proposal to consider more cases in
> more detail:
>  * Concurrency
>  * SequenceType versus GeneratorType
>  * Should a language feature depend on the Standard Library
> (GeneratorType)? Alternatives:
>  + func myFunction -> () -> T?
>  + func myFunction -> () -> (myFunction_State, myFunction_State -> T?)
>  * What happens if you write: guard ... else { yield ... }
>  * Use an enum for the state that encapsulates all possible variables in
> each state
>
> If you're not familiar with it, there's another thread that discussed
> similar here:
>
> https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151207/001872.html
>
> In particular you may be interested in Chris Lattner's comment:
>
> I’m very interested in this, but it is clearly out of scope for Swift 3.
> It should also be considered alongside whatever async/concurrency approach
> we tackle (likely in swift 4).
>
>
> Either way it's worth discussing and working towards :)
>
> On Tue, Dec 22, 2015 at 6:03 PM, Félix Cloutier  > wrote:
>
>> There's probably some additional work to do on the proposal document, but
>> I would like to see coroutines in Swift too. The feature has been very
>> successful in other languages like Python and C#, and unless I'm mistaken,
>> work is being done to standardize it in C++.
>>
>> Generators are one use case, but resumable functions in general can also
>> be used to make async code look prettier.
>>
>> Félix
>>
>> Le 22 déc. 2015 à 01:47:05, Susan Cheng via swift-evolution <
>> swift-evolution@swift.org
>> > a écrit :
>>
>> here is my proposal for swift lang
>>
>>
>> https://github.com/SusanDoggie/swift-evolution/blob/master/proposals/0018-coroutine-for-swift.md
>> ___
>> 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
>
>
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


[swift-evolution] Fwd: Coroutine for Swift

2015-12-22 Thread Susan Cheng via swift-evolution
-- Forwarded message --
From: Susan Cheng 
Date: 2015-12-22 16:19 GMT+08:00
Subject: Re: [swift-evolution] Coroutine for Swift
To: Andrew Bennett 


Hi, Andrew Bennett

I have updated the proposal with some of your suggestions.

Susan

2015-12-22 15:33 GMT+08:00 Andrew Bennett :

> Great proposal! I'm all for this, I think your proposed implementation is
> pretty good too.
>
> It would be interesting to expand the proposal to consider more cases in
> more detail:
>  * Concurrency
>  * SequenceType versus GeneratorType
>  * Should a language feature depend on the Standard Library
> (GeneratorType)? Alternatives:
>  + func myFunction -> () -> T?
>  + func myFunction -> () -> (myFunction_State, myFunction_State -> T?)
>  * What happens if you write: guard ... else { yield ... }
>  * Use an enum for the state that encapsulates all possible variables in
> each state
>
> If you're not familiar with it, there's another thread that discussed
> similar here:
>
> https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151207/001872.html
>
> In particular you may be interested in Chris Lattner's comment:
>
> I’m very interested in this, but it is clearly out of scope for Swift 3.
> It should also be considered alongside whatever async/concurrency approach
> we tackle (likely in swift 4).
>
>
> Either way it's worth discussing and working towards :)
>
> On Tue, Dec 22, 2015 at 6:03 PM, Félix Cloutier  > wrote:
>
>> There's probably some additional work to do on the proposal document, but
>> I would like to see coroutines in Swift too. The feature has been very
>> successful in other languages like Python and C#, and unless I'm mistaken,
>> work is being done to standardize it in C++.
>>
>> Generators are one use case, but resumable functions in general can also
>> be used to make async code look prettier.
>>
>> Félix
>>
>> Le 22 déc. 2015 à 01:47:05, Susan Cheng via swift-evolution <
>> swift-evolution@swift.org> a écrit :
>>
>> here is my proposal for swift lang
>>
>>
>> https://github.com/SusanDoggie/swift-evolution/blob/master/proposals/0018-coroutine-for-swift.md
>> ___
>> 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] Coroutine for Swift

2015-12-22 Thread Susan Cheng via swift-evolution
with consider defer statement
we can clean up the memory if coroutine is not completed.

i have updated the proposal.

2015-12-22 15:33 GMT+08:00 Andrew Bennett :

> Great proposal! I'm all for this, I think your proposed implementation is
> pretty good too.
>
> It would be interesting to expand the proposal to consider more cases in
> more detail:
>  * Concurrency
>  * SequenceType versus GeneratorType
>  * Should a language feature depend on the Standard Library
> (GeneratorType)? Alternatives:
>  + func myFunction -> () -> T?
>  + func myFunction -> () -> (myFunction_State, myFunction_State -> T?)
>  * What happens if you write: guard ... else { yield ... }
>  * Use an enum for the state that encapsulates all possible variables in
> each state
>
> If you're not familiar with it, there's another thread that discussed
> similar here:
>
> https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151207/001872.html
>
> In particular you may be interested in Chris Lattner's comment:
>
> I’m very interested in this, but it is clearly out of scope for Swift 3.
> It should also be considered alongside whatever async/concurrency approach
> we tackle (likely in swift 4).
>
>
> Either way it's worth discussing and working towards :)
>
> On Tue, Dec 22, 2015 at 6:03 PM, Félix Cloutier  > wrote:
>
>> There's probably some additional work to do on the proposal document, but
>> I would like to see coroutines in Swift too. The feature has been very
>> successful in other languages like Python and C#, and unless I'm mistaken,
>> work is being done to standardize it in C++.
>>
>> Generators are one use case, but resumable functions in general can also
>> be used to make async code look prettier.
>>
>> Félix
>>
>> Le 22 déc. 2015 à 01:47:05, Susan Cheng via swift-evolution <
>> swift-evolution@swift.org> a écrit :
>>
>> here is my proposal for swift lang
>>
>>
>> https://github.com/SusanDoggie/swift-evolution/blob/master/proposals/0018-coroutine-for-swift.md
>> ___
>> 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


[swift-evolution] Coroutine for Swift

2015-12-21 Thread Susan Cheng via swift-evolution
here is my proposal for swift lang

https://github.com/SusanDoggie/swift-evolution/blob/master/proposals/0018-coroutine-for-swift.md
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution