Re: [swift-evolution] [Proposal] Random Unification

2017-12-01 Thread Xiaodi Wu via swift-evolution
On Thu, Nov 30, 2017 at 6:55 PM, Nate Cook  wrote:

>
> On Nov 30, 2017, at 6:20 PM, Xiaodi Wu  wrote:
>
> On Thu, Nov 30, 2017 at 5:24 PM, Nate Cook  wrote:
>
>> On Nov 30, 2017, at 4:30 PM, Xiaodi Wu via swift-evolution <
>> swift-evolution@swift.org> wrote:
>>
>> On Thu, Nov 30, 2017 at 3:58 PM, Dave DeLong via swift-evolution <
>> swift-evolution@swift.org> wrote:
>>
>>>
>>>
>>> On Nov 30, 2017, at 2:48 PM, Jonathan Hull via swift-evolution <
>>> swift-evolution@swift.org> wrote:
>>>
>>> I would personally go with:
>>>
>>> Int.random //Returns a random Int
>>>
>>>
>>> “Type.random” is so rarely used as to not be worth the addition, IMO. If
>>> you really need a random element from the *entire* domain, then I think you
>>> should have to manually create the ClosedRange yourself.
>>>
>>> Int.random(in: ClosedRange) //Works for Comparable types. Gives a
>>> result from the closed range. Closed Range is never empty.
>>>
>>>
>>> This is redundant. In order to pick a random element, you’re saying I
>>> should have to do “Int.random(0 ..< 10)”? The redundancy here is that I
>>> have to specify Int twice: once for the “.random” call, and again for the
>>> type of the range. We can do better than that.
>>>
>>
>> I don’t see how this is redundant—do you mean that you’d need to write
>> out the type name instead of writing `(0..<10).random()!`? I continue to be
>> of the opinion that picking a random integer/floating-point value/Boolean
>> and picking a random element from a collection are two different
>> operations. Yes, there’s overlap between the two, but they’re different
>> enough that having two ways to choose an integer between 0 and 10 would be
>> fine.
>>
>
> As I wrote elsewhere, if they're sufficiently different enough, then they
> ought to have distinct names. If they are not, then there ought to be only
> one of them. I'm no longer sure myself of which one I'd prefer, but in no
> case should there be two things named "random."
>
> If the proposal to make `IndexDistance == Int` is accepted, then ranges
> cannot conform to Collection and we encounter some interesting difficulties
> attempting to index into such a collection to pick a random value.
>
> [0,2,3].randomElement //Returns a random element from the collection
>>>
>>>
>>> I strongly believe this should be a method, not a property. Properties,
>>> like .first and .last, are expected to return the same value each time you
>>> access them. “.random” inherently breaks that.
>>>
>>
>> FWIW--and this isn't a vote, I know--I largely agree with Dave DeLong's
>> conclusions above, and for substantially the same reasons.
>>
>>>
>>> Then a version of each with a ‘using:’ parameter which takes a
>>> generator/source:
>>>
>>> Int.random(using: RandomSource) //Returns a random Int using the given
>>> source of randomness
>>> Int.random(in: ClosedRange, using: RandomSource)
>>> [0,2,3].randomElement(using: RandomSource)
>>>
>>> In my own RandomSource & RandomSourceCreatable protocols, I frequently
>>> use random colors and sizes as well.  The issue there is that you really
>>> want a closed range for each dimension. I wish Swift had a better notion of
>>> dimensionality baked into the language.
>>>
>>> What I ended up doing was having a “constraints” parameter which took an
>>> array of constraints which corresponded to various dimensions.  It works
>>> for me, but it might be a bit complex for something in the standard library.
>>>
>>> Honestly, given the current capabilities of Swift what this really calls
>>> for is custom initializers/functions for dimensional types:
>>>
>>> UIColor.random //This comes from the protocol
>>> UIColor.random(hue: ClosedRange = 0…1, saturation:
>>> ClosedRange = 0…1, brightness: ClosedRange = 0…1, alpha:
>>> ClosedRange = 1…1)
>>> //…and of course the same as above, but with ‘using:'
>>>
>>> Then you can easily get random colors which look like they belong
>>> together:
>>> let myColor = UIColor.random(saturation: 0.2…0.2, brightness: 0.6…0.6)
>>>
>>> There would probably also be a convenience version taking CGFloats and
>>> passing them to the real function as ranges:
>>>
>>> let myColor = UIColor.random(saturation: 0.2, brightness: 0.6)
>>>
>>>
>>> This means that our default RandomSource needs to be publicly available,
>>> so that the custom functions can use it as the default…
>>>
>>>
>> It does not. Having actually implemented some version of these APIs, it's
>> readily apparent now to me that all custom types can simply call
>> Int.random(in:) (or UnsafeRawBufferPointer.random(byteCount:), or
>> whatever else we want to have in the standard library) to get random values
>> from the default RNG for any built-in type and size. The actual default
>> random need never be exposed publicly, and since its functions are strictly
>> redundant to these other APIs (which, of course, are the "currency" APIs
>> that our purpose here is to design and make public), the 

Re: [swift-evolution] [Proposal] Random Unification

2017-12-01 Thread Xiaodi Wu via swift-evolution
On Sat, Dec 2, 2017 at 12:23 AM, David Waite 
wrote:

>
>
> On Dec 1, 2017, at 11:05 AM, Erica Sadun via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> I'd like to put forth that Gameplay Kit offers a perfectly cromulent model
> of random number generation and API. Why not take that as a starting point,
> Swiftify it so it becomes a cross platform solution, and then apply the
> specific questions of sequences, collections, and indices as a second step?
>
>
> I don't support intermingling random functionality with existing core
> types.
>
>
> GameplayKit randomization has a number of API deficiencies that we can’t
> easily/efficiently solve by wrapping it in Swift.
>
> Most significantly, it is not designed to support any cryptographic
> operations (which I believe is why they never added a nextBytes() or
> equivalent method).
>
> For GameplayKit this is fine - the design focuses on being able to get the
> distribution appropriate for your game, and being able to have identical
> pseudorandom number sequences for each device in a multiplayer scenario.
> They went as far as to require all random sources to support NSSecureCoding
> so that they may be persisted and/or serialized over the wire, which
> precludes a GKRandomSource from being based on the system random sources.
>

That said, I am not sure that this proposal should give any pretense of
being suitable for cryptographic use. On implementation, the code will not
have been audited for that purpose, although the author very rightly
attempts to use the "best" possible sources of entropy available for each
platform. Perhaps explicitly _not_ supporting cryptographic operations is
the more Swifty way to go (in the sense that, where possible, Swift API
design aims to help users avoid footguns).
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal] Random Unification

2017-12-01 Thread David Waite via swift-evolution


> On Dec 1, 2017, at 11:05 AM, Erica Sadun via swift-evolution 
>  wrote:
> 
> I'd like to put forth that Gameplay Kit offers a perfectly cromulent model of 
> random number generation and API. Why not take that as a starting point, 
> Swiftify it so it becomes a cross platform solution, and then apply the 
> specific questions of sequences, collections, and indices as a second step?  
> 
> I don't support intermingling random functionality with existing core types.
> 

GameplayKit randomization has a number of API deficiencies that we can’t 
easily/efficiently solve by wrapping it in Swift.

Most significantly, it is not designed to support any cryptographic operations 
(which I believe is why they never added a nextBytes() or equivalent method).

For GameplayKit this is fine - the design focuses on being able to get the 
distribution appropriate for your game, and being able to have identical 
pseudorandom number sequences for each device in a multiplayer scenario. They 
went as far as to require all random sources to support NSSecureCoding so that 
they may be persisted and/or serialized over the wire, which precludes a 
GKRandomSource from being based on the system random sources.

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


Re: [swift-evolution] Proposal: Introduce User-defined "Dynamic Member Lookup" Types

2017-12-01 Thread Matthew Johnson via swift-evolution

> On Dec 1, 2017, at 12:23 AM, Chris Lattner  wrote:
> 
>> On Nov 30, 2017, at 6:15 AM, Matthew Johnson  wrote:
>>> 
>>> I think better interoperability with Python (and other OO languages in 
>>> widespread use) is a good goal, and I agree that the implementation of the 
>>> feature described is straight-forward and not terribly invasive in the 
>>> compiler.
>>> 
>>> However, I do not think this proposal is going in the right direction for 
>>> Swift. I have objections on several different grounds.
>> 
>> +1 to everything Doug says here.  He articulates the concerns I tried to 
>> voice in an earlier thread more clearly and more thoroughly.  
> 
> Doug’s email was pretty confusing, so I’ll try to clear up some of the 
> misconceptions here.  I also updated the proposal with a new section at the 
> end, please check it out.

Thank you for your latest reply and the latest reply to Doug.  I can only speak 
for myself, but it helped me to better understand the motivation you have for 
the proposal.  I really do appreciate your view and the motivation behind it.

> 
>> This design introduces a significant hole in the type system which is 
>> contrary to the spirit of Swift.
> 
> There is no “hole” in the type system.  The proposal is fully type safe. 
> 
> Further, the addition is absolutely in the spirit of Swift, because it is 
> directly analogous to an existing feature: AnyObject lookup.  The difference 
> between it and AnyObject lookup is that AnyObject lookup is:
> 
> a) specific to Objective-C interop
> b) type unsafe
> c) massively invasive on the rest of the compiler.
> 
> We’ve made many attempts to narrow the scope of AnyObject lookup, but it is 
> difficult to do so given backwards compatibility constraints and the limited 
> nature of Objective-C metadata.

I may have spoken incorrectly but I do still believe it is contrary to what I 
(and apparently many others) feel is the spirit of Swift.  

As I understand it, AnyObject lookup was a necessity during the historical 
development of Swift.  The attempts to narrow its scope have merit regardless 
of how far they can go.  They indicate that perhaps it is a feature we would 
remove if that were possible.  I would love to see that happen someday 
(although I know it is unlikely), or at least see it be made explicit at the 
call site.  I suspect if this feature did not exist and it was proposed today 
it would be met with at least as much resistance as your proposals have.

> 
>> It doesn’t just make dynamic language interop easy, it also changes the 
>> semantics of any type which conforms to DynamicMemberLookupProtocol.  That 
>> is not something that is locally visible when looking at a piece of code.  
>> Worse, it does so in a way that trivial mistakes such as a typo can turn 
>> into runtime errors.  Worst of all, as Doug points out it is possible to use 
>> retroactive conformance to change the semantics of vast quantities of widely 
>> used types in one fell swoop.
> 
> This is a feature, like many others, which can be misused.  This has not been 
> the metric we have used to judge what should go into Swift.  I can elaborate 
> if my response to Doug wasn’t clear.

The primary problem I have is that misuse is too easy and too subtle.  It is at 
least as easy to misuse as other features in Swift which have been carefully 
designed to be obvious at usage sites.  

I was happy to see that you are willing to consider Xiaodi’s suggestion to 
require conformance to be stated as part of the original type declaration.  
That would be a significant improvement to the proposal IMO.  I strongly urge 
you to reconsider the decision of that dynamic members must be made available 
with no indication at usage sites.  An indication of dynamic lookup at usage 
sites aligns very well (IMO) with the rest of Swift (AnyObject lookup aside) by 
calling attention to code that requires extra care to get right.

> 
>> One additional concern that I don’t believe has been mentioned is that of 
>> evolution.  When a library is imported from a dynamic language and the 
>> library makes breaking changes Swift code written using this feature will 
>> break without notice until a runtime error occurs.  Is that acceptable?  
>> That may be what users of dynamic languages are accustomed to but can we do 
>> better in Swift?  If we can make the process of upgrading dependencies less 
>> a less harrowing experience perhaps that could be a major selling point in 
>> moving them to Swift.  But we won’t accomplish that with this design.
> 
> How would you this to work with *any* interoperability approach?  Dynamic 
> languages are in fact dynamic, and need the ability to do dynamic lookups 
> somehow.  Those dynamic lookups will all have the problem you observe.

I’ll mostly let Doug continue the discussion of the approach he is suggesting.  
It looks to me like that is an approach that might help in this area.  For 
example, if a 

Re: [swift-evolution] Proposal: Introduce User-defined "Dynamic Member Lookup" Types

2017-12-01 Thread Vincent Esche via swift-evolution
Paul Cantrell wrote:

It seems like this fundamentally alters Swift’s aesthetic of “either an
> operation is type-safe, or it’s clear at the point of use that it’s not.”
> Should this use an operator other than a period, e.g. `pickle->loads(blob)`?
>

This is a major concern of mine as well. What you end up by camouflaging
dynamic, unchecked APIs in what looks like normal (i.e. static, checked)
Swift is a wolf in sheeps’ clothing. One would not be able to tell one from
the other, yet would have to juggle two completely orthogonal language
models in one’s mind when reading/writing Swift code.

For me for such a proposal to even be remotely acceptable such dynamic
calls would have to have a clearly distinguishable syntax (`foo.bar?(…)`
would have been a great fit for this, but that ship has sailed).

In order to prevent such dynamic code from getting sprinkled all over the
place (dirt gets everywhere if given enough time) I’d further more expect
entire code blocks to be marked with a label that leans more towards
discouragement, than encouragement, such as:

unchecked {
foo.bar?!(…)
}


Brent Royal-Gordon wrote:

* Let's step away from bridging entirely and just think about Swift for a
> moment. There are cases where we'd like to make *semi*-dynamic proxies
> which wrap another type and allow operations based on what's statically
> known about that type. Think, for example, of the appearance proxy in
> UIKit: This is an object attached to UIView subclasses which lets you (in
> essence) set default values for all instances. We currently just pretend
> it's an instance of `Self`, which mostly works because of Objective-C, but
> a Swift-native version would probably prefer to return a
> `UIAppearance` object which used its knowledge of `Self` to expose
> `Self`'s properties on itself. Is there a way we could design this feature,
> or a related feature, to cover that kind of use case? That is, to allow a
> limited set of keys—perhaps even key-path-based when you want static
> control—with a different type for each key, *or* to allow any key with some
> common type, depending on your type's needs?


This particular use-case (along with NSProxy) looks to me like a perfect us
of a new-type/derive as known from Haskell or Rust, rather than dynamic.
(Albeit there are problems with new-type and types making use of `Self` as
associated types.)

Doug Gregor wrote:

Swift is, unabashedly, a strong statically-typed language.


And thankfully so, if I may say so. There a few places in the language
(other than objc-bridging) where one needs to make us of dynamic features.
But most of these are caused by the fact that Swift’s type system is still
rather limited and certain type relations simply cannot be expressed yet,
forcing one to make use of the type-safety escape hook that is
Any/AnyObject.

IMO, this proposal is a significant departure from the fundamental
> character of Swift, because it allows access to possibly-nonexistent
> members […] without any indication that the operation might fail.


Unless there would be a corresponding compiler flag for marking use of such
dynamic calls as warnings if not errors, the addition of this proposal
would eliminate many of the safety guarantees that Swift gives me for code
written in it for safety critical programs. If one cannot judge about the
safety of a piece of code in Swift by merely looking at it, then what is
the use of a remaining half-baked safety promise to begin with?

Matt Diephouse wrote:

I personally don’t want to work with APIs like this. And while I can
> understand the appeal of easier interop—especially if you’ve come into a
> large library of Python code—IMO this would inevitably lead to other
> misuses of dynamic lookups in 1st- or popular 3rd-party libraries.


Neither do I. The still unfinished nature of Swift’s type checking/system
and lack of meta-programming capabilities will drive users of the language,
who don’t know any better (especially when coming from dynamic languages),
to a wide-spread misuse of such features.

There also is another aspect to it:

The main driving force behind this proposal according to this discussion is
“interop with dynamic languages”.
The majority of language users however work in an environment where such
inter is prohibited: iOS.
Releasing a feature that’s basically shouting “MISUSE ME, MISUSE ME!” at
hundreds of thousands of users who’s pretty much only possible use _is_ a
misuse, and of which many are coming from ObjC or Java and still at odds
with, if not outright denial of Swift’s more strict type rules, is a
terrible foundation, I think.

I also think that we should rather have a syntax sugar freeze until Swift 6
(more on that: http://bit.ly/2BDOFxu
), rather
than adding yet another to the mix without really thinking about the
consequences (lack of coherence, e.g.).

Benjamin G wrote:

A few examples of the kind of things that i would think about :

Re: [swift-evolution] Proposal: Introduce User-defined "Dynamic Member Lookup" Types

2017-12-01 Thread Dave DeLong via swift-evolution
This email reminded me of something…

One of the beautiful things about the announcement of Swift in 2014 was that no 
one saw it coming, even though a whole bunch of signs were in place. One of 
those signs was Objective-C Modules, which *essentially* describe an API in an 
abstract syntax, so that it can be used from another language. (It was billed 
as  making compilation faster , but IIRC this was one 
of its trojan purposes).

Can that same tactic be used here? Can we somehow generate modules for python 
code, and then import those modules as the basis for cross-library invocations? 

Dave


> On Dec 1, 2017, at 1:49 PM, Marc Schlichte via swift-evolution 
>  wrote:
> 
> A somewhat extreme alternative could be the use of IDLs and "libs as 
> services“:
> 
> A Python lib could aditionally expose its APIs (or a relevant subset of it) 
> via an IDL. Generators would help with the necessary stub and skeleton code 
> on both Python and Swift sides.
> 
> My impression is that only big libs like TensorFlow are relevant to be 
> bridged anyhow so that the effort to create an IDLized API for that community 
> is acceptable.
> 
> IDLs are an old idea but they seem to get reinvented every now and then. 
> Google has a new one called FIDL for its Fuchsia project: 
> (https://fuchsia.googlesource.com/fidl/ 
> )
> 
> Cheers
> Marc
> 
> 
> 
> 
>> Am 01.12.2017 um 17:07 schrieb Jon Gilbert via swift-evolution 
>> >:
>> 
>> On Dec 1, 2017, at 02:44, Xiaodi Wu via swift-evolution 
>> > wrote:
>> 
>>> So the use case here is, how do we make Swift a viable candidate for doing 
>>> those things which today drive users to Python? The answer here is _not_: 
>>> build a better Python. Nor does it require, out of the gate, even being as 
>>> good as Python. The solution is to provide a _reasonably_ ergonomic to 
>>> _interoperate with libraries available in Python_, with the benefit that 
>>> those parts that you can write in native Swift will make the overall result 
>>> safer and faster, etc.
>> 
>> I think we would be better served by a transpiler that translates Python 
>> (etc.) into Swift at compile time. 
>> 
>> Look what Google did with j2objc (https://github.com/google/j2objc 
>> ). It translates Java right into Objective 
>> C. You can even put your Java code right in XCode and it auto-translates at 
>> build time. 
>> 
>> Clearly, this is no small feat, and j2objc is a technical marvel that took 
>> world-class engineers years to perfect. 
>> 
>> My point is, “Dynamic Member Lookup” is not the only solution, and it’s not 
>> the ideal solution if indeed it compromises the static guarantees of Swift.
>> 
>> Therefore, we should consider what other approaches might entail. The main 
>> players in Swift have lots of money and technical resources they could pour 
>> into a set of revolutionary transpilers. 
>> 
>> Surely we don’t want to allow Goole to be the only company to provide a 
>> library that translates other codebases directly to a primarily Apple 
>> language, do we?
>> 
>> That being said, I am still interested to hear Chris’s response to these 
>> concerns, and if they were already addressed on a previous message and I 
>> missed that, then please forgive me.
>> 
>> - Jon
>> ___
>> 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] array splatting for variadic parameters

2017-12-01 Thread Tino Heth via swift-evolution
> What about calling a framework variadic function that I could not re-declare?
> like print
That’s a good question — in „regular“ frameworks, variadic functions as we have 
them now wouldn’t exist anymore, but C is a different story…
My expectation (without deep knowledge of the compatibility-layer) is that it 
isn't hard to solve this; after all, it’s basically just a small change in 
syntax (although afair, T… is a special case in the type system).

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


Re: [swift-evolution] Proposal: Introduce User-defined "Dynamic Member Lookup" Types

2017-12-01 Thread Marc Schlichte via swift-evolution
A somewhat extreme alternative could be the use of IDLs and "libs as services“:

A Python lib could aditionally expose its APIs (or a relevant subset of it) via 
an IDL. Generators would help with the necessary stub and skeleton code on both 
Python and Swift sides.

My impression is that only big libs like TensorFlow are relevant to be bridged 
anyhow so that the effort to create an IDLized API for that community is 
acceptable.

IDLs are an old idea but they seem to get reinvented every now and then. Google 
has a new one called FIDL for its Fuchsia project: 
(https://fuchsia.googlesource.com/fidl/)

Cheers
Marc




> Am 01.12.2017 um 17:07 schrieb Jon Gilbert via swift-evolution 
> :
> 
> On Dec 1, 2017, at 02:44, Xiaodi Wu via swift-evolution 
> > wrote:
> 
>> So the use case here is, how do we make Swift a viable candidate for doing 
>> those things which today drive users to Python? The answer here is _not_: 
>> build a better Python. Nor does it require, out of the gate, even being as 
>> good as Python. The solution is to provide a _reasonably_ ergonomic to 
>> _interoperate with libraries available in Python_, with the benefit that 
>> those parts that you can write in native Swift will make the overall result 
>> safer and faster, etc.
> 
> I think we would be better served by a transpiler that translates Python 
> (etc.) into Swift at compile time. 
> 
> Look what Google did with j2objc (https://github.com/google/j2objc 
> ). It translates Java right into Objective 
> C. You can even put your Java code right in XCode and it auto-translates at 
> build time. 
> 
> Clearly, this is no small feat, and j2objc is a technical marvel that took 
> world-class engineers years to perfect. 
> 
> My point is, “Dynamic Member Lookup” is not the only solution, and it’s not 
> the ideal solution if indeed it compromises the static guarantees of Swift.
> 
> Therefore, we should consider what other approaches might entail. The main 
> players in Swift have lots of money and technical resources they could pour 
> into a set of revolutionary transpilers. 
> 
> Surely we don’t want to allow Goole to be the only company to provide a 
> library that translates other codebases directly to a primarily Apple 
> language, do we?
> 
> That being said, I am still interested to hear Chris’s response to these 
> concerns, and if they were already addressed on a previous message and I 
> missed that, then please forgive me.
> 
> - Jon
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

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


Re: [swift-evolution] [RFC] Associated type inference

2017-12-01 Thread Nevin Brackett-Rozinsky via swift-evolution
On Thu, Nov 30, 2017 at 7:28 PM, Douglas Gregor via swift-evolution <
swift-evolution@swift.org> wrote:

> *A Rough Proposal*
> I’ve been thinking about this for a bit, and I think there are three ways
> in which we should be able to infer an associated type witness:
>
>
>1. Associated type defaults, which are specified with the associated
>type itself, e.g.,
>
>  associatedtype Indices = DefaultIndices
>
>These are easy to reason about for both the programmer and the
>compiler.
>2. Typealiases in (possibly constrained) protocol extensions, e.g.,
>
>  extension RandomAccessCollection where Index : Strideable,
>Index.Stride == IndexDistance {
>typealias RandomAccessCollection.Indices = CountableRange
>  }
>
>I’m intentionally using some odd ‘.’ syntax here to indicate that this
>typealias is intended only to be found when trying to satisfy an associated
>type requirement, and is not a general typealias that could be found by
>normal name lookup. Let’s set the syntax bike shed aside for the moment.
>The primary advantage of this approach (vs. inferring Indices from “var
>Indices: CountableRange” in a constrained protocol extension) is
>that there’s a real typealias declaration that compiler and programmer
>alike can look at and reason about based just on the name “Indices”.
>
>Note that this mechanism technically obviates the need for (1), in the
>same sense that default implementations in protocols
>
> 
>  are
>merely syntactic sugar.
>3. Declarations within the nominal type declaration or extension that
>declares conformance to the protocol in question. This is generally the
>same approach as described in “associated type inference” above, where we
>match requirements of the protocol against declarations that could satisfy
>those requirements and infer associated types from there. However, I want
>to turn it around: instead of starting with the requirements of the
>protocol any looking basically anywhere in the type or any protocol to
>which it conforms (for implementations in protocol extensions), start with
>the declarations that the user explicitly wrote at the point of the
>conformance and look for requirements they might satisfy. For example,
>consider our initial example:
>
>  extension MyCollection: RandomAccessCollection {
>var startIndex: Int { return contents.startIndex }
>var endIndex: Int { return contents.endIndex }
>subscript(index: Int) -> T { return contents[index] }
>  }
>
>Since startIndex, endIndex, and subscript(_:) are declared in the same
>extension that declares conformance to RandomAccessIterator, we should look
>for requirements with the same name as these properties and subscript
>within RandomAccessCollection (or any protocol it inherits) and infer Index
>:= Int and Element := T by matching the type signatures. This is still the
>most magical inference rule, because there is no declaration named “Index”
>or “Element” to look at. However, it is much narrower in scope than the
>current implementation, because it’s only going to reason from the
>(probably small) set of declarations that the user wrote alongside the
>conformance, so it’s more likely to be intentional. Note that this is again
>nudging programmers toward the style of programming where one puts one
>protocol conformance per extension, which is admittedly my personal
>preference.
>
>
> *Thoughts?*
> I think this approach is more predictable and more implementable than the
> current model. I’m curious whether the above makes sense to someone other
> than me, and whether it covers existing use cases well enough. Thoughts?
>
> - Doug
>


How does this work with retroactive conformance, especially where all the
protocol requirements already exist on a type and an empty extension
declares conformance? For example, suppose Module A declares a protocol
with associated types, and Module B has a struct which naturally possesses
all the required members to conform (maybe B handles Double concretely,
while A can work with any FloatingPoint, or some such). As a client
importing both modules and providing an empty extension to conform B’s
struct to A’s protocol, will the associated types be inferred?

Also, have you considered the possibility of allowing protocol authors to
specify which types should be inferred from which requirements? For example
Collection might demarcate “startIndex” as the source-of-truth for
inferring “Index”, and “subscript (Index)->Element” as the source-of-truth
for inferring “Element”.

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


Re: [swift-evolution] [RFC] Associated type inference

2017-12-01 Thread Douglas Gregor via swift-evolution


> On Dec 1, 2017, at 10:07 AM, Greg Titus  wrote:
> 
> 
> 
>> On Dec 1, 2017, at 9:11 AM, Ben Langmuir via swift-evolution 
>> > wrote:
>> Hey Doug,
>> 
>> I'm very much in favour of reducing the scope of associated type inference.  
>> Can you outline why you believe that (3) is necessary?  If I am following 
>> correctly, if we had (1) and (2) the only thing you'd need to add to the 
>> "minimal collection" implementation would be a typealias for `Element`, 
>> which seems reasonable to me.
>> 
>> Ben
> 
> If nothing else, dropping (3) would be source breaking for 90%+ of current 
> associated type uses. Whereas even the very minimal inference in (3) probably 
> brings that figure down to 1% or so (outside of the stdlib, which would need 
> to adopt a bunch of (2)). Obviously these percentages are just my guesses and 
> not based on any real survey, but certainly would be the case for all Swift 
> code I’ve seen.

Many of the associated-type inference bugs I’ve seen were from people expecting 
something like (3), but the current implementation either fails to infer 
anything (the common case!) or we get inference from some seemingly-unrelated 
place. I included (3) specifically because I think taking away (3) will break 
source compatibility significantly (as Greg suggests)… and despite the fact 
that the complexity of implementation for (3) is fairly high.

- Doug


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


Re: [swift-evolution] [RFC] Associated type inference

2017-12-01 Thread Douglas Gregor via swift-evolution


> On Dec 1, 2017, at 9:11 AM, Ben Langmuir  wrote:
> 
>> 
>> On Nov 30, 2017, at 4:28 PM, Douglas Gregor via swift-evolution 
>> > wrote:
>> 
>> Hello Swift community,
>> 
>> Associated type inference, which is the process by which the Swift compiler 
>> attempts to infer typealiases to satisfy associated-type requirements based 
>> on other requirements, has caused both implementation problems and user 
>> confusion for a long time. Some of you might remember a previous (failed) 
>> attempt to remove this feature from the Swift language, in SE-0108 “Remove 
>> associated type inference”. 
>> 
>>  
>> 
>> I’m not sure we can remove this feature outright (i.e., the concerns that 
>> sank that proposal are still absolutely valid), because it is so very 
>> convenient and a lot of user code likely depends on it in some form or 
>> other. So, here I’d like to describe the uses of the feature, its current 
>> (very problematic) implementation approach, and a half-baked proposal to 
>> narrow the scope of associated type inference to something that I think is 
>> more tractable. I need help with the design of this feature, because I feel 
>> like it’s going to be a delicate balance between implementability and 
>> expressiveness.
>> 
>> A Motivating Example
>> As a motivating example, let’s consider a “minimal” random access collection:
>> 
>> struct MyCollection {
>> var contents: [T]
>> }
>> 
>> extension MyCollection: RandomAccessCollection {
>> var startIndex: Int { return contents.startIndex }
>> var endIndex: Int { return contents.endIndex }
>> subscript(index: Int) -> T { return contents[index] }
>> }
>> 
>> This is actually pretty awesome: by providing just two properties and a 
>> subscript, we get the full breadth of the random access collection API! This 
>> is relying heavily on associated type inference (for associated type 
>> requirements) and default implementations specified on protocol extensions. 
>> Without associated type inference, we would have had to write:
>> 
>> 
>> extension MyCollection: RandomAccessCollection {
>> typealias Element = T
>> typealias Index = Int
>> typealias Indices = CountableRange
>> typealias Iterator = IndexingIterator
>> typealias SubSequence = RandomAccessSlice
>> 
>> var startIndex: Int { return contents.startIndex }
>> var endIndex: Int { return contents.endIndex }
>> subscript(index: Int) -> T { return contents[index] }
>> }
>> 
>> where the bolded typealiases are currently inferred. It was worse back when 
>> we reviewed SE-0108, because IIRC there were a few underscored associated 
>> types (e.g., _Element) that have since been removed. Still, that’s a bit of 
>> additional work to define a “minimal” collection, and requires quite a bit 
>> more understanding: how do I know to choose IndexingIterator, and 
>> CountableRange, and RandomAccessSlice?
>> 
>> The issue would get worse with, e.g., SE-0174 “Change filter to return an 
>> associated type” 
>> ,
>>  which adds an associated type Filtered that almost nobody will ever 
>> customize, and isn’t really fundamental to the way collections work. Adding 
>> Filtered to the standard library would be a source-breaking change, because 
>> users would have to write a typealias giving it its default.
>> 
>> Associated Type Defaults
>> One of the ways in which we avoid having to specify typealiases is to use 
>> associated type defaults. For example, the standard library contains 
>> associated type defaults for Indices, Iterator, and SubSequence. Let’s focus 
>> on Indices:
>> 
>> protocol Collection : Sequence {
>>   associatedtype Indices = DefaultIndices
>>   // ...
>> }
>> 
>> protocol BidirectionalCollection : Collection {
>>   associatedtype Indices = DefaultBidirectionalIndices
>>   // ...
>> }
>> 
>> protocol RandomAccessCollection : BidirectionalCollection {
>>   associatedtype Indices = DefaultRandomAccessIndices
>>   // ...
>> }
>> 
>> The basic idea here is that different protocols in the hierarchy provide 
>> different defaults, and you presumably want the default from the most 
>> specific protocol. If I define a type and make it conform to 
>> BidirectionalCollection, I’d expect to get DefaultBidirectionalIndices 
>> for Indices. If a define a type and make it conform to RandomAccessIterator, 
>> I’d expect to get DefaultRandomAccessIndices.
>> 
>> (Aside: DefaultRandomAccessIndices and DefaultBidirectionalIndices got 
>> collapsed into DefaultIndices now that we have conditional conformances for 
>> the standard library , but the 
>> issues I’m describing remain).
>> 
>> Associated type defaults 

Re: [swift-evolution] Proposal: Introduce User-defined "Dynamic Member Lookup" Types

2017-12-01 Thread Douglas Gregor via swift-evolution


> On Dec 1, 2017, at 1:30 AM, Chris Lattner  wrote:
> 
>> On Dec 1, 2017, at 12:26 AM, Douglas Gregor > > wrote:
 Philosophy
> 
>>> More problematically for your argument: your preferred approach requires 
>>> the introduction of (something like) DynamicMemberLookupProtocol or 
>>> something like AnyObject-For-Python, so your proposal would be additive on 
>>> top of solving the core problem I’m trying to solve.  It isn’t an 
>>> alternative approach at all.
>> 
>> I wouldn’t say that’s my preferred approach. My preferred approach involves 
>> taking the method/property/etc. declarations that already exist in Python 
>> and mapping them into corresponding Swift declarations so we have something 
>> to find with name lookup. One could put all of these declarations on some 
>> PyVal struct or PythonObject and there would be no need for 
>> AnyObject-for-Python or DynamicMemberLookupProtocol.
> 
> You’re suggesting that the transitive closure of all Python methods and 
> properties be preprocessed into a single gigantic Swift PyVal type?  I guess 
> something like that could be done.

That’s effectively what Swift is already doing with AnyObject.

> I would be concerned because there are many N^2 or worse algorithms in the 
> Swift compiler would probably explode.

As noted above, we already do this for AnyObject with every @objc entity 
everywhere. The # of overloads for a given name is usually not so high that 
it’s a problem for the compiler.

>  It also doesn’t provide the great tooling experience that you’re seeking, 
> given that code completion would show everything in the Python universe, 
> which is not helpful.

It’s better for code completion to provide too much than to provide nothing at 
all. If code completion provides too much, typing a small number of characters 
will reduce the completion set down to something manageable quite fast.

> Further, it doesn’t provide a *better* experience than what I’m suggesting, 
> it seems strictly worse.  

>From my prior message, having the declarations of all Python methods and 
>properties available on PyVal makes Swift tooling work:

For the same working Swift code

  dog.add_trick(rollOver)

that calls into Python, the solution I’m proposing:

* Gave you the add_trick(<#trick#>) code completion with the number of 
parameters and their names
* Supports goto definition to jump to the wrapper method on PyVal
* Supports “quick help” to show the declaration of that wrapper method on 
PyVal, showing the documentation (docstring) and in which Python class it was 
declared.
* Supports indexing functionality so we can find the likely uses of “add_trick"

DynamicMemberLookup doesn’t gave any of those, because “add_trick” is just a 
string that looks like an identifier. Only the Python runtime can resolve.

> A preprocessing step prevents users from playfully importing random Python 
> modules into the Swift repl and playgrounds.

*At worst*, you invoke the tool from the command line to build the Swift module 
that corresponds to a given Python module.

py2swift 

We could absolutely introduce tooling hooks to make the compiler initiate that 
step.

>  It also seems worse for implementors (who will get a stream of new bugs 
> about compiler scalability).

To my knowledge, AnyObject lookup has not been a serious source of performance 
problems for the compiler. The global lookup table it requires was annoying to 
implement, but it’s just a symbol table.

> 
 Whenever we discuss adding more dynamic features to Swift, there’s a 
 strong focus on maintaining that strong static type system.
>>> 
>>> Which this does, by providing full type safety - unlike AnyObject lookup.
>> 
>> You get dynamic safety because it goes into the Python interpreter; fair 
>> enough. You get no help from your tools to form a correct invocation of any 
>> method provided by Python.
> 
> Sure, that’s status quo for Python APIs.

That’s not the status quo for Python IDEs. They will give you the basic shape 
of method calls.

> 
 Tooling
 The Python interoperability enabled by this proposal *does* look fairly 
 nice when you look at a small, correctly-written example. However, 
 absolutely none of the tooling assistance we rely on when writing such 
 code will work for Python interoperability. Examples:
 
 * As noted earlier, if you typo’d a name of a Python entity or passed the 
 wrong number of arguments to it, the compiler will not tell you: it’ll be 
 a runtime failure in the Python interpreter. I guess that’s what you’d get 
 if you were writing the code in Python, but Swift is supposed to be 
 *better* than Python if we’re to convince a community to use Swift instead.
 * Code completion won’t work, because Swift has no visibility into 
 declarations written in Python
 * Indexing/jump-to-definition/lookup documentation/generated interface 
 

Re: [swift-evolution] Proposal: Introduce User-defined "Dynamic Member Lookup" Types

2017-12-01 Thread Jacob Williams via swift-evolution
I’ve been going back and forth on whether I’m for or against the current 
revision of the proposal and I’d have to say that I am in favor of it as is for 
the following reasons (many of which have already been stated):

It was stated early on in this proposal that Python is not going to be given 
the same first class support that C/Objective-C have in the compiler. It would 
be unreasonable and would set a precedent that all languages would get the same 
treatment when the community wants to add interoperability. Many arguments have 
been made that we NEED to have static typing for dynamic languages. I don’t see 
static typing coming without first class compiler support. 

Also, the very nature of these dynamic languages means static typing would 
violate basic principles of the dynamic language. I think it would be much 
worse and scare away python developers who are suddenly forced to statically 
type things that they may know to be dynamic types in their python APIs. Of 
course, the other side of the coin is that swift developers would be scared 
away by the lack of static typing when using Python interop. I see the latter 
as a non-issue though because anyone using python knows to expect things 
without static types. 

Forcing static types where there are no static types sounds like a really bad 
idea to me. So I’m ok with the proposed PyVal type for all python types. 
Extensions can be written to make casting a PyVal object to the various swift 
types easy (if/when desired).

There has also been much discussion on the potential for abuse. There was an 
example given of adding conformance to NSObject I believe. Chris and Xiaodi 
both proposed solutions to this that would minimize (and possibly eliminate) 
the potential for abuse. 

However, there will always be potential for a feature to be misused. The 
potential does not mean it is an absolute given that it will be misused (I’m an 
optimist if you can’t tell ;).

I don’t view this protocol as a beginner user feature. This is not a protocol 
that will be commonly used or even commonly desired. It has a very specific set 
of uses and I strongly believe that the community will continue to do a good 
job at suggesting the right tool for the right job. The advanced users that are 
aware of this protocol will most likely properly recommend this protocol when 
applicable. Your average Joe Shmoe isn’t going to even be aware of this. Those 
who are curious, will probably ask about it. There will be StackOverflow 
responses describing it and what it does and when/why to use it. (This is just 
my two cents based on what I’ve witnessed in the swift community and on 
StackOverflow in the past). I’m sure that if the documentation on this protocol 
says “Used to provide interoperability with dynamic languages” then most users 
are going to steer clear of it unless they are writing an interop layer with a 
dynamic language.

I don’t think the goal here is to write Python (or ruby or javascript or 
[dynamic language]) in swift. The aim of this proposal it to make it easy and 
possible to use python from swift. I don’t expect to write a full blown python 
project in swift. I expect to call the few python APIs from module xyz and be 
done with python. I’m trying to write a swift project not a python one. If I 
wanted to use python extensively then I would just stick with python (I work as 
a python developer and Python is definitely not my language of choice, but it 
does have its upsides). I don’t want to write my own swift implementation for 
something where a python module already exists so I import the python module 
and do the few things with it that I actually need. I don’t need or expect IDE 
integration with the language I’m using at that moment. I can read docs for my 
2-3 python API calls while I’m developing it.

Even with this proposal, people could write their own swift libraries that are 
just statically typed wrappers around a python library. This proposal does not 
limit people in any way. It does however, open the door for interoperability 
with a large set of dynamic languages.

> On Dec 1, 2017, at 10:37 AM, Chris Lattner via swift-evolution 
>  wrote:
> 
> On Dec 1, 2017, at 12:26 AM, Douglas Gregor  > wrote:
>>> On Nov 30, 2017, at 10:05 PM, Chris Lattner >> > wrote:
>>> Hi Doug,
>>> 
>>> Thank you for the detailed email.  I have been traveling today, so I 
>>> haven’t had a chance to respond until now.  I haven’t read the down-thread 
>>> emails, so I apologize if any of this was already discussed:
>>> 
 I think better interoperability with Python (and other OO languages in 
 widespread use) is a good goal, and I agree that the implementation of the 
 feature described is straight-forward and not terribly invasive in the 
 compiler.
>>> 
>>> Fantastic, I’m really pleased to hear that!  I only care about 

Re: [swift-evolution] [RFC] Associated type inference

2017-12-01 Thread Greg Titus via swift-evolution


> On Dec 1, 2017, at 9:11 AM, Ben Langmuir via swift-evolution 
>  wrote:
> Hey Doug,
> 
> I'm very much in favour of reducing the scope of associated type inference.  
> Can you outline why you believe that (3) is necessary?  If I am following 
> correctly, if we had (1) and (2) the only thing you'd need to add to the 
> "minimal collection" implementation would be a typealias for `Element`, which 
> seems reasonable to me.
> 
> Ben

If nothing else, dropping (3) would be source breaking for 90%+ of current 
associated type uses. Whereas even the very minimal inference in (3) probably 
brings that figure down to 1% or so (outside of the stdlib, which would need to 
adopt a bunch of (2)). Obviously these percentages are just my guesses and not 
based on any real survey, but certainly would be the case for all Swift code 
I’ve seen.

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


Re: [swift-evolution] [Proposal] Random Unification

2017-12-01 Thread Erica Sadun via swift-evolution


> On Nov 30, 2017, at 5:21 PM, Xiaodi Wu via swift-evolution 
>  wrote:
> 
> On Thu, Nov 30, 2017 at 5:24 PM, Nate Cook  > wrote:
>> On Nov 30, 2017, at 4:30 PM, Xiaodi Wu via swift-evolution 
>> > wrote:
>> 
>> On Thu, Nov 30, 2017 at 3:58 PM, Dave DeLong via swift-evolution 
>> > wrote:
>> 
>> 
>>> On Nov 30, 2017, at 2:48 PM, Jonathan Hull via swift-evolution 
>>> > wrote:
>>> 
>>> I would personally go with:
>>> 
>>> Int.random //Returns a random Int
>> 
>> “Type.random” is so rarely used as to not be worth the addition, IMO. If you 
>> really need a random element from the *entire* domain, then I think you 
>> should have to manually create the ClosedRange yourself.
>> 
>>> Int.random(in: ClosedRange) //Works for Comparable types. Gives a 
>>> result from the closed range. Closed Range is never empty.
>> 
>> This is redundant. In order to pick a random element, you’re saying I should 
>> have to do “Int.random(0 ..< 10)”? The redundancy here is that I have to 
>> specify Int twice: once for the “.random” call, and again for the type of 
>> the range. We can do better than that.
> 
> I don’t see how this is redundant—do you mean that you’d need to write out 
> the type name instead of writing `(0..<10).random()!`? I continue to be of 
> the opinion that picking a random integer/floating-point value/Boolean and 
> picking a random element from a collection are two different operations. Yes, 
> there’s overlap between the two, but they’re different enough that having two 
> ways to choose an integer between 0 and 10 would be fine.
> 
> As I wrote elsewhere, if they're sufficiently different enough, then they 
> ought to have distinct names. If they are not, then there ought to be only 
> one of them. I'm no longer sure myself of which one I'd prefer, but in no 
> case should there be two things named "random."
> 
> If the proposal to make `IndexDistance == Int` is accepted, then ranges 
> cannot conform to Collection and we encounter some interesting difficulties 
> attempting to index into such a collection to pick a random value.

I'd like to put forth that Gameplay Kit offers a perfectly cromulent model of 
random number generation and API. Why not take that as a starting point, 
Swiftify it so it becomes a cross platform solution, and then apply the 
specific questions of sequences, collections, and indices as a second step?  

I don't support intermingling random functionality with existing core types.

-- E


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


Re: [swift-evolution] [Proposal] Random Unification

2017-12-01 Thread Martin Waitz via swift-evolution
Hi,

> With a protocol defining random() and random(in:), you could write generic 
> algorithms on things which know how to create themselves from a RNG.  With 
> your approach the RNG has to provide a way to get a random value for each 
> type you want to support.

This is right, if we want a generic prototype for construction of random 
objects, well then we need such a protocol and a new method or initializer.
However, I‘m not yet convinced that such a protocol is necessary.
Most objects will be constructed using randomized values, according to the use 
case at hand. A generic randomizable protocol would not help here.

> For example, without random(in:) or random(), how would you get a CGFloat 
> between 0 and 1?  Ranges are only collections if they are countable…

I was assuming that there would be a random.draw(from:) for ranges.

>> extension RandomFoo {
>>   func draw(from urn: T) -> T.Element? {
>>   guard !urn.isEmpty else { return nil }
>>   let idx = draw(from: urn.indices)
>>   return urn[idx]
>>   }
>> }
>> 
> This will call itself repeatedly and hang...

You are right, Collection.indices is also a Collection. We have to explicitly 
use the range here.

>> We just have to define one base protocol for such extensions. Every random 
>> number generator then automatically knows how to draw elements from ranges 
>> and collections.
> 
> It isn’t automatic, thought.  How would I get a random color?

This has already been discussed: you either want some random color from a fixed 
set, or you want to produce a new color using some random values. A completely 
random color it totally useless.

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


Re: [swift-evolution] Proposal: Introduce User-defined "Dynamic Member Lookup" Types

2017-12-01 Thread Chris Lattner via swift-evolution
On Dec 1, 2017, at 12:26 AM, Douglas Gregor  wrote:
>> On Nov 30, 2017, at 10:05 PM, Chris Lattner > > wrote:
>> Hi Doug,
>> 
>> Thank you for the detailed email.  I have been traveling today, so I haven’t 
>> had a chance to respond until now.  I haven’t read the down-thread emails, 
>> so I apologize if any of this was already discussed:
>> 
>>> I think better interoperability with Python (and other OO languages in 
>>> widespread use) is a good goal, and I agree that the implementation of the 
>>> feature described is straight-forward and not terribly invasive in the 
>>> compiler.
>> 
>> Fantastic, I’m really pleased to hear that!  I only care about solving the 
>> problem, so if we can find a good technical solution to the problems than 
>> I’ll be happy.

After thinking about your email a bit more, I think I might understand the 
disconnect we’re having.  I think we have different versions in mind of what 
“success” looks like:

I believe your view is that people start using Python APIs from their Swift 
code, but gradually add type annotations (either inline or in a sidecar 
database) to make those APIs progressively more Swifty.  New features will be 
added to Python (its type system, compilers, databases for common APIs, etc) to 
improve this interoperability, along the lines of what we’ve done for 
Objective-C over the years.  Fast forward several years, and large Python 
libraries would be nice to use from Swift - perhaps nicer than they are to use 
from Python itself.  This view aligns with what happened with Objective-C <-> 
Swift interoperability.

In contrast, I’m specifically interested in developers in certain large domains 
(e.g. data science and ML) which are “forced” to use Python because that is 
where all the libraries are.  I have spoken to many of these sorts of people, 
and a large number of them really *dislike* using Python for all the obvious 
reasons (including the tooling issues you point out).  My view of success is 
that we allow them to write all of *their code* in Swift, which will lead to a 
massive quality of life benefit for these frustrated people.  You’re right that 
they will still chaff when using imported Python APIs (which don’t feel 
“swifty” for LOTS of reasons - e.g. method naming and design patterns), but my 
view is that this will provide incentive for these people to provide a proper 
Swift implementation for these libraries over time.

In short, your end game is a pervasively intertwined Swift/Python world (like 
ObjC and Swift are).  My view is that Swift holds Python at arm's length, and 
wins over the hearts and minds of developers, leading to new Swift APIs 
designed for Swift.


I’m not sure if you agree with that portrayal of your position, and if not, I’m 
sorry and will try to understand another way.  However, if I’m close, then I 
have several concerns about that vision and don’t believe the end-game is 
achievable or better than what I’m proposing.  Consider:

- I don’t think there will be a lot of success getting people who *actually 
love* Python to use Swift, unless there is already an extrinsic reason for them 
to use it.
- Type hints are not widely used in Python, and there are believable reasons 
that they won’t ever be.  Because they are specifically poorly suited for 
libraries, their use seems to be in “user’s own code” - but my proposal solves 
this already!  See below for examples.
- Even if type hints were widely adopted, it would require massive extensions 
to them and to Python to make them be "good enough” to provide value for the 
things you’re envisioning.  Analogs to instancetype, objc generics, lots of the 
C macros, and many of the other things we’ve added to ObjC would have to be 
added.
- The Python community has no reason to do this work for the Swift community, 
or accept changes to Python that are required to make this actually great.
- Beyond the core type system, the Python and Objective-C languages work 
extremely differently in other ways (e.g. lack of umbrella headers making 
AnyObject-style dispatch questionable).
- Even with those annotations and all the work, the APIs we’d end up with are 
not going to be good Swift APIs.  I don’t think that “renamification” and "IUO 
audits" would ever actually happen in practice, for example.
- I believe the engineering effort required to implement this vision is so 
massive (including the changes to Swift, Python, and Python libraries) that it 
simply will never actually happen.


More concerning to me is that your design of using the existing AnyObject type 
presents a really concerning technical problem, scalability: It is not simply a 
Swift/ObjC/Python world, Javascript is also super important.  There are also a 
number of other less-widely used dynamic languages that are interesting.  Your 
design leads to them all being mashed together into a common runtime system.  I 
cannot imagine how this would end 

Re: [swift-evolution] array splatting for variadic parameters

2017-12-01 Thread Cao, Jiannan via swift-evolution
What about calling a framework variadic function that I could not re-declare?
like print

> 在 2017年12月2日,上午1:26,Tino Heth <2...@gmx.de > 写道:
> 
> There has been a solution to the same problem that’s imho much nicer, because 
> instead of adding fundamental new syntax, it removes a piece of C-legacy:
> 
> Basically,instead of
> func f(args: Int…)
> you would just declare
> func f(args: @variadic [Int])
> or even
> func f(args: [Int])
> and interpret any argument that’s a comma-separated list as an array — or, 
> and that’s imho another useful aspect, something else that can be expressed 
> with an array literal
> func f(args: Set)
> 
> So you would not only make the language surface smaller, but also add new 
> abilities that basically come for free (they would still have to be 
> implemented, though ;-)
> 
>> Am 30.11.2017 um 22:13 schrieb Cao, Jiannan via swift-evolution 
>> >:
>> 
>> What happened with this proposal? This looks easy to implement.
>> 
>> func sumOf(numbers: Int...) -> Int {
>>   ...
>>   }
>> typealias Function = [Int] -> Int
>> let sumOfArray = unsafeBitCast(sumOf, Function.self)
>> sumOfArray([1, 2, 3])
>> 
>>> Hello everyone.
>>> 
>>> I understand that topic has already been discussed in the past, but I 
>>> failed to get any information on its current state of affairs.
>>> 
>>> I guess the subject of this mail is explicit, but to make sure I’m clear, 
>>> here's a small snippet that illustrates the problem:
>>> 
>>> func f(args: Int…) {
>>>   // Some implementation ...
>>> }
>>> // Now it's impossible to call f without explicitly naming its parameters.
>>> 
>>> For many use-cases, this problem can be solved by overloading f so that it 
>>> explicitly accepts an array.
>>> 
>>> func f(_ args: [Int]) {
>>>   // Some implementation ...
>>> }
>>> 
>>> func f(_ args: Int…) {
>>>   f(args)
>>> }
>>> 
>>> Some people also advocate (myself generally included) that one should 
>>> prefer the signature explicitly marking args as an array, as the syntactic 
>>> overhead of wrapping the arguments with “[]” when calling f is arguably 
>>> bearable. However, in some other situations, this approach might not be 
>>> applicable. For instance, one may simply not be able to modify the original 
>>> function. Another use-case may be a function that should forward its own 
>>> variadic parameters.
>>> 
>>> In a variety of other languages, there exists a way to do this. For 
>>> instance, Python can “unpack” (or splat) a list into function arguments by 
>>> prefixing it with *:
>>> 
>>> def f(*args):
>>>   # Some implementation …
>>> 
>>> f(*[1, 2, 3]) # == f(1, 2, 3)
>>> 
>>> I was wondering if such feature could be supported by Swift, and if not, 
>>> why.
>>> 
>>> Syntactically, I like the use of “…”, which would mirror function 
>>> signatures:
>>> 
>>> f(…[1, 2, 3]) // == f(1, 2, 3)
>>> 
>>> Thanks.
>>> 
>>> --
>>> Dimitri Racordon
>> 
>> ___
>> 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] array splatting for variadic parameters

2017-12-01 Thread Tino Heth via swift-evolution
There has been a solution to the same problem that’s imho much nicer, because 
instead of adding fundamental new syntax, it removes a piece of C-legacy:

Basically,instead of
func f(args: Int…)
you would just declare
func f(args: @variadic [Int])
or even
func f(args: [Int])
and interpret any argument that’s a comma-separated list as an array — or, and 
that’s imho another useful aspect, something else that can be expressed with an 
array literal
func f(args: Set)

So you would not only make the language surface smaller, but also add new 
abilities that basically come for free (they would still have to be 
implemented, though ;-)

> Am 30.11.2017 um 22:13 schrieb Cao, Jiannan via swift-evolution 
> :
> 
> What happened with this proposal? This looks easy to implement.
> 
> func sumOf(numbers: Int...) -> Int {
>   ...
>   }
> typealias Function = [Int] -> Int
> let sumOfArray = unsafeBitCast(sumOf, Function.self)
> sumOfArray([1, 2, 3])
> 
>> Hello everyone.
>> 
>> I understand that topic has already been discussed in the past, but I failed 
>> to get any information on its current state of affairs.
>> 
>> I guess the subject of this mail is explicit, but to make sure I’m clear, 
>> here's a small snippet that illustrates the problem:
>> 
>> func f(args: Int…) {
>>   // Some implementation ...
>> }
>> // Now it's impossible to call f without explicitly naming its parameters.
>> 
>> For many use-cases, this problem can be solved by overloading f so that it 
>> explicitly accepts an array.
>> 
>> func f(_ args: [Int]) {
>>   // Some implementation ...
>> }
>> 
>> func f(_ args: Int…) {
>>   f(args)
>> }
>> 
>> Some people also advocate (myself generally included) that one should prefer 
>> the signature explicitly marking args as an array, as the syntactic overhead 
>> of wrapping the arguments with “[]” when calling f is arguably bearable. 
>> However, in some other situations, this approach might not be applicable. 
>> For instance, one may simply not be able to modify the original function. 
>> Another use-case may be a function that should forward its own variadic 
>> parameters.
>> 
>> In a variety of other languages, there exists a way to do this. For 
>> instance, Python can “unpack” (or splat) a list into function arguments by 
>> prefixing it with *:
>> 
>> def f(*args):
>>   # Some implementation …
>> 
>> f(*[1, 2, 3]) # == f(1, 2, 3)
>> 
>> I was wondering if such feature could be supported by Swift, and if not, why.
>> 
>> Syntactically, I like the use of “…”, which would mirror function signatures:
>> 
>> f(…[1, 2, 3]) // == f(1, 2, 3)
>> 
>> Thanks.
>> 
>> --
>> Dimitri Racordon
> 
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

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


Re: [swift-evolution] [RFC] Associated type inference

2017-12-01 Thread Ben Langmuir via swift-evolution

> On Nov 30, 2017, at 4:28 PM, Douglas Gregor via swift-evolution 
>  wrote:
> 
> Hello Swift community,
> 
> Associated type inference, which is the process by which the Swift compiler 
> attempts to infer typealiases to satisfy associated-type requirements based 
> on other requirements, has caused both implementation problems and user 
> confusion for a long time. Some of you might remember a previous (failed) 
> attempt to remove this feature from the Swift language, in SE-0108 “Remove 
> associated type inference”. 
> 
>  
> 
> I’m not sure we can remove this feature outright (i.e., the concerns that 
> sank that proposal are still absolutely valid), because it is so very 
> convenient and a lot of user code likely depends on it in some form or other. 
> So, here I’d like to describe the uses of the feature, its current (very 
> problematic) implementation approach, and a half-baked proposal to narrow the 
> scope of associated type inference to something that I think is more 
> tractable. I need help with the design of this feature, because I feel like 
> it’s going to be a delicate balance between implementability and 
> expressiveness.
> 
> A Motivating Example
> As a motivating example, let’s consider a “minimal” random access collection:
> 
> struct MyCollection {
> var contents: [T]
> }
> 
> extension MyCollection: RandomAccessCollection {
> var startIndex: Int { return contents.startIndex }
> var endIndex: Int { return contents.endIndex }
> subscript(index: Int) -> T { return contents[index] }
> }
> 
> This is actually pretty awesome: by providing just two properties and a 
> subscript, we get the full breadth of the random access collection API! This 
> is relying heavily on associated type inference (for associated type 
> requirements) and default implementations specified on protocol extensions. 
> Without associated type inference, we would have had to write:
> 
> 
> extension MyCollection: RandomAccessCollection {
> typealias Element = T
> typealias Index = Int
> typealias Indices = CountableRange
> typealias Iterator = IndexingIterator
> typealias SubSequence = RandomAccessSlice
> 
> var startIndex: Int { return contents.startIndex }
> var endIndex: Int { return contents.endIndex }
> subscript(index: Int) -> T { return contents[index] }
> }
> 
> where the bolded typealiases are currently inferred. It was worse back when 
> we reviewed SE-0108, because IIRC there were a few underscored associated 
> types (e.g., _Element) that have since been removed. Still, that’s a bit of 
> additional work to define a “minimal” collection, and requires quite a bit 
> more understanding: how do I know to choose IndexingIterator, and 
> CountableRange, and RandomAccessSlice?
> 
> The issue would get worse with, e.g., SE-0174 “Change filter to return an 
> associated type” 
> ,
>  which adds an associated type Filtered that almost nobody will ever 
> customize, and isn’t really fundamental to the way collections work. Adding 
> Filtered to the standard library would be a source-breaking change, because 
> users would have to write a typealias giving it its default.
> 
> Associated Type Defaults
> One of the ways in which we avoid having to specify typealiases is to use 
> associated type defaults. For example, the standard library contains 
> associated type defaults for Indices, Iterator, and SubSequence. Let’s focus 
> on Indices:
> 
> protocol Collection : Sequence {
>   associatedtype Indices = DefaultIndices
>   // ...
> }
> 
> protocol BidirectionalCollection : Collection {
>   associatedtype Indices = DefaultBidirectionalIndices
>   // ...
> }
> 
> protocol RandomAccessCollection : BidirectionalCollection {
>   associatedtype Indices = DefaultRandomAccessIndices
>   // ...
> }
> 
> The basic idea here is that different protocols in the hierarchy provide 
> different defaults, and you presumably want the default from the most 
> specific protocol. If I define a type and make it conform to 
> BidirectionalCollection, I’d expect to get DefaultBidirectionalIndices 
> for Indices. If a define a type and make it conform to RandomAccessIterator, 
> I’d expect to get DefaultRandomAccessIndices.
> 
> (Aside: DefaultRandomAccessIndices and DefaultBidirectionalIndices got 
> collapsed into DefaultIndices now that we have conditional conformances for 
> the standard library , but the 
> issues I’m describing remain).
> 
> Associated type defaults seem like a reasonable feature that fits well enough 
> into the design. However, it’s not the only thing in place with our 
> MyCollection example, for which Indices was inferred to CountableRange. How’s 
> that happen?
> 

Re: [swift-evolution] Proposal: Introduce User-defined "Dynamic Member Lookup" Types

2017-12-01 Thread David Hart via swift-evolution
The semantics of the DLR seems fairly similar to Chris’ proposal, does it not? 
Btw, this makes me think that I would prefer to have one proposal contain both 
dynamic member lookup and dynamic method calls: it would be kind of silly to 
have one accepted and not the other.

David.

> On 1 Dec 2017, at 17:38, C. Keith Ray via swift-evolution 
>  wrote:
> 
> Should we compare dynamic member lookup to Microsoft's DLR ?
> 
> https://docs.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/dynamic-language-runtime-overview
>  
> 
> 
> Quote: 
> The dynamic language runtime (DLR) is a runtime environment that adds a set 
> of services for dynamic languages to the common language runtime (CLR). The 
> DLR makes it easier to develop dynamic languages to run on the .NET Framework 
> and to add dynamic features to statically typed languages. 
> Dynamic languages can identify the type of an object at run time, whereas in 
> statically typed languages such as C# and Visual Basic (when you use Option 
> Explicit On) you must specify object types at design time. Examples of 
> dynamic languages are Lisp, Smalltalk, JavaScript, PHP, Ruby, Python, 
> ColdFusion, Lua, Cobra, and Groovy. 
> Most dynamic languages provide the following advantages for developers: 
> The ability to use a rapid feedback loop (REPL, or read-evaluate-print loop). 
> This lets you enter several statements and immediately execute them to see 
> the results. 
> Support for both top-down development and more traditional bottom-up 
> development. For example, when you use a top-down approach, you can call 
> functions that are not yet implemented and then add underlying 
> implementations when you need them. 
> Easier refactoring and code modifications, because you do not have to change 
> static type declarations throughout the code. 
> Dynamic languages make excellent scripting languages. Customers can easily 
> extend applications created by using dynamic languages with new commands and 
> functionality. Dynamic languages are also frequently used for creating Web 
> sites and test harnesses, maintaining server farms, developing various 
> utilities, and performing data transformations. + <>
> The purpose of the DLR is to enable a system of dynamic languages to run on 
> the .NET Framework and give them .NET interoperability. The DLR introduces 
> dynamic objects to C# and Visual Basic in Visual Studio 2010 to support 
> dynamic behavior in these languages and enable their interoperation with 
> dynamic languages.
> 
> --
> C. Keith Ray
> 
> * https://leanpub.com/wepntk  <- buy my book?
> * http://www.thirdfoundationsw.com/keith_ray_resume_2014_long.pdf 
> 
> * http://agilesolutionspace.blogspot.com/ 
> 
> 
> On Dec 1, 2017, at 8:07 AM, Benjamin G via swift-evolution 
> > wrote:
> 
>> 
>> 
>> On Fri, Dec 1, 2017 at 4:35 PM, Jon Gilbert via swift-evolution 
>> > wrote:
>> > On Nov 30, 2017, at 08:10, Karl Wagner via swift-evolution 
>> > > wrote:
>> >
>> > Personally, I feel this system is designed to let you write Python, using 
>> > Swift as a wrapper language - except unlike with Objective-C,
>> 
>> Let me paraphrase the proposal—it basically says this system is designed to 
>> make it easier to “fake import” existing Python/Ruby/JS libs to make it 
>> easier for people who depend on them to adopt Swift. Especially in the world 
>> of server-side Swift, I can see how this could help speed Swift’s adoption.
>> 
>> As a sidenote, the weakest points of python on the server side is 
>> compile-time type safety (none) and concurrency (almost none either). If we 
>> want to convince anyone at the moment to switch to swift on the backend, i'd 
>> say the urgent part isn't to make one or two function calls to a python 
>> library more "swifty" (but without any guarantee that we didn't mistype a 
>> function name). I'd say we should better focus on having a great agent 
>> concurrency model, as well as even better generics and faster compile time.
>> From what i've observed around me, people seem to migrate python code to 
>> golang. Not ruby or lisp.
>> 
>> 
>>  
>> 
>> However, I believe that you bring up an extremely valid concern. To 
>> extrapolate from your points, this proposal seems to have a high potential 
>> to erode what makes Swift special, and it provides a way to get around 
>> Swift’s safe-guards, avoid writing Swift versions of libraries, and 
>> ultimately, avoid hiring real Swift developers.
>> 
>> > it doesn’t have any static information about what you can do or not. It 
>> > can’t 

Re: [swift-evolution] Proposal: Introduce User-defined "Dynamic Member Lookup" Types

2017-12-01 Thread BJ Homer via swift-evolution
Responses inline.

> On Dec 1, 2017, at 8:35 AM, Jon Gilbert via swift-evolution 
>  wrote:
> 
>> On Nov 30, 2017, at 08:10, Karl Wagner via swift-evolution 
>>  wrote:
>> 
>> Personally, I feel this system is designed to let you write Python, using 
>> Swift as a wrapper language - except unlike with Objective-C,
> 
> Let me paraphrase the proposal—it basically says this system is designed to 
> make it easier to “fake import” existing Python/Ruby/JS libs to make it 
> easier for people who depend on them to adopt Swift. Especially in the world 
> of server-side Swift, I can see how this could help speed Swift’s adoption.
> 
> However, I believe that you bring up an extremely valid concern. To 
> extrapolate from your points, this proposal seems to have a high potential to 
> erode what makes Swift special, and it provides a way to get around Swift’s 
> safe-guards, avoid writing Swift versions of libraries, and ultimately, avoid 
> hiring real Swift developers. 
> 

The point is not to let you write Python in Swift. If you want to write Python, 
just write Python. The point is to let you call Python libraries (or any 
dynamic language) from Swift, in the same way that we can already call C 
libraries from Swift. The ability to call C libraries does not make people 
“avoid hiring real Swift developers”; it just means that Swift developers can 
take advantage of C libraries. The goal of this proposal is to make Swift able 
to use more existing libraries. It sounds like your argument is “we want people 
to rewrite those libraries in Swift instead”. That’s a great goal, but it will 
only be achieved if Swift gains the kind of widespread cross-platform adoption 
that would be facilitated by this very proposal.


>> it doesn’t have any static information about what you can do or not. It 
>> can’t provide the “safe by default” guarantees are other core principles and 
>> set Swift apart from other languages.
> 
> Exactly. 
> 
> Look how JSON parsing is done in Swift 3.2 and 4.0—we make static types. The 
> 1’s and 0’s from a web response go through layers of proper error handling 
> before they become proper types Swift.
> 
> So why does this proposal keeps mentioning JSON parsing as an excuse for 
> making a dynamic ghetto within the language? Because some people are parsing 
> untyped JSON? Well, the solution for that is, type your frickin’ JSON. 

It doesn’t. There was one brief mention of a JSON example, to show how this 
proposal is useful for more than just Python interop. But most of the proposal 
talks about Python, not JSON.

> 
> Why compromise Swift’s static-ness and roll out the red carpet for the 
> dynamic, unwashed masses?
> 
> Wouldn’t it be better to create an AI that quickly translates Pyton, Ruby, or 
> JS into Swift? Augustus built huge public bathhouses for the unwashed Romans. 

If you can create an AI that quickly and accurately translates Python, Ruby, 
and JS into Swift, go right ahead. To the extent that those projects are not 
taking advantage of the dynamic features of their language, that’s likely 
feasible. It’s going to be a lot more difficult for the kind of code that does 
take advantage of the dynamic nature of the language. For example, dynamic 
languages can inspect the function name to vary its behavior. You can write one 
“fetchAllFromDatabase()” function, and then call it as 
fetchAllEntiresFromDatabase(), fetchAllUsersFromDatabase(), or 
fetchAllCommentsFromDatabase(), and automatically get the right behavior. I 
don’t think you’re going to be able to automatically create an AI that mimics 
that behavior on Swift; it fundamentally relies on the dynamic binding present 
in those languages.

It’s clear that you think dynamic languages are inferior to static languages. 
That’s fine, but the fact is that there are existing useful libraries in those 
languages which do not currently exist in Swift. Is it your argument that Swift 
should not be able to make use of such libraries because of their 
“unclean-ness”? I disagree.

> 
>> When we consider interoperability with other languages, it should be from 
>> the perspective of mapping their features to Swift’s philosophies.
> 
> Amen.
> 
>> This proposal takes the reverse approach, and makes Swift like Python, so 
>> I’m against it.
> 
> This is my concern as well. 
> 
> Perhaps there is a way to make the proposal require that you declare Swift 
> types and protocols that map to these other languages, with verbose error 
> handling for when this glue breaks down (just like we have for typed JSON). 
> 
> Then, we could also make scripts that auto-generate the necessary Swift 
> typing boilerplate interface code from the Python/Ruby/JS source, kinda like 
> we get for Obj.-C bridging headers. This could be a good step towards the 
> full AI translation that I mentioned.
> 
> Of course, maybe I am missing something here, and my opinion is wrong; Chris 
> will let us know if 

Re: [swift-evolution] Proposal: Introduce User-defined "Dynamic Member Lookup" Types

2017-12-01 Thread C. Keith Ray via swift-evolution
Should we compare dynamic member lookup to Microsoft's DLR ?

https://docs.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/dynamic-language-runtime-overview

Quote: 
The dynamic language runtime (DLR) is a runtime environment that adds a set of 
services for dynamic languages to the common language runtime (CLR). The DLR 
makes it easier to develop dynamic languages to run on the .NET Framework and 
to add dynamic features to statically typed languages. 
Dynamic languages can identify the type of an object at run time, whereas in 
statically typed languages such as C# and Visual Basic (when you use Option 
Explicit On) you must specify object types at design time. Examples of dynamic 
languages are Lisp, Smalltalk, JavaScript, PHP, Ruby, Python, ColdFusion, Lua, 
Cobra, and Groovy. 
Most dynamic languages provide the following advantages for developers: 
The ability to use a rapid feedback loop (REPL, or read-evaluate-print loop). 
This lets you enter several statements and immediately execute them to see the 
results. 
Support for both top-down development and more traditional bottom-up 
development. For example, when you use a top-down approach, you can call 
functions that are not yet implemented and then add underlying implementations 
when you need them. 
Easier refactoring and code modifications, because you do not have to change 
static type declarations throughout the code. 
Dynamic languages make excellent scripting languages. Customers can easily 
extend applications created by using dynamic languages with new commands and 
functionality. Dynamic languages are also frequently used for creating Web 
sites and test harnesses, maintaining server farms, developing various 
utilities, and performing data transformations. +
The purpose of the DLR is to enable a system of dynamic languages to run on the 
.NET Framework and give them .NET interoperability. The DLR introduces dynamic 
objects to C# and Visual Basic in Visual Studio 2010 to support dynamic 
behavior in these languages and enable their interoperation with dynamic 
languages.

--
C. Keith Ray

* https://leanpub.com/wepntk <- buy my book?
* http://www.thirdfoundationsw.com/keith_ray_resume_2014_long.pdf
* http://agilesolutionspace.blogspot.com/

> On Dec 1, 2017, at 8:07 AM, Benjamin G via swift-evolution 
>  wrote:
> 
> 
> 
>> On Fri, Dec 1, 2017 at 4:35 PM, Jon Gilbert via swift-evolution 
>>  wrote:
>> > On Nov 30, 2017, at 08:10, Karl Wagner via swift-evolution 
>> >  wrote:
>> >
>> > Personally, I feel this system is designed to let you write Python, using 
>> > Swift as a wrapper language - except unlike with Objective-C,
>> 
>> Let me paraphrase the proposal—it basically says this system is designed to 
>> make it easier to “fake import” existing Python/Ruby/JS libs to make it 
>> easier for people who depend on them to adopt Swift. Especially in the world 
>> of server-side Swift, I can see how this could help speed Swift’s adoption.
> 
> As a sidenote, the weakest points of python on the server side is 
> compile-time type safety (none) and concurrency (almost none either). If we 
> want to convince anyone at the moment to switch to swift on the backend, i'd 
> say the urgent part isn't to make one or two function calls to a python 
> library more "swifty" (but without any guarantee that we didn't mistype a 
> function name). I'd say we should better focus on having a great agent 
> concurrency model, as well as even better generics and faster compile time.
> From what i've observed around me, people seem to migrate python code to 
> golang. Not ruby or lisp.
> 
> 
>  
>> 
>> However, I believe that you bring up an extremely valid concern. To 
>> extrapolate from your points, this proposal seems to have a high potential 
>> to erode what makes Swift special, and it provides a way to get around 
>> Swift’s safe-guards, avoid writing Swift versions of libraries, and 
>> ultimately, avoid hiring real Swift developers.
>> 
>> > it doesn’t have any static information about what you can do or not. It 
>> > can’t provide the “safe by default” guarantees are other core principles 
>> > and set Swift apart from other languages.
>> 
>> Exactly.
>> 
>> Look how JSON parsing is done in Swift 3.2 and 4.0—we make static types. The 
>> 1’s and 0’s from a web response go through layers of proper error handling 
>> before they become proper types Swift.
>> 
>> So why does this proposal keeps mentioning JSON parsing as an excuse for 
>> making a dynamic ghetto within the language? Because some people are parsing 
>> untyped JSON? Well, the solution for that is, type your frickin’ JSON.
>> 
>> Why compromise Swift’s static-ness and roll out the red carpet for the 
>> dynamic, unwashed masses?
>> 
>> Wouldn’t it be better to create an AI that quickly translates Pyton, Ruby, 
>> or JS into Swift? Augustus built huge public bathhouses for the unwashed 
>> Romans.

Re: [swift-evolution] Proposal: Introduce User-defined "Dynamic Member Lookup" Types

2017-12-01 Thread Benjamin G via swift-evolution
On Fri, Dec 1, 2017 at 4:35 PM, Jon Gilbert via swift-evolution <
swift-evolution@swift.org> wrote:

> > On Nov 30, 2017, at 08:10, Karl Wagner via swift-evolution <
> swift-evolution@swift.org> wrote:
> >
> > Personally, I feel this system is designed to let you write Python,
> using Swift as a wrapper language - except unlike with Objective-C,
>
> Let me paraphrase the proposal—it basically says this system is designed
> to make it easier to “fake import” existing Python/Ruby/JS libs to make it
> easier for people who depend on them to adopt Swift. Especially in the
> world of server-side Swift, I can see how this could help speed Swift’s
> adoption.
>

As a sidenote, the weakest points of python on the server side is
compile-time type safety (none) and concurrency (almost none either). If we
want to convince anyone at the moment to switch to swift on the backend,
i'd say the urgent part isn't to make one or two function calls to a python
library more "swifty" (but without any guarantee that we didn't mistype a
function name). I'd say we should better focus on having a great agent
concurrency model, as well as even better generics and faster compile time.
>From what i've observed around me, people seem to migrate python code to
golang. Not ruby or lisp.




>
> However, I believe that you bring up an extremely valid concern. To
> extrapolate from your points, this proposal seems to have a high potential
> to erode what makes Swift special, and it provides a way to get around
> Swift’s safe-guards, avoid writing Swift versions of libraries, and
> ultimately, avoid hiring real Swift developers.
>
> > it doesn’t have any static information about what you can do or not. It
> can’t provide the “safe by default” guarantees are other core principles
> and set Swift apart from other languages.
>
> Exactly.
>
> Look how JSON parsing is done in Swift 3.2 and 4.0—we make static types.
> The 1’s and 0’s from a web response go through layers of proper error
> handling before they become proper types Swift.
>
> So why does this proposal keeps mentioning JSON parsing as an excuse for
> making a dynamic ghetto within the language? Because some people are
> parsing untyped JSON? Well, the solution for that is, type your frickin’
> JSON.
>
> Why compromise Swift’s static-ness and roll out the red carpet for the
> dynamic, unwashed masses?
>
> Wouldn’t it be better to create an AI that quickly translates Pyton, Ruby,
> or JS into Swift? Augustus built huge public bathhouses for the unwashed
> Romans.
>
> > When we consider interoperability with other languages, it should be
> from the perspective of mapping their features to Swift’s philosophies.
>
> Amen.
>
> > This proposal takes the reverse approach, and makes Swift like Python,
> so I’m against it.
>
> This is my concern as well.
>
> Perhaps there is a way to make the proposal require that you declare Swift
> types and protocols that map to these other languages, with verbose error
> handling for when this glue breaks down (just like we have for typed JSON).
>
> Then, we could also make scripts that auto-generate the necessary Swift
> typing boilerplate interface code from the Python/Ruby/JS source, kinda
> like we get for Obj.-C bridging headers. This could be a good step towards
> the full AI translation that I mentioned.
>
> Of course, maybe I am missing something here, and my opinion is wrong;
> Chris will let us know if these concerns are valid.
>
> However, I hope we don’t hear how we are just being paranoid, because I
> assure you, this is not paranoia. It’s just about maintaining the
> static-ness and purity of Swift to help save the world from bad code.
>
> Everything in life and engineering is a trade-off. Swift’s trademark is
> that it consistently sacrifices the convenience of dynamic-ness for the
> safety and performance of static-ness. This proposal does seem to do the
> opposite, and we’d be naive not to fear the effect this will have.
>
> Ask yourself... what if Product knows about it? The last conversation a
> tech lead or engineering manager wants to have, I would imagine, is to
> explain on deaf ears why it would be bad to cut costs by farming out the
> iOS work to a cheap Python shop overseas, then just wrap it in sugary
> compiler hooks. Or why it would be bad for a Swift project to depend upon a
> stack of third-language dependencies that CocoaPods/Carthage can’t manage,
> XCode can’t analyze, stack traces can’t delve into (or can it?), lldb can’t
> step through, etc.
>
> I do not believe this is unreasonable paranoia, I just believe it looks
> that way to people who work with an elite squad of engineers at a top
> company, who have perhaps not seen what goes on at most places, where
> budgets are tight and lots of people are not the biggest fans of Apple.
> It’s already with much grinding of teeth that non-Windows, non-Linux devs
> are necessary.
>
> Given Swift’s emphasis on safety, this push to make danger easier really
> does surprise me, 

Re: [swift-evolution] Proposal: Introduce User-defined "Dynamic Member Lookup" Types

2017-12-01 Thread Jon Gilbert via swift-evolution
On Dec 1, 2017, at 02:44, Xiaodi Wu via swift-evolution 
 wrote:
> 
> So the use case here is, how do we make Swift a viable candidate for doing 
> those things which today drive users to Python? The answer here is _not_: 
> build a better Python. Nor does it require, out of the gate, even being as 
> good as Python. The solution is to provide a _reasonably_ ergonomic to 
> _interoperate with libraries available in Python_, with the benefit that 
> those parts that you can write in native Swift will make the overall result 
> safer and faster, etc.

I think we would be better served by a transpiler that translates Python (etc.) 
into Swift at compile time. 

Look what Google did with j2objc (https://github.com/google/j2objc). It 
translates Java right into Objective C. You can even put your Java code right 
in XCode and it auto-translates at build time. 

Clearly, this is no small feat, and j2objc is a technical marvel that took 
world-class engineers years to perfect. 

My point is, “Dynamic Member Lookup” is not the only solution, and it’s not the 
ideal solution if indeed it compromises the static guarantees of Swift.

Therefore, we should consider what other approaches might entail. The main 
players in Swift have lots of money and technical resources they could pour 
into a set of revolutionary transpilers. 

Surely we don’t want to allow Goole to be the only company to provide a library 
that translates other codebases directly to a primarily Apple language, do we?

That being said, I am still interested to hear Chris’s response to these 
concerns, and if they were already addressed on a previous message and I missed 
that, then please forgive me.

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


Re: [swift-evolution] Proposal: Introduce User-defined "Dynamic Member Lookup" Types

2017-12-01 Thread Dave DeLong via swift-evolution
+  

Dave

> On Dec 1, 2017, at 8:35 AM, Jon Gilbert via swift-evolution 
>  wrote:
> 
>> On Nov 30, 2017, at 08:10, Karl Wagner via swift-evolution 
>>  wrote:
>> 
>> Personally, I feel this system is designed to let you write Python, using 
>> Swift as a wrapper language - except unlike with Objective-C,
> 
> Let me paraphrase the proposal—it basically says this system is designed to 
> make it easier to “fake import” existing Python/Ruby/JS libs to make it 
> easier for people who depend on them to adopt Swift. Especially in the world 
> of server-side Swift, I can see how this could help speed Swift’s adoption.
> 
> However, I believe that you bring up an extremely valid concern. To 
> extrapolate from your points, this proposal seems to have a high potential to 
> erode what makes Swift special, and it provides a way to get around Swift’s 
> safe-guards, avoid writing Swift versions of libraries, and ultimately, avoid 
> hiring real Swift developers. 
> 
>> it doesn’t have any static information about what you can do or not. It 
>> can’t provide the “safe by default” guarantees are other core principles and 
>> set Swift apart from other languages.
> 
> Exactly. 
> 
> Look how JSON parsing is done in Swift 3.2 and 4.0—we make static types. The 
> 1’s and 0’s from a web response go through layers of proper error handling 
> before they become proper types Swift.
> 
> So why does this proposal keeps mentioning JSON parsing as an excuse for 
> making a dynamic ghetto within the language? Because some people are parsing 
> untyped JSON? Well, the solution for that is, type your frickin’ JSON. 
> 
> Why compromise Swift’s static-ness and roll out the red carpet for the 
> dynamic, unwashed masses?
> 
> Wouldn’t it be better to create an AI that quickly translates Pyton, Ruby, or 
> JS into Swift? Augustus built huge public bathhouses for the unwashed Romans. 
> 
>> When we consider interoperability with other languages, it should be from 
>> the perspective of mapping their features to Swift’s philosophies.
> 
> Amen.
> 
>> This proposal takes the reverse approach, and makes Swift like Python, so 
>> I’m against it.
> 
> This is my concern as well. 
> 
> Perhaps there is a way to make the proposal require that you declare Swift 
> types and protocols that map to these other languages, with verbose error 
> handling for when this glue breaks down (just like we have for typed JSON). 
> 
> Then, we could also make scripts that auto-generate the necessary Swift 
> typing boilerplate interface code from the Python/Ruby/JS source, kinda like 
> we get for Obj.-C bridging headers. This could be a good step towards the 
> full AI translation that I mentioned.
> 
> Of course, maybe I am missing something here, and my opinion is wrong; Chris 
> will let us know if these concerns are valid.
> 
> However, I hope we don’t hear how we are just being paranoid, because I 
> assure you, this is not paranoia. It’s just about maintaining the static-ness 
> and purity of Swift to help save the world from bad code.
> 
> Everything in life and engineering is a trade-off. Swift’s trademark is that 
> it consistently sacrifices the convenience of dynamic-ness for the safety and 
> performance of static-ness. This proposal does seem to do the opposite, and 
> we’d be naive not to fear the effect this will have. 
> 
> Ask yourself... what if Product knows about it? The last conversation a tech 
> lead or engineering manager wants to have, I would imagine, is to explain on 
> deaf ears why it would be bad to cut costs by farming out the iOS work to a 
> cheap Python shop overseas, then just wrap it in sugary compiler hooks. Or 
> why it would be bad for a Swift project to depend upon a stack of 
> third-language dependencies that CocoaPods/Carthage can’t manage, XCode can’t 
> analyze, stack traces can’t delve into (or can it?), lldb can’t step through, 
> etc.
> 
> I do not believe this is unreasonable paranoia, I just believe it looks that 
> way to people who work with an elite squad of engineers at a top company, who 
> have perhaps not seen what goes on at most places, where budgets are tight 
> and lots of people are not the biggest fans of Apple. It’s already with much 
> grinding of teeth that non-Windows, non-Linux devs are necessary.
> 
> Given Swift’s emphasis on safety, this push to make danger easier really does 
> surprise me, unless I just don’t understand this correctly. Have we 
> re-evaluated the importance of having the language itself prohibit bad 
> practices? Or is there some reason why this proposal does not actually make 
> it easier to write code that looks like good, type-safe Swift code, but 
> actually isn’t?
> 
> Finally, to really be honest, may I ask why web devs, many of whom never 
> touched a line of Swift, deserve all this dynamic sugar, while on the other 
> hand, we SWIFT devs don’t get any? How will people feel who were told that 
> 

Re: [swift-evolution] Proposal: Introduce User-defined "Dynamic Member Lookup" Types

2017-12-01 Thread Jon Gilbert via swift-evolution
> On Nov 30, 2017, at 08:10, Karl Wagner via swift-evolution 
>  wrote:
> 
> Personally, I feel this system is designed to let you write Python, using 
> Swift as a wrapper language - except unlike with Objective-C,

Let me paraphrase the proposal—it basically says this system is designed to 
make it easier to “fake import” existing Python/Ruby/JS libs to make it easier 
for people who depend on them to adopt Swift. Especially in the world of 
server-side Swift, I can see how this could help speed Swift’s adoption.

However, I believe that you bring up an extremely valid concern. To extrapolate 
from your points, this proposal seems to have a high potential to erode what 
makes Swift special, and it provides a way to get around Swift’s safe-guards, 
avoid writing Swift versions of libraries, and ultimately, avoid hiring real 
Swift developers. 

> it doesn’t have any static information about what you can do or not. It can’t 
> provide the “safe by default” guarantees are other core principles and set 
> Swift apart from other languages.

Exactly. 

Look how JSON parsing is done in Swift 3.2 and 4.0—we make static types. The 
1’s and 0’s from a web response go through layers of proper error handling 
before they become proper types Swift.

So why does this proposal keeps mentioning JSON parsing as an excuse for making 
a dynamic ghetto within the language? Because some people are parsing untyped 
JSON? Well, the solution for that is, type your frickin’ JSON. 

Why compromise Swift’s static-ness and roll out the red carpet for the dynamic, 
unwashed masses?

Wouldn’t it be better to create an AI that quickly translates Pyton, Ruby, or 
JS into Swift? Augustus built huge public bathhouses for the unwashed Romans. 

> When we consider interoperability with other languages, it should be from the 
> perspective of mapping their features to Swift’s philosophies.

Amen.

> This proposal takes the reverse approach, and makes Swift like Python, so I’m 
> against it.

This is my concern as well. 

Perhaps there is a way to make the proposal require that you declare Swift 
types and protocols that map to these other languages, with verbose error 
handling for when this glue breaks down (just like we have for typed JSON). 

Then, we could also make scripts that auto-generate the necessary Swift typing 
boilerplate interface code from the Python/Ruby/JS source, kinda like we get 
for Obj.-C bridging headers. This could be a good step towards the full AI 
translation that I mentioned.

Of course, maybe I am missing something here, and my opinion is wrong; Chris 
will let us know if these concerns are valid.

However, I hope we don’t hear how we are just being paranoid, because I assure 
you, this is not paranoia. It’s just about maintaining the static-ness and 
purity of Swift to help save the world from bad code.

Everything in life and engineering is a trade-off. Swift’s trademark is that it 
consistently sacrifices the convenience of dynamic-ness for the safety and 
performance of static-ness. This proposal does seem to do the opposite, and 
we’d be naive not to fear the effect this will have. 

Ask yourself... what if Product knows about it? The last conversation a tech 
lead or engineering manager wants to have, I would imagine, is to explain on 
deaf ears why it would be bad to cut costs by farming out the iOS work to a 
cheap Python shop overseas, then just wrap it in sugary compiler hooks. Or why 
it would be bad for a Swift project to depend upon a stack of third-language 
dependencies that CocoaPods/Carthage can’t manage, XCode can’t analyze, stack 
traces can’t delve into (or can it?), lldb can’t step through, etc.

I do not believe this is unreasonable paranoia, I just believe it looks that 
way to people who work with an elite squad of engineers at a top company, who 
have perhaps not seen what goes on at most places, where budgets are tight and 
lots of people are not the biggest fans of Apple. It’s already with much 
grinding of teeth that non-Windows, non-Linux devs are necessary.

Given Swift’s emphasis on safety, this push to make danger easier really does 
surprise me, unless I just don’t understand this correctly. Have we 
re-evaluated the importance of having the language itself prohibit bad 
practices? Or is there some reason why this proposal does not actually make it 
easier to write code that looks like good, type-safe Swift code, but actually 
isn’t?

Finally, to really be honest, may I ask why web devs, many of whom never 
touched a line of Swift, deserve all this dynamic sugar, while on the other 
hand, we SWIFT devs don’t get any? How will people feel who were told that 
dynamic is so unsafe that Swift was designed to prevent it altogether? People 
who have been through all the migrations and member-wise trenches might chafe a 
bit. Is that unreasonable?

Lastly, if you can “fake import” Javascript or Python to Swift via this 
proposal, is there anything that would 

Re: [swift-evolution] [RFC] Associated type inference

2017-12-01 Thread Johannes Weiß via swift-evolution
Hi Douglas,

First of all, thanks very much for looking into this seemingly dark corner of 
the compiler. This caused us a lot of trouble already.

Comments inline.

> On 1 Dec 2017, at 12:28 am, Douglas Gregor via swift-evolution 
>  wrote:
> 
> Hello Swift community,
> 
> Associated type inference, which is the process by which the Swift compiler 
> attempts to infer typealiases to satisfy associated-type requirements based 
> on other requirements, has caused both implementation problems and user 
> confusion for a long time. Some of you might remember a previous (failed) 
> attempt to remove this feature from the Swift language, in SE-0108 “Remove 
> associated type inference”. 
> 
> I’m not sure we can remove this feature outright (i.e., the concerns that 
> sank that proposal are still absolutely valid), because it is so very 
> convenient and a lot of user code likely depends on it in some form or other. 
> So, here I’d like to describe the uses of the feature, its current (very 
> problematic) implementation approach, and a half-baked proposal to narrow the 
> scope of associated type inference to something that I think is more 
> tractable. I need help with the design of this feature, because I feel like 
> it’s going to be a delicate balance between implementability and 
> expressiveness.
> 
> A Motivating Example
> As a motivating example, let’s consider a “minimal” random access collection:
> 
> struct MyCollection {
> var contents: [T]
> }
> 
> extension MyCollection: RandomAccessCollection {
> var startIndex: Int { return contents.startIndex }
> var endIndex: Int { return contents.endIndex }
> subscript(index: Int) -> T { return contents[index] }
> }
> 
> This is actually pretty awesome: by providing just two properties and a 
> subscript, we get the full breadth of the random access collection API! This 
> is relying heavily on associated type inference (for associated type 
> requirements) and default implementations specified on protocol extensions. 
> Without associated type inference, we would have had to write:
> 
> 
> extension MyCollection: RandomAccessCollection {
> typealias Element = T
> typealias Index = Int
> typealias Indices = CountableRange
> typealias Iterator = IndexingIterator
> typealias SubSequence = RandomAccessSlice
> 
> var startIndex: Int { return contents.startIndex }
> var endIndex: Int { return contents.endIndex }
> subscript(index: Int) -> T { return contents[index] }
> }
> 
> where the bolded typealiases are currently inferred. It was worse back when 
> we reviewed SE-0108, because IIRC there were a few underscored associated 
> types (e.g., _Element) that have since been removed. Still, that’s a bit of 
> additional work to define a “minimal” collection, and requires quite a bit 
> more understanding: how do I know to choose IndexingIterator, and 
> CountableRange, and RandomAccessSlice?
> 
> The issue would get worse with, e.g., SE-0174 “Change filter to return an 
> associated type”, which adds an associated type Filtered that almost nobody 
> will ever customize, and isn’t really fundamental to the way collections 
> work. Adding Filtered to the standard library would be a source-breaking 
> change, because users would have to write a typealias giving it its default.
> 
> Associated Type Defaults
> One of the ways in which we avoid having to specify typealiases is to use 
> associated type defaults. For example, the standard library contains 
> associated type defaults for Indices, Iterator, and SubSequence. Let’s focus 
> on Indices:
> 
> protocol Collection : Sequence {
>   associatedtype Indices = DefaultIndices
>   // ...
> }
> 
> protocol BidirectionalCollection : Collection {
>   associatedtype Indices = DefaultBidirectionalIndices
>   // ...
> }
> 
> protocol RandomAccessCollection : BidirectionalCollection {
>   associatedtype Indices = DefaultRandomAccessIndices
>   // ...
> }
> 
> The basic idea here is that different protocols in the hierarchy provide 
> different defaults, and you presumably want the default from the most 
> specific protocol. If I define a type and make it conform to 
> BidirectionalCollection, I’d expect to get DefaultBidirectionalIndices 
> for Indices. If a define a type and make it conform to RandomAccessIterator, 
> I’d expect to get DefaultRandomAccessIndices.
> 
> (Aside: DefaultRandomAccessIndices and DefaultBidirectionalIndices got 
> collapsed into DefaultIndices now that we have conditional conformances for 
> the standard library, but the issues I’m describing remain).
> 
> Associated type defaults seem like a reasonable feature that fits well enough 
> into the design. However, it’s not the only thing in place with our 
> MyCollection example, for which Indices was inferred to CountableRange. How’s 
> that happen?
> 
> Associated Type Inference
> Associated type inference attempts to look at the 

Re: [swift-evolution] Proposal: Introduce User-defined "Dynamic Member Lookup" Types

2017-12-01 Thread Xiaodi Wu via swift-evolution
On Fri, Dec 1, 2017 at 4:17 AM, Karl Wagner via swift-evolution <
swift-evolution@swift.org> wrote:

>
>
> > On 1. Dec 2017, at 07:05, Chris Lattner via swift-evolution <
> swift-evolution@swift.org> wrote:
> >
> > Hi Doug,
> >
> > Thank you for the detailed email.  I have been traveling today, so I
> haven’t had a chance to respond until now.  I haven’t read the down-thread
> emails, so I apologize if any of this was already discussed:
> >
> >> I think better interoperability with Python (and other OO languages in
> widespread use) is a good goal, and I agree that the implementation of the
> feature described is straight-forward and not terribly invasive in the
> compiler.
> >
> > Fantastic, I’m really pleased to hear that!  I only care about solving
> the problem, so if we can find a good technical solution to the problems
> than I’ll be happy.
> >
> > A funny thing about swift-evolution is that it is populated with lots of
> people who already use Swift and want to see incremental improvements, but
> the people who *aren’t* using Swift yet (but should be) aren’t represented
> here.  As you know, I’m perhaps the biggest proponent of Swift spreading
> into new domains and earning the love of new users.
>
>
> I don’t really appreciate that argument. You also need to consider: what
> improvements are we offering these people who don’t yet use Swift?
>
> For Objective-C developers, the static typing and resulting performance
> and safety improvements made this a worthwhile switch. Plus, we could
> interoperate very well with existing Objective-C codebases and libraries
> (e.g. we can have generic subclasses of NSObject!), so we could actually
> use a lot of these nice features when writing our mac/iOS applications.
>
> For Python developers, I gather the pitch would be similar: Swift has all
> kinds of nice features which will make your code safer and faster. We’re
> unlikely to achieve the same tight integration with Python (or any other
> language) that we have with Objective-C, though. We used to rely a lot on
> AnyObject, but since Objective-C made the importing experience so much
> better, you rarely (if ever) see it in practice. Objective-C can also be
> more dynamic than we show it as - you can have methods which are not
> declared anywhere, and which the object synthesises during its
> message-handling routines. We don’t support calling these non-existing
> methods on Objective-C objects, so why should we allow it for these objects?
>
> My worry is that in eagerness to try and scoop up developers of other
> languages, that we diminish the Swift language to the point where it
> doesn’t really provide a benefit for them. Python developers will be
> writing the same unsafe, non-checked code using Swift that they do in
> Python; where’s the win?
>

It's not about getting "Python developers" or "Ruby developers" to switch
to Swift. Yes, if you believe the objective is to attract people who like
Python to Swift, then you must offer something "better than Python." Now,
given that some of the things that attract people to Python have to do with
its dynamic behavior, you've defined an impossible task right off the bat.
But that's not the objective here and it misses the point entirely. No, the
motivation instead is this:

Why would someone--someone who might not even know Python or Ruby--choose
to use those languages? Why does some bother to learn Python or Ruby other
than curiosity or love of the language itself? The answer is that there are
some tasks that are best accomplished using those languages because of
libraries and their user communities--so much better than one's other
favorite languages that those other languages are not even in contention.
In my case, many excellent computational biology tools were only available
(nowadays, are most mature and have the biggest ecosystem of users) in
languages such as Python or Perl. So the use case here is, how do we make
Swift a viable candidate for doing those things which today drive users to
Python? The answer here is _not_: build a better Python. Nor does it
require, out of the gate, even being as good as Python. The solution is to
provide a _reasonably_ ergonomic to _interoperate with libraries available
in Python_, with the benefit that those parts that you can write in native
Swift will make the overall result safer and faster, etc.

Again, it's _not_ about "scooping up developers of other languages"--it's
about expanding the universe of computational tasks for which Swift is a
viable candidate. This is why, also, Chris's insistence that the solution
be equally available in the REPL and in Playgrounds is so important.
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Proposal: Introduce User-defined "Dynamic Member Lookup" Types

2017-12-01 Thread Karl Wagner via swift-evolution


> On 1. Dec 2017, at 07:05, Chris Lattner via swift-evolution 
>  wrote:
> 
> Hi Doug,
> 
> Thank you for the detailed email.  I have been traveling today, so I haven’t 
> had a chance to respond until now.  I haven’t read the down-thread emails, so 
> I apologize if any of this was already discussed:
> 
>> I think better interoperability with Python (and other OO languages in 
>> widespread use) is a good goal, and I agree that the implementation of the 
>> feature described is straight-forward and not terribly invasive in the 
>> compiler.
> 
> Fantastic, I’m really pleased to hear that!  I only care about solving the 
> problem, so if we can find a good technical solution to the problems than 
> I’ll be happy.
> 
> A funny thing about swift-evolution is that it is populated with lots of 
> people who already use Swift and want to see incremental improvements, but 
> the people who *aren’t* using Swift yet (but should be) aren’t represented 
> here.  As you know, I’m perhaps the biggest proponent of Swift spreading into 
> new domains and earning the love of new users.


I don’t really appreciate that argument. You also need to consider: what 
improvements are we offering these people who don’t yet use Swift?

For Objective-C developers, the static typing and resulting performance and 
safety improvements made this a worthwhile switch. Plus, we could interoperate 
very well with existing Objective-C codebases and libraries (e.g. we can have 
generic subclasses of NSObject!), so we could actually use a lot of these nice 
features when writing our mac/iOS applications.

For Python developers, I gather the pitch would be similar: Swift has all kinds 
of nice features which will make your code safer and faster. We’re unlikely to 
achieve the same tight integration with Python (or any other language) that we 
have with Objective-C, though. We used to rely a lot on AnyObject, but since 
Objective-C made the importing experience so much better, you rarely (if ever) 
see it in practice. Objective-C can also be more dynamic than we show it as - 
you can have methods which are not declared anywhere, and which the object 
synthesises during its message-handling routines. We don’t support calling 
these non-existing methods on Objective-C objects, so why should we allow it 
for these objects?

My worry is that in eagerness to try and scoop up developers of other 
languages, that we diminish the Swift language to the point where it doesn’t 
really provide a benefit for them. Python developers will be writing the same 
unsafe, non-checked code using Swift that they do in Python; where’s the win?

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


Re: [swift-evolution] Proposal: Introduce User-defined "Dynamic Member Lookup" Types

2017-12-01 Thread Benjamin G via swift-evolution
On Fri, Dec 1, 2017 at 11:03 AM, Benjamin G via swift-evolution <
swift-evolution@swift.org> wrote:

> I think the fear most of us , poor developers working with developers of
> various skills, is the potential for abuse. I've heard many times that it
> isn't a guiding principle for swift, so i'll just reformulate the concern
> in a more acceptable way :
> Could your proposal explain how the swift language will still keep
> encouraging developers to use static / compile-time type checking *when
> it's possible* ? (because i think we can all argue that a compile-time
> checks is better than a runtime one). Obviously, python interop isn't my
> concern here. I'm talking about the impact of your proposal on pure swift
> code.
>
> As example, calling some feature "unsafe", or "force", makes every
> developer pause and wonder if there isn't a better alternative. I'd like to
> see the same kind of things for dynamic calls.
>

A few examples of the kind of things that i would think about :
- use different file names for code using dynamic features.
- have every dynamic code included in a dynamic{} block
- have a different syntax for dynamic function calls, using ! or !!!
- Make the dynamic calls work only of subclasses of a base "PythonObject".
That would make the goal clear.
etc.
Now, i think those are all bad ideas (and that's why i don't like the
proposal in the first place). But i really think the concern should be
addressed.



>
>
> On Fri, Dec 1, 2017 at 10:30 AM, Chris Lattner via swift-evolution <
> swift-evolution@swift.org> wrote:
>
>> On Dec 1, 2017, at 12:26 AM, Douglas Gregor  wrote:
>>
>> *Philosophy*
>> Swift is, unabashedly, a strong statically-typed language.
>>
>>
>> That’s factually incorrect.
>>
>>
>> You’re going to have to explain that statement without reference to
>> AnyObject (we’ll discuss that case below).
>>
>>
>> Perhaps it depends on what you mean by “strong”: I interpreted that as
>> meaning that it provides type safety, with a level of strength akin to what
>> Java provides: a level that could support mobile code deployment.
>>
>> Swift certainly does not provide that strong of a static type system,
>> because it gives people explicit ways to opt out of that.
>> UnsafeMutableRawPointer, unsafe bitcast, and many other facilities support
>> this.  It also allows calling into non-type safe code, so it isn’t very
>> strong that way.  There are also race conditions and other holes in the
>> type system.
>>
>> All that said, I think it is correct that a subset of Swift exists that
>> does provide strong type safety, but particularly when bridging to C/ObjC
>> is involved, that quickly goes away.
>>
>>
>> More problematically for your argument: your preferred approach requires
>> the introduction of (something like) DynamicMemberLookupProtocol or
>> something like AnyObject-For-Python, so your proposal would be additive on
>> top of solving the core problem I’m trying to solve.  It isn’t an
>> alternative approach at all.
>>
>>
>> I wouldn’t say that’s my preferred approach. My preferred approach
>> involves taking the method/property/etc. declarations that already exist in
>> Python and mapping them into corresponding Swift declarations so we have
>> something to find with name lookup. One could put all of these declarations
>> on some PyVal struct or PythonObject and there would be no need for
>> AnyObject-for-Python or DynamicMemberLookupProtocol.
>>
>>
>> You’re suggesting that the transitive closure of all Python methods and
>> properties be preprocessed into a single gigantic Swift PyVal type?  I
>> guess something like that could be done.
>>
>> I would be concerned because there are many N^2 or worse algorithms in
>> the Swift compiler would probably explode.  It also doesn’t provide the
>> great tooling experience that you’re seeking, given that code completion
>> would show everything in the Python universe, which is not helpful.
>>
>> Further, it doesn’t provide a *better* experience than what I’m
>> suggesting, it seems strictly worse.  A preprocessing step prevents users
>> from playfully importing random Python modules into the Swift repl and
>> playgrounds.  It also seems worse for implementors (who will get a stream
>> of new bugs about compiler scalability).
>>
>> Whenever we discuss adding more dynamic features to Swift, there’s a
>> strong focus on maintaining that strong static type system.
>>
>>
>> Which this does, by providing full type safety - unlike AnyObject lookup.
>>
>>
>> You get dynamic safety because it goes into the Python interpreter; fair
>> enough. You get no help from your tools to form a correct invocation of any
>> method provided by Python.
>>
>>
>> Sure, that’s status quo for Python APIs.
>>
>> IMO, this proposal is a significant departure from the fundamental
>> character of Swift, because it allows access to possibly-nonexistent
>> members (as well as calls with incorrect arguments, in the related
>> proposal) without any 

Re: [swift-evolution] Proposal: Introduce User-defined "Dynamic Member Lookup" Types

2017-12-01 Thread Benjamin G via swift-evolution
I think the fear most of us , poor developers working with developers of
various skills, is the potential for abuse. I've heard many times that it
isn't a guiding principle for swift, so i'll just reformulate the concern
in a more acceptable way :
Could your proposal explain how the swift language will still keep
encouraging developers to use static / compile-time type checking *when
it's possible* ? (because i think we can all argue that a compile-time
checks is better than a runtime one). Obviously, python interop isn't my
concern here. I'm talking about the impact of your proposal on pure swift
code.

As example, calling some feature "unsafe", or "force", makes every
developer pause and wonder if there isn't a better alternative. I'd like to
see the same kind of things for dynamic calls.


On Fri, Dec 1, 2017 at 10:30 AM, Chris Lattner via swift-evolution <
swift-evolution@swift.org> wrote:

> On Dec 1, 2017, at 12:26 AM, Douglas Gregor  wrote:
>
> *Philosophy*
> Swift is, unabashedly, a strong statically-typed language.
>
>
> That’s factually incorrect.
>
>
> You’re going to have to explain that statement without reference to
> AnyObject (we’ll discuss that case below).
>
>
> Perhaps it depends on what you mean by “strong”: I interpreted that as
> meaning that it provides type safety, with a level of strength akin to what
> Java provides: a level that could support mobile code deployment.
>
> Swift certainly does not provide that strong of a static type system,
> because it gives people explicit ways to opt out of that.
> UnsafeMutableRawPointer, unsafe bitcast, and many other facilities support
> this.  It also allows calling into non-type safe code, so it isn’t very
> strong that way.  There are also race conditions and other holes in the
> type system.
>
> All that said, I think it is correct that a subset of Swift exists that
> does provide strong type safety, but particularly when bridging to C/ObjC
> is involved, that quickly goes away.
>
>
> More problematically for your argument: your preferred approach requires
> the introduction of (something like) DynamicMemberLookupProtocol or
> something like AnyObject-For-Python, so your proposal would be additive on
> top of solving the core problem I’m trying to solve.  It isn’t an
> alternative approach at all.
>
>
> I wouldn’t say that’s my preferred approach. My preferred approach
> involves taking the method/property/etc. declarations that already exist in
> Python and mapping them into corresponding Swift declarations so we have
> something to find with name lookup. One could put all of these declarations
> on some PyVal struct or PythonObject and there would be no need for
> AnyObject-for-Python or DynamicMemberLookupProtocol.
>
>
> You’re suggesting that the transitive closure of all Python methods and
> properties be preprocessed into a single gigantic Swift PyVal type?  I
> guess something like that could be done.
>
> I would be concerned because there are many N^2 or worse algorithms in the
> Swift compiler would probably explode.  It also doesn’t provide the great
> tooling experience that you’re seeking, given that code completion would
> show everything in the Python universe, which is not helpful.
>
> Further, it doesn’t provide a *better* experience than what I’m
> suggesting, it seems strictly worse.  A preprocessing step prevents users
> from playfully importing random Python modules into the Swift repl and
> playgrounds.  It also seems worse for implementors (who will get a stream
> of new bugs about compiler scalability).
>
> Whenever we discuss adding more dynamic features to Swift, there’s a
> strong focus on maintaining that strong static type system.
>
>
> Which this does, by providing full type safety - unlike AnyObject lookup.
>
>
> You get dynamic safety because it goes into the Python interpreter; fair
> enough. You get no help from your tools to form a correct invocation of any
> method provided by Python.
>
>
> Sure, that’s status quo for Python APIs.
>
> IMO, this proposal is a significant departure from the fundamental
> character of Swift, because it allows access to possibly-nonexistent
> members (as well as calls with incorrect arguments, in the related
> proposal) without any indication that the operation might fail.
>
>
> The only way your claim is correct is if someone implements the protocol
> wrong.  What you describe is true of AnyObject lookup though, so I
> understand how you could be confused by that.
>
>
> AnyObject lookup still requires you to find an actual declaration with a
> type signature. Yes, there are still failure cases. The dynamic type might
> be totally unrelated to the class in which you found the declaration you’re
> supposedly calling, which is a typical “unrecognized selector” failure and
> will always be an issue with dynamic typing. The actual type safety hole
> you’re presumably referring to is that the selector could be overloaded
> with a different type signature, and 

Re: [swift-evolution] Proposal: Introduce User-defined "Dynamic Member Lookup" Types

2017-12-01 Thread Chris Lattner via swift-evolution
> On Dec 1, 2017, at 12:26 AM, Douglas Gregor  wrote:
>>> Philosophy
>>> Swift is, unabashedly, a strong statically-typed language.
>> 
>> That’s factually incorrect.
> 
> You’re going to have to explain that statement without reference to AnyObject 
> (we’ll discuss that case below).

Perhaps it depends on what you mean by “strong”: I interpreted that as meaning 
that it provides type safety, with a level of strength akin to what Java 
provides: a level that could support mobile code deployment.

Swift certainly does not provide that strong of a static type system, because 
it gives people explicit ways to opt out of that.  UnsafeMutableRawPointer, 
unsafe bitcast, and many other facilities support this.  It also allows calling 
into non-type safe code, so it isn’t very strong that way.  There are also race 
conditions and other holes in the type system.

All that said, I think it is correct that a subset of Swift exists that does 
provide strong type safety, but particularly when bridging to C/ObjC is 
involved, that quickly goes away.


>> More problematically for your argument: your preferred approach requires the 
>> introduction of (something like) DynamicMemberLookupProtocol or something 
>> like AnyObject-For-Python, so your proposal would be additive on top of 
>> solving the core problem I’m trying to solve.  It isn’t an alternative 
>> approach at all.
> 
> I wouldn’t say that’s my preferred approach. My preferred approach involves 
> taking the method/property/etc. declarations that already exist in Python and 
> mapping them into corresponding Swift declarations so we have something to 
> find with name lookup. One could put all of these declarations on some PyVal 
> struct or PythonObject and there would be no need for AnyObject-for-Python or 
> DynamicMemberLookupProtocol.

You’re suggesting that the transitive closure of all Python methods and 
properties be preprocessed into a single gigantic Swift PyVal type?  I guess 
something like that could be done.

I would be concerned because there are many N^2 or worse algorithms in the 
Swift compiler would probably explode.  It also doesn’t provide the great 
tooling experience that you’re seeking, given that code completion would show 
everything in the Python universe, which is not helpful.

Further, it doesn’t provide a *better* experience than what I’m suggesting, it 
seems strictly worse.  A preprocessing step prevents users from playfully 
importing random Python modules into the Swift repl and playgrounds.  It also 
seems worse for implementors (who will get a stream of new bugs about compiler 
scalability).

>>> Whenever we discuss adding more dynamic features to Swift, there’s a strong 
>>> focus on maintaining that strong static type system.
>> 
>> Which this does, by providing full type safety - unlike AnyObject lookup.
> 
> You get dynamic safety because it goes into the Python interpreter; fair 
> enough. You get no help from your tools to form a correct invocation of any 
> method provided by Python.

Sure, that’s status quo for Python APIs.

>>> IMO, this proposal is a significant departure from the fundamental 
>>> character of Swift, because it allows access to possibly-nonexistent 
>>> members (as well as calls with incorrect arguments, in the related 
>>> proposal) without any indication that the operation might fail.
>> 
>> The only way your claim is correct is if someone implements the protocol 
>> wrong.  What you describe is true of AnyObject lookup though, so I 
>> understand how you could be confused by that.
> 
> AnyObject lookup still requires you to find an actual declaration with a type 
> signature. Yes, there are still failure cases. The dynamic type might be 
> totally unrelated to the class in which you found the declaration you’re 
> supposedly calling, which is a typical “unrecognized selector” failure and 
> will always be an issue with dynamic typing. The actual type safety hole 
> you’re presumably referring to is that the selector could be overloaded with 
> a different type signature, and we don’t proactively check that the signature 
> we type-checked against matches the signature found at runtime. It’s doable 
> with the Objective-C method encodings, but has never been considered 
> worthwhile.

To be clear, I’m not suggesting a change to AnyObject lookup.  I don’t think 
that it is worth changing at this point in time.  My point was to observe that 
the proposed DynamicMemberLookupProtocol proposal does not suffer from these 
problems.  It really is type / memory safe, assuming a sane implementation.


>>> It’s easy to fall through these cracks for any type that supports 
>>> DynamicMemberLookupProtocol—a single-character typo when using a 
>>> DynamicMemberLookupProtocol-capable type means you’ve fallen out of the 
>>> safety that Swift provides.
>> 
>> Since you seem to be latching on to this, I’ll say it again: the proposal is 
>> fully type safe :-)
>> 
>> That said, the “simple 

Re: [swift-evolution] Proposal: Introduce User-defined "Dynamic Member Lookup" Types

2017-12-01 Thread Douglas Gregor via swift-evolution


> On Nov 30, 2017, at 10:05 PM, Chris Lattner  wrote:
> 
> Hi Doug,
> 
> Thank you for the detailed email.  I have been traveling today, so I haven’t 
> had a chance to respond until now.  I haven’t read the down-thread emails, so 
> I apologize if any of this was already discussed:
> 
>> I think better interoperability with Python (and other OO languages in 
>> widespread use) is a good goal, and I agree that the implementation of the 
>> feature described is straight-forward and not terribly invasive in the 
>> compiler.
> 
> Fantastic, I’m really pleased to hear that!  I only care about solving the 
> problem, so if we can find a good technical solution to the problems than 
> I’ll be happy.
> 
> A funny thing about swift-evolution is that it is populated with lots of 
> people who already use Swift and want to see incremental improvements, but 
> the people who *aren’t* using Swift yet (but should be) aren’t represented 
> here.  As you know, I’m perhaps the biggest proponent of Swift spreading into 
> new domains and earning the love of new users.

While I, too, am interested in attracting new users to Swift, it should not 
come at the cost of making the language less coherent.

>> However, I do not think this proposal is going in the right direction for 
>> Swift. I have objections on several different grounds.
> 
> Thanks for being up front about this.  It turns out that a majority of the 
> points you raise were brought up early in the pitch phases of the discussion, 
> but I screwed up by not capturing that discussion into the alternatives 
> section of the proposal.
> 
> Better late than never I guess: I just significantly revised the proposal, 
> adding a new “Alternative Python Interoperability Approaches” section.  I’d 
> appreciate it if you could read it and comment if you find any part 
> disagreeable:
> https://gist.github.com/lattner/b016e1cf86c43732c8d82f90e5ae5438#alternative-python-interoperability-approaches
>  
> 
> 
> Many of the points you make are discussed there, but I’ll respond 
> point-by-point below as well:
> 
>> Philosophy
>> Swift is, unabashedly, a strong statically-typed language.
> 
> That’s factually incorrect.

You’re going to have to explain that statement without reference to AnyObject 
(we’ll discuss that case below).

>> We don’t allow implicit down casting, we require “as?” so you have to cope 
>> with the possibility of failure (or use “as!” and think hard about the “!”). 
>> Even the gaping hole that is AnyObject dispatch still requires the existence 
>> of an @objc declaration and produces an optional lookup result, so the user 
>> must contend with the potential for dynamic failure.
> 
> AnyObject dispatch is one of the gaping holes for sure.  You don’t mention 
> it, but its lookup results are represented as *ImplicitlyUnwrappedOptional* 
> results, which do not force the user to contend with dynamic failure.  
> Further, unlike my proposal (which is fully type safe), AnyObject lookup is 
> not type safe at all.

As noted, AnyObject is a gaping hole, and the fact that it still produces an 
ImplicitlyUnwrappedOptional does make my statement weaker. It means you can 
dynamically end up with “unrecognized selector” without having acknowledged the 
possibility with a ‘!’.

>  It is also far more invasively intertwined throughout the compiler.

Not so much any more; there’s the weird lookup rule and some expression kinds 
that get mapped directly through to objc_msgSend.

> 
> More problematically for your argument: your preferred approach requires the 
> introduction of (something like) DynamicMemberLookupProtocol or something 
> like AnyObject-For-Python, so your proposal would be additive on top of 
> solving the core problem I’m trying to solve.  It isn’t an alternative 
> approach at all.

I wouldn’t say that’s my preferred approach. My preferred approach involves 
taking the method/property/etc. declarations that already exist in Python and 
mapping them into corresponding Swift declarations so we have something to find 
with name lookup. One could put all of these declarations on some PyVal struct 
or PythonObject and there would be no need for AnyObject-for-Python or 
DynamicMemberLookupProtocol.

>> Whenever we discuss adding more dynamic features to Swift, there’s a strong 
>> focus on maintaining that strong static type system.
> 
> Which this does, by providing full type safety - unlike AnyObject lookup.

You get dynamic safety because it goes into the Python interpreter; fair 
enough. You get no help from your tools to form a correct invocation of any 
method provided by Python.

> 
>> IMO, this proposal is a significant departure from the fundamental character 
>> of Swift, because it allows access to possibly-nonexistent members (as well 
>> as calls with incorrect arguments, in the related proposal) without any 

Re: [swift-evolution] Proposal: Introduce User-defined "Dynamic Member Lookup" Types

2017-12-01 Thread David Hart via swift-evolution


> On 1 Dec 2017, at 00:54, Xiaodi Wu via swift-evolution 
>  wrote:
> 
>> On Thu, Nov 30, 2017 at 2:24 AM, Douglas Gregor via swift-evolution 
>>  wrote:
>> 
>> 
>>> On Nov 26, 2017, at 10:04 PM, Chris Lattner via swift-evolution 
>>>  wrote:
>>> 
>>> I’d like to formally propose the inclusion of user-defined dynamic member 
>>> lookup types.
>>> 
>>> Here is my latest draft of the proposal:
>>> https://gist.github.com/lattner/b016e1cf86c43732c8d82f90e5ae5438
>>> https://github.com/apple/swift-evolution/pull/768
>>> 
>>> An implementation of this design is available here:
>>> https://github.com/apple/swift/pull/13076
>>> 
>>> The implementation is straight-forward and (IMO) non-invasive in the 
>>> compiler.
>> 
>> 
>> I think better interoperability with Python (and other OO languages in 
>> widespread use) is a good goal, and I agree that the implementation of the 
>> feature described is straight-forward and not terribly invasive in the 
>> compiler.
>> 
>> However, I do not think this proposal is going in the right direction for 
>> Swift. I have objections on several different grounds.
>> 
>> Philosophy
>> Swift is, unabashedly, a strong statically-typed language. We don’t allow 
>> implicit down casting, we require “as?” so you have to cope with the 
>> possibility of failure (or use “as!” and think hard about the “!”). Even the 
>> gaping hole that is AnyObject dispatch still requires the existence of an 
>> @objc declaration and produces an optional lookup result, so the user must 
>> contend with the potential for dynamic failure. Whenever we discuss adding 
>> more dynamic features to Swift, there’s a strong focus on maintaining that 
>> strong static type system.
>> 
>> IMO, this proposal is a significant departure from the fundamental character 
>> of Swift, because it allows access to possibly-nonexistent members (as well 
>> as calls with incorrect arguments, in the related proposal) without any 
>> indication that the operation might fail. It’s easy to fall through these 
>> cracks for any type that supports DynamicMemberLookupProtocol—a 
>> single-character typo when using a DynamicMemberLookupProtocol-capable type 
>> means you’ve fallen out of the safety that Swift provides. I think that’s a 
>> poor experience for the Python interoperability case, but more on that in 
>> the Tooling section below.
>> 
>> While we shouldn’t necessarily avoid a feature simply because it can be used 
>> distastefully, consider something like this:
>> 
>>  public extension NSObject :  DynamicMemberLookupProtocol, 
>> DynamicCallableProtocol { … }
>> 
>> that goes directly to the Objective-C runtime to resolve member lookups and 
>> calls—avoiding @objc, bridging headers, and so on. It’s almost frighteningly 
>> convenient, and one could imagine some mixed Objective-C/Swift code bases 
>> where this would save a lot of typing (of code)… at the cost of losing 
>> static typing in the language. The presence of that one extension means I 
>> can no longer rely on the safety guarantees Swift normally provides, for any 
>> project that imports that extension and uses a subclass of NSObject. At 
>> best, we as a community decide “don’t do that”; at worse, some nontrivial 
>> fraction of the community decides that the benefits outweigh the costs (for 
>> this type or some other), and we can no longer say that Swift is a strong 
>> statically-typed language without adding “unless you’re using something that 
>> adopts DynamicMemberLookupProtocol”.
> 
> There are several commenters below to whom I would have liked to respond in 
> the fullness of time, but time constraints would make doing so prohibitive. 
> Since your message set off an abundance of discussion, I'll reply to the 
> points you make here and, along the way, ask your forbearance to bring up and 
> respond to some related concerns raised by others.
> 
> I agree that the prospect above seems not ideal at all. On reading Chris's 
> proposal, it never occurred to me that the intention was to support such 
> retroactive conformance to these special protocols. Admittedly, such 
> retroactive conformance is possible with all protocols--with the notable 
> exception of those that require compiler synthesis of requirements. But 
> Chris's protocols seemed magical enough (in the gut feeling sense) that I 
> naturally assumed that retroactive conformance was never on the table. We 
> would be justified in making that prohibition here, I think, although I'm not 
> sure if Chris as proposal author feels the same way.
> 
> Alternatively--and perhaps more elegantly--we could address this concern 
> head-on by having, instead of `DynamicMemberLookupProtocol` and 
> `DynamicCallable`, a magical class `DynamicObject` which all dynamic types 
> must inherit from. It would then be clear by design that Swift types cannot 
> be _retroactively dynamic_ in the sense that Chris proposes. I 

Re: [swift-evolution] [Proposal] Random Unification

2017-12-01 Thread Mike Kluev via swift-evolution
on Thu, 30 Nov 2017 15:08:55 -0800 Jonathan Hull  wrote:

>
> I think it is important to have Type.random as the base because there are
> many types which would conform (not just Int & Double).



what would Double.random return though? a "uniformly distributed value" in
the range minus DBL_MAX ...  plus DBL_MAX ?

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


Re: [swift-evolution] [Proposal] Random Unification

2017-12-01 Thread Jonathan Hull via swift-evolution

> On Nov 30, 2017, at 11:11 PM, Martin Waitz  wrote:
> 
> Hello,
> 
>> The collection is a subject which has elements, and we are asking for one of 
>> them at random.
> 
> it has elements, sure.
> And because of its structure, it has a first and a last element and whatever.
> But that random element is not an inherent property of the collection.
> 
> I find it much more natural to use the random number generator to draw random 
> elements from collections than the other way round.
> That approach also completely side-steps the problem with having to define 
> default arguments. The user can just use any random number generator she has. 
> Obviously, it makes sense to provide a default one named `random` to make it 
> easily accessible.
> 
 var list = [1,2,3,4]
 let a:Int? = list.randomElement //List is still [1,2,3,4] and ‘a’ contains 
 one of the elements
>>> 
>>> Instead I would prefer to have something like:
>>> 
>>> let a = random.draw(from: list)
>> 
>> But now the RNG has to understand the concept of collections. I would argue 
>> it is much cleaner to write an extension on Collection.
>> 
>> func randomElement(using source: RandomSource = .default) -> Element? {
>>  guard !isEmpty else {return nil}
>>  let idx = Int.random(in: 0…(count - 1), using: source)
>>  return self[idx]
>> }
> 
> But then the Collection has to understand the concept of random numbers. ;-)
Not really.  Collection itself doesn’t have to change it’s structure at all.  
We can just define a convenience function in an extension.

> Well both approaches are equally clean from this point of view:

With a protocol defining random() and random(in:), you could write generic 
algorithms on things which know how to create themselves from a RNG.  With your 
approach the RNG has to provide a way to get a random value for each type you 
want to support.

For example, without random(in:) or random(), how would you get a CGFloat 
between 0 and 1?  Ranges are only collections if they are countable…


> 
> extension RandomFoo {
>func draw(from urn: T) -> T.Element? {
>guard !urn.isEmpty else { return nil }
>let idx = draw(from: urn.indices)
>return urn[idx]
>}
> }
> 
This will call itself repeatedly and hang...


> We just have to define one base protocol for such extensions. Every random 
> number generator then automatically knows how to draw elements from ranges 
> and collections.

It isn’t automatic, thought.  How would I get a random color?



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