Re: [swift-evolution] [Pitch] Percentage Type

2018-01-17 Thread Xiaodi Wu via swift-evolution
On Wed, Jan 17, 2018 at 2:04 AM, David Sweeris  wrote:

>
>
> Sent from my iPhone
>
> > On Jan 16, 2018, at 23:45, Jonathan Hull via swift-evolution <
> swift-evolution@swift.org> wrote:
> >
> > Mainly semantics.
> >
> > We could technically use Int instead of having a Bool type (just using 1
> and 0).  We don’t do that since Int and Bool have intrinsically different
> meanings in code.
> >
> > What I am saying is that parameters that take the range 0 to 1 typically
> have a fundamentally different meaning (or at least a different way of
> thinking about them) than Doubles.  It would be nice to be able to see that
> distinction when using APIs.
> >
> > With both this and the Angle type, I am pointing out areas where, due to
> historical reasons in C, we have conflated a bunch of types which have
> different behavior, and then just expect programmers to be conscientious
> enough to use them correctly in each case.  These types/numbers all have a
> different forms of dimensionality.
> >
> > I’d like to discuss that before we lock everything down.
>
> +1 (although I think a “normalized to [0, 1]” type would be more useful
> than a “percentage” type)
>

Bool is not a good example; it permits precisely two logical values (0 and
1). By contrast, if you're going to support 1000%, then your type supports
the same values as the underlying storage. As I wrote in a different
thread, one way to look at a type is the set of values that a variable can
have.

What is your limiting principle here if you think that a range that's not
enforced makes a value become of a different type? Often, a 1-5 rating
system is used. Sometimes, it's 1-4 or 1-10. And of course, a "3" on a 1-5
scale means something very different from a "3" on a 1-10 scale. Should
ScaleFrom1To5 be its own type? And also ScaleFrom1To4 and ScaleFrom1To10?

Besides, even supposing a percentage type would be in high demand, there's
no need for its inclusion in the standard library. It's very easy to
implement on your own in a third-party library. Moreover, custom operators
will allow you to define a postfix `%`, and then you could write: `let x =
100%`. Throw in some heterogeneous arithmetic operators and you could do
almost any math you want.
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] FloatingPoint does not conform to ExpressibleByFloatLiteral

2018-01-17 Thread Xiaodi Wu via swift-evolution
On Wed, Jan 17, 2018 at 4:56 PM, Jonathan Hull via swift-evolution <
swift-evolution@swift.org> wrote:

> I’m with Nevin on this one.  Perhaps the easiest thing to do is to add
> something to the FloatLiteral type that lets you get it as a string if
> desired.
>
> Didn’t we have a discussion a while back on how to make Integer Literals
> work with BigInt?  Maybe there is an idea from that discussion that would
> help.
>
> Tl;dr:  Literals shouldn’t be tied to a particular implementation of a
> single conforming type (though they can/should be optimized for common
> implementations).  The issue here is that FloatLiteral is throwing out
> information which is given to it based on its underlying implementation.  I
> view this as a bug.
>

I suppose you can view it as anything you want; but the initial question
was whether there is a reason that FloatingPoint doesn't conform to
ExpressibleByFloatLiteral, and there very much is: namely, the current
semantics of a float literal.

Literals aren't tied to any particular conforming type, but they are always
tied to some group of built-in types. Until there's a clear additional use
case (e.g., a Decimal type), it's pretty pointless to redesign literal
protocols, because whether or not a particular way in which information
about the literal value is conveyed to the initializer is ergonomic and
efficient will depend on the underlying implementation of the type.

BigInt will be able to take advantage, in the next version of Swift, to
DoubleWidth's conformance to _ExpressibleByBuiltinIntegerLiteral; in other
words, literals of up to 2048 bits are supported, and that's plenty for a
literal.


> Thanks,
> Jon
>
>
>
> On Jan 16, 2018, at 4:20 PM, Nevin Brackett-Rozinsky via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> On Tue, Jan 16, 2018 at 6:31 PM, Xiaodi Wu  wrote:
>
>> On Tue, Jan 16, 2018 at 4:30 PM, Nevin Brackett-Rozinsky <
>> nevin.brackettrozin...@gmail.com> wrote:
>>
>>> The thing that is “broken” here is generic programming. If I constrain
>>> something to FloatingPoint, I cannot use a float literal in calculations
>>> with it:
>>>
>>> func centimeters (inches: T) -> T {
>>> return 2.54 * inches// Error
>>>
>>> }
>>>
>>
>> Why not constrain it to `BinaryFloatingPoint`? What other types are you
>> trying to use with this function?
>>
>
> We should not ask nor expect people to constrain their generic algorithms
> to BinaryFloatingPoint unless they are working with the radix.
>
>
>
>> so that eg. a Rational type could be used. And that gives a hint as to
>>> the workaround:
>>>
>>> func centimeters (inches: T) -> T {
>>> return (254 / 100) * inches
>>> }
>>>
>>
>> Yes, you *could* do that.
>>
>
> And it seems I *will* be doing that, as long as such a workaround is
> necessary. Though it does appear to have the unfortunate cost of an extra
> division operation.
>
>
> That only works for numbers which don’t overflow the integer literals
>>> though.
>>>
>>
>> Integer literals don't overflow until 2048 bits. The following compiles
>> just fine:
>>
>> func moles(particles: T) -> T {
>>   let N_A: T = 602_214_085_774_000_000_000_000
>>   return particles / N_A
>> }
>>
>
> When I write that in a playground it shows N_A as 1.67866967797794e+18.
>
> (Also, you appear to have mistakenly concatenated the standard uncertainty
> in the last 2 digits, “74”, onto the accepted value for the constant.)
>
>
> If we want a really large or small value then we have to split it in
>>> pieces:
>>>
>>> func moles  (particles: T) -> T {
>>> let avogadroNumber: T = 6_022_140_857 * 100_000_000_000_000
>>> return particles / avogadroNumber
>>>
>>> }
>>>
>>> It would be much nicer to write “let avogadroNumber: T = 6.022140857e23”.
>>>
>>
>> You could write:
>>
>> func moles(particles: T)
>> -> T {
>>   let N_A = T("6.02214085774e+23")!
>>   return particles / N_A
>> }
>>
>
> …or I could write “T: FloatingPoint & ExpressibleByFloatLiteral”. I could
> even make a typealias for that. But I shouldn’t have to.
>
> Nevin
> ___
> 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] FloatingPoint does not conform to ExpressibleByFloatLiteral

2018-01-16 Thread Xiaodi Wu via swift-evolution
On Tue, Jan 16, 2018 at 6:20 PM, Nevin Brackett-Rozinsky <
nevin.brackettrozin...@gmail.com> wrote:

> On Tue, Jan 16, 2018 at 6:31 PM, Xiaodi Wu  wrote:
>
>> On Tue, Jan 16, 2018 at 4:30 PM, Nevin Brackett-Rozinsky <
>> nevin.brackettrozin...@gmail.com> wrote:
>>
>>> The thing that is “broken” here is generic programming. If I constrain
>>> something to FloatingPoint, I cannot use a float literal in calculations
>>> with it:
>>>
>>> func centimeters (inches: T) -> T {
>>>
>>> return 2.54 * inches// Error
>>>
>>> }
>>>
>>
>> Why not constrain it to `BinaryFloatingPoint`? What other types are you
>> trying to use with this function?
>>
>
> We should not ask nor expect people to constrain their generic algorithms
> to BinaryFloatingPoint unless they are working with the radix.
>

On the contrary, I think the "currency" floating-point protocol should be
`BinaryFloatingPoint`. Having worked with `FloatingPoint` rather
extensively (or, attempted to at least), I reiterate that I find it to be a
distinctly unhelpful protocol in terms of enabling useful generic
algorithms; if we were to do anything, I'd advocate for its complete
removal before ABI stability sets in. For compatibility we would supply a
deprecated `typealias FloatingPoint = BinaryFloatingPoint`.



>
>> so that eg. a Rational type could be used. And that gives a hint as to
>>> the workaround:
>>>
>>> func centimeters (inches: T) -> T {
>>>
>>> return (254 / 100) * inches
>>>
>>> }
>>>
>>
>> Yes, you *could* do that.
>>
>
> And it seems I *will* be doing that, as long as such a workaround is
> necessary. Though it does appear to have the unfortunate cost of an extra
> division operation.
>

There should be no runtime cost when specialized.


That only works for numbers which don’t overflow the integer literals
>>> though.
>>>
>>
>> Integer literals don't overflow until 2048 bits. The following compiles
>> just fine:
>>
>> func moles(particles: T) -> T {
>>   let N_A: T = 602_214_085_774_000_000_000_000
>>   return particles / N_A
>> }
>>
>
> When I write that in a playground it shows N_A as 1.67866967797794e+18.
>
> (Also, you appear to have mistakenly concatenated the standard uncertainty
> in the last 2 digits, “74”, onto the accepted value for the constant.)
>

Yes, those are typos; I was typing freehand into an email. Please adjust
the number and value of digits as necessary.



> If we want a really large or small value then we have to split it in
>>> pieces:
>>>
>>> func moles  (particles: T) -> T {
>>>
>>> let avogadroNumber: T = 6_022_140_857 * 100_000_000_000_000
>>>
>>> return particles / avogadroNumber
>>>
>>> }
>>>
>>> It would be much nicer to write “let avogadroNumber: T = 6.022140857e23”.
>>>
>>
>> You could write:
>>
>> func moles(particles: T)
>> -> T {
>>   let N_A = T("6.02214085774e+23")!
>>   return particles / N_A
>> }
>>
>
> …or I could write “T: FloatingPoint & ExpressibleByFloatLiteral”. I could
> even make a typealias for that. But I shouldn’t have to.
>

Sure, you could do that too. Your solution here is actually probably the
best, in that if a user wishes to conform a decimal type
to ExpressibleByFloatLiteral, your extensions would also work for that
type. I've already explained why the semantics of ExpressibleByFloatLiteral
are such that not every FloatingPoint type could conform.
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] FloatingPoint does not conform to ExpressibleByFloatLiteral

2018-01-16 Thread Xiaodi Wu via swift-evolution
On Tue, Jan 16, 2018 at 4:30 PM, Nevin Brackett-Rozinsky <
nevin.brackettrozin...@gmail.com> wrote:

> The thing that is “broken” here is generic programming. If I constrain
> something to FloatingPoint, I cannot use a float literal in calculations
> with it:
>
> func centimeters (inches: T) -> T {
>
> return 2.54 * inches// Error
>
> }
>

Why not constrain it to `BinaryFloatingPoint`? What other types are you
trying to use with this function?


Of course, “T: FloatingPoint” is an overconstraint in this example, as what
> I actually want is “T: OrderedField”
>

This approach was considered during revision of integer protocols and
rejected. You could make your own protocol to which your types of interest
then conform, if you're so interested.


so that eg. a Rational type could be used. And that gives a hint as to the
> workaround:
>
> func centimeters (inches: T) -> T {
>
> return (254 / 100) * inches
>
> }
>

Yes, you *could* do that.


That only works for numbers which don’t overflow the integer literals
> though.
>

Integer literals don't overflow until 2048 bits. The following compiles
just fine:

func moles(particles: T) -> T {
  let N_A: T = 602_214_085_774_000_000_000_000
  return particles / N_A
}


If we want a really large or small value then we have to split it in pieces:
>
> func moles  (particles: T) -> T {
>
> let avogadroNumber: T = 6_022_140_857 * 100_000_000_000_000
>
> return particles / avogadroNumber
>
> }
>
> It would be much nicer to write “let avogadroNumber: T = 6.022140857e23”.
>

You could write:

func moles(particles: T) ->
T {
  let N_A = T("6.02214085774e+23")!
  return particles / N_A
}


On Tue, Jan 16, 2018 at 3:39 PM, Chris Lattner <clatt...@nondot.org> wrote:
>
>> On Jan 15, 2018, at 11:01 PM, Xiaodi Wu via swift-evolution <
>> swift-evolution@swift.org> wrote:
>> > - Can we change the semantics? Maybe, but I doubt
>> ExpressibleByFloatLiteral can be outright replaced. You're not the first to
>> wonder about how to design an alternative protocol. Dig through the
>> archives and you'll find some existing ideas. My two cents: The main
>> alternative base in question here is 10. However, decimal storage formats
>> and binary storage formats share so little in common that any initializer
>> common to both will be extremely unwieldy for one or both formats.
>> Personally, somewhere down the road, I'd rather see Decimal64/128 become
>> standard library types (already working on it), DecimalFloatingPoint become
>> a standard library protocol, and `0.1` become a "decimal literal" (with
>> Float, Double, Float80, and Decimal64/128 all conforming) as distinct from
>> a "float literal" that we could then restrict to hexadecimal (?and binary)
>> floating-point literals (and maybe rename accordingly).
>>
>> If we were motivated to fix this (and I’m not :-), then I think the best
>> path forward would be to rename ExpressibleByFloatLiteral to something like
>> ExpressibleByBinaryFloatLiteral.  This would allow the introduction of a
>> new ExpressibleByDecimalFloatLiteral with a different initializer
>> requirement.
>>
>> I’m not motivated to fix this, because there is nothing actively broken
>> by the current state of things.  With the current name we can still
>> introduce a ExpressibleByDecimalFloatLiteral someday in the future.  The
>> two names will be a little odd, but given the cost of changing it at this
>> point, that seems perfectly acceptable.
>>
>> -Chris
>
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] FloatingPoint does not conform to ExpressibleByFloatLiteral

2018-01-15 Thread Xiaodi Wu via swift-evolution
On Tue, Jan 16, 2018 at 00:32 Nevin Brackett-Rozinsky <
nevin.brackettrozin...@gmail.com> wrote:

> On Mon, Jan 15, 2018 at 11:27 PM, Xiaodi Wu  wrote:
>
>> On Mon, Jan 15, 2018 at 20:37 Nevin Brackett-Rozinsky <
>> nevin.brackettrozin...@gmail.com> wrote:
>>
>>>
>>> That protocol is spelled ExpressibleByFloatLiteral, which reflects the
>>> meaning that we want and should have. The name is correct, the problem is
>>> with the implementation.
>>>
>>
>> I get that you want float literals to have semantics other than what they
>> have. Again, that's a different conversation.
>>
>
> It is the exact conversation I started this thread to have, so if there is
> any other conversation going on here then *that* is the different one. :-)
>

There are two distinct questions here:

- Your original questions to the list. Rephrased: Is it an implementation
bug that FloatingPoint does not refine ExpressibleByFloatLiteral? Can
FloatingPoint, with its current semantics, refine
ExpressibleByFloatLiteral, with its current semantics? The answer is: no
and no.

- Can we change the semantics? Maybe, but I doubt ExpressibleByFloatLiteral
can be outright replaced. You're not the first to wonder about how to
design an alternative protocol. Dig through the archives and you'll find
some existing ideas. My two cents: The main alternative base in question
here is 10. However, decimal storage formats and binary storage formats
share so little in common that any initializer common to both will be
extremely unwieldy for one or both formats. Personally, somewhere down the
road, I'd rather see Decimal64/128 become standard library types (already
working on it), DecimalFloatingPoint become a standard library protocol,
and `0.1` become a "decimal literal" (with Float, Double, Float80, and
Decimal64/128 all conforming) as distinct from a "float literal" that we
could then restrict to hexadecimal (?and binary) floating-point literals
(and maybe rename accordingly).
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] FloatingPoint does not conform to ExpressibleByFloatLiteral

2018-01-15 Thread Xiaodi Wu via swift-evolution
On Mon, Jan 15, 2018 at 20:37 Nevin Brackett-Rozinsky <
nevin.brackettrozin...@gmail.com> wrote:

> On Mon, Jan 15, 2018 at 8:51 PM, Xiaodi Wu  wrote:
>
>> On Mon, Jan 15, 2018 at 19:20 Nevin Brackett-Rozinsky <
>> nevin.brackettrozin...@gmail.com> wrote:
>>
>>> All I’m saying is the current situation seems semantically wrong. As in,
>>> how can a type claim to be a floating point number, if it *literally*
>>> cannot be represented by a floating point number?
>>>
>>
>> Again, you can think of it that way, but what I’m saying is that
>> “FloatLiteral” is a misnomer: semantically, a conforming type is
>> specifically claiming that it is expressible by a _binary_ floating point
>> number.
>>
>
>  I strongly disagree. To say that it is a “misnomer” implies that the
> semantics are correct and the problem is with the name.
>
> However, in Swift a floating point literal consists of certain patterns of
> characters in source code, as specified by the language grammar. Thus it is
> meaningful and correct to say that certain types can be expressed as
> floating point literals. We have a protocol for exactly that purpose: to
> indicate that conforming types can be written as floating point literals.
>

I understand that you disagree with the current semantics, but they aren't
arbitrary. You know, I’m sure, that we can write integer literals in any of
several bases. For example, `0x` is an integer literal which represents
the same value as `65535`:

  0x == 65535 // true

It doesn’t matter in which base you write the literal, it represents some
particular _binary integer_ up to a maximum of 2048 (binary) digits.

Likewise, we can write floating-point literals in any of several bases. For
example:

  0x1.5bf0a8b145769p1 == 2.7182818284590451 // true

It doesn't matter in which base you write the literal, it represents some
particular _binary floating-point value_ up to a maximum of 63 or 52
fractional bits, depending on the platform.

That protocol is spelled ExpressibleByFloatLiteral, which reflects the
> meaning that we want and should have. The name is correct, the problem is
> with the implementation.
>

I get that you want float literals to have semantics other than what they
have. Again, that's a different conversation. I'm simply explaining that
the current semantics are not by accident, and that the implementation
isn't a buggy execution of the semantics you think they should have, but an
exact execution of semantics you may not agree with but nonetheless
deliberately chosen.

If you want to argue that, after we fix the buggy implementation of
> ExpressibleByFloatLiteral, then we should introduce a new protocol named
> ExpressibleByBinaryFloatLiteral, that might be a discussion worth having.
> But for the existing protocol, renaming it would not solve the underlying
> issue.
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] FloatingPoint does not conform to ExpressibleByFloatLiteral

2018-01-15 Thread Xiaodi Wu via swift-evolution
On Mon, Jan 15, 2018 at 19:20 Nevin Brackett-Rozinsky <
nevin.brackettrozin...@gmail.com> wrote:

> All I’m saying is the current situation seems semantically wrong. As in,
> how can a type claim to be a floating point number, if it *literally*
> cannot be represented by a floating point number?
>

Again, you can think of it that way, but what I’m saying is that
“FloatLiteral” is a misnomer: semantically, a conforming type is
specifically claiming that it is expressible by a _binary_ floating point
number.

You suggest treating a float literal as a string, but another alternative
> is to teach the compiler to handle arbitrary-length integer literals, and
> then treat a float literal as two integer literals separated by a dot.
>

You *could*, but the fractional part is encoded quite differently from the
integral part in a binary floating point value, so that would require an
inelegant conversion.

More elegantly, you could represent the literal as a fraction, where the
denominator is given as a power of the radix. There are many ways to slice
it but this is getting far afield of your original question, which is,
essentially, that given the semantics of the two protocols it’s not correct
to conform FloatingPoint to ExpressibleByFloatLiteral, and not an oversight.

In any case, is this something that would have to be done before ABI
> stability, or could it wait until after?
>

I don’t think the current protocol can go away, so any additions or
enhancements are something that can wait.

Nevin
>
>
> On Mon, Jan 15, 2018 at 7:41 PM, Xiaodi Wu  wrote:
>
>> On Mon, Jan 15, 2018 at 4:24 PM, Nevin Brackett-Rozinsky via
>> swift-evolution  wrote:
>>
>>> Currently, the FloatingPoint protocol does not conform to
>>> ExpressibleByFloatLiteral, whereas BinaryFloatingPoint does.
>>>
>>> The only explanation I can find for this is a brief comment from Steve
>>> Canon
>>> 
>>> during the review of SE-0067 (Enhanced Floating Point Protocols)
>>> 
>>> :
>>>
>>>
>>> On Mon, Apr 25, 2016 at 1:32 PM, Stephen Canon via swift-evolution
  wrote:

 On Apr 23, 2016, at 8:53 PM, Brent Royal-Gordon via swift-evolution
>  wrote:
>
> Any reason why FloatLiteralConvertible isn't on FloatingPoint?


 It doesn’t make sense for non-radix-2 types; you would change bases
 multiple times.
>>>
>>>
>>>
>>> I don’t have Steve’s level of floating-point expertise, but from a
>>> conceptual standpoint Swift protocols encapsulate semantics and, unless I
>>> am quite mistaken, semantically a floating-point number *can* be expressed
>>> as a floating-point literal.
>>>
>>> So, what exactly is the problem preventing such a conformance, and what
>>> would be required to fix it? Do we need to revamp how numeric literals are
>>> handled, eg. to allow arbitrary-precision integers and base-agnostic floats?
>>>
>>
>> Note that there are no types that ship with Swift itself that conform to
>> FloatingPoint but not BinaryFloatingPoint (Foundation.Decimal does not
>> conform to FloatingPoint, and cannot do so without some major
>> backwards-incompatible surgery because of how it handles subnormals,
>> infinity, NaN, and a host of other issues), so this discussion does not
>> affect most (any?) end users.
>>
>>
>> The name ExpressibleByFloatLiteral is kind of a misnomer. To conform, a
>> type must be able to convert a value from some other type that conforms to
>> _ExpressibleByBuiltinFloatLiteral, which is to say a _binary_
>> floating-point type.
>>
>> If you create a Decimal type, it *could try to conform* to
>> ExpressibleByFloatLiteral, but given `var x: Double = 0.1`, the value would
>> actually be something like 0.10001, not exactly 0.1, because
>> it'd be the decimal approximation of a _binary_ approximation to the
>> literal. This is what Steve means by "you would change bases multiple
>> times," and the result is unintuitive. The alternative is to try to convert
>> to a decimal value via the _string representation_ of the _binary
>> approximation_ to the literal, which would let you recover `0.1` but lose
>> all information as to significant digits in the original literal (i.e.,
>> "0.1" vs. "0.100"), an important piece of information for Decimal types.
>>
>> In other words, given the actual design of ExpressibleByFloatLiteral, it
>> doesn't entirely make sense for non-binary floating-point types to conform.
>>
>>
>> Yes, we can try to perform major surgery on the floating-point literal
>> protocol, or add another one, so that it's possible for non-binary types to
>> conform, and there have been proposals on this list along those lines. It
>> would appear to me that any such design would necessarily be more complex
>> and possibly slower than the existing design; at its 

Re: [swift-evolution] FloatingPoint does not conform to ExpressibleByFloatLiteral

2018-01-15 Thread Xiaodi Wu via swift-evolution
On Mon, Jan 15, 2018 at 4:24 PM, Nevin Brackett-Rozinsky via
swift-evolution  wrote:

> Currently, the FloatingPoint protocol does not conform to
> ExpressibleByFloatLiteral, whereas BinaryFloatingPoint does.
>
> The only explanation I can find for this is a brief comment from Steve
> Canon
> 
> during the review of SE-0067 (Enhanced Floating Point Protocols)
> 
> :
>
>
> On Mon, Apr 25, 2016 at 1:32 PM, Stephen Canon via swift-evolution
>>  wrote:
>>
>> On Apr 23, 2016, at 8:53 PM, Brent Royal-Gordon via swift-evolution
>>>  wrote:
>>>
>>> Any reason why FloatLiteralConvertible isn't on FloatingPoint?
>>
>>
>> It doesn’t make sense for non-radix-2 types; you would change bases
>> multiple times.
>
>
>
> I don’t have Steve’s level of floating-point expertise, but from a
> conceptual standpoint Swift protocols encapsulate semantics and, unless I
> am quite mistaken, semantically a floating-point number *can* be expressed
> as a floating-point literal.
>
> So, what exactly is the problem preventing such a conformance, and what
> would be required to fix it? Do we need to revamp how numeric literals are
> handled, eg. to allow arbitrary-precision integers and base-agnostic floats?
>

Note that there are no types that ship with Swift itself that conform to
FloatingPoint but not BinaryFloatingPoint (Foundation.Decimal does not
conform to FloatingPoint, and cannot do so without some major
backwards-incompatible surgery because of how it handles subnormals,
infinity, NaN, and a host of other issues), so this discussion does not
affect most (any?) end users.


The name ExpressibleByFloatLiteral is kind of a misnomer. To conform, a
type must be able to convert a value from some other type that conforms to
_ExpressibleByBuiltinFloatLiteral, which is to say a _binary_
floating-point type.

If you create a Decimal type, it *could try to conform* to
ExpressibleByFloatLiteral, but given `var x: Double = 0.1`, the value would
actually be something like 0.10001, not exactly 0.1, because
it'd be the decimal approximation of a _binary_ approximation to the
literal. This is what Steve means by "you would change bases multiple
times," and the result is unintuitive. The alternative is to try to convert
to a decimal value via the _string representation_ of the _binary
approximation_ to the literal, which would let you recover `0.1` but lose
all information as to significant digits in the original literal (i.e.,
"0.1" vs. "0.100"), an important piece of information for Decimal types.

In other words, given the actual design of ExpressibleByFloatLiteral, it
doesn't entirely make sense for non-binary floating-point types to conform.


Yes, we can try to perform major surgery on the floating-point literal
protocol, or add another one, so that it's possible for non-binary types to
conform, and there have been proposals on this list along those lines. It
would appear to me that any such design would necessarily be more complex
and possibly slower than the existing design; at its simplest, it could
involve representing the literal as a string, which almost all types,
whether Decimal or BigInt, would expected to be able to parse anyway. But
that's a much larger discussion for another day. The answer to your
question as to why `FloatingPoint` does not refine
`ExpressibleByFloatLiteral` is as shown above; tl;dr: it doesn't make sense
to do so.
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


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

2018-01-13 Thread Xiaodi Wu via swift-evolution
On Sat, Jan 13, 2018 at 10:29 PM, Erica Sadun via swift-evolution <
swift-evolution@swift.org> wrote:

> I think a full random implementation should be decoupled from Swift's
> standard library and generic random is overkill.
>
> In-language, I think pre-seeded random uniform (0 ..< 1,
> `Double.uniformRandom()`), random int (0 ..< max, `Int.uniform(max)`), and
> random index for indexed collection (`collection.randomIndex()`) is more
> than sufficient, assuming sufficient doc warnings that none of this is
> suitable for encryption or gambling.
>

Agree almost entirely, with the modification that if we limit ourselves to
these APIs it should be possible to implement in such a way that
suitability for encryption or gambling can be assured, which would be a
nice bonus but not a must-have.


> -- E
>
> On Jan 13, 2018, at 6:48 PM, Jonathan Hull via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> Basically, my point is that I want to be able to operate generically.
>
> On Jan 13, 2018, at 5:20 AM, Letanyan Arumugam 
> wrote:
>
>
> On 13 Jan 2018, at 02:24, Jonathan Hull  wrote:
>
> I think we have different definitions of consistency.  I am fine with the
> ergonomics of (0…100).random() as a convenience, but it really worries me
> here that everything is special cased.  Special cased things are fine for
> individual projects, but not the standard library.  We should make sure
> that the design is flexible and extensible, and that comes in part from
> having a consistent interface.
>
>
> I think we just want different consistencies. Mine is that I want the same
> mental model of having to get a random value from some explicit
> ’set’/’space’.
>
> Also, as I said before, we really shouldn’t be doing these crazy
> contortions to avoid ‘random() % 100’.  Instead we should look for that
> pattern and issue with a warning + fixit to change it to random(in:).  I
> think that will be much more effective in actually changing the behavior in
> the long run.
>
> Finally, tying everything to Range is extremely limiting.  I understand if
> we don’t want to add other types to the standard library, but I should be
> able to build on what we add to do it myself without having to reinvent the
> wheel for each type.  It is important to have a consistent story for these
> things (including multi-dimensional types) so that they can interoperate.
>
>
> As a stated above I don’t think of it as being tied to a range, but rather
> a set of possible values. If you want to have multi-dimensional generators,
> could you not add an extension on an array to generate a value treating the
> array's elements as constraints?
>
> Using CGPoint as an example with Nate’s api design of random.
>
> public enum ConstraintKind {
> case constant(T)
> case range(T, T)
> case custom((RandomNumberGenerator) -> T)
> }
>
> public enum PointConstraint {
> case x(ConstraintKind)
> case y(ConstraintKind)
> }
>
> extension Array where Element == PointConstraint {
> func random(from constraintKind: ConstraintKind,
> using generator: RandomNumberGenerator = Random.default
> ) -> CGFloat {
> switch constraintKind {
> case let .constant(a): return a
> case let .range(min, max): return (min...max).random(using: generator)
> case let .custom(f): return f(generator)
> }
> }
>
> public func createRandom(using generator: RandomNumberGenerator = Random.
> default) -> CGPoint {
> var x: CGFloat? = nil
> var y: CGFloat? = nil
>
> for constraint in self {
> switch constraint {
> case let .x(c): x = random(from: c, using: generator)
> case let .y(c): y = random(from: c, using: generator)
> }
> }
>
> return CGPoint(x: x ?? 0.0, y: y ?? 0.0)
> }
> }
>
> let pointSpace: [PointConstraint] = [
> .x(.range(2, 32.5)),
> .y(.constant(4))
> ]
>
> pointSpace.createRandom()
>
>
>
> This uses the idea that constraints create a space of possible CGPoint
> values that createRandom 'gets' from.
>
>
> You could make array conform to some ConstraintRandom protocol when we get
> conditional conformance.
>
> We really should be looking at GamePlayKit more for design inspiration.
> There are several use-cases there that are being blatantly ignored in this
> discussion.  For example, what if I want to randomly generate a game world
> (e.g. The square from The Battle For Polytopia” formerly “SuperTribes”)?
> Or what if I want an effect where it randomly fades in letters from a
> String.  (…).random() will be completely inadequate for these things.
>
> Thanks,
> Jon
>
>
>
> On Jan 12, 2018, at 5:11 AM, Letanyan Arumugam 
> wrote:
>
> Nate’s design follows a consistent idea of getting a random value from
> some set of values. Adding the static method random() to a type essentially
> creates an implicit set which you yourself said leads to inconsistency
> (Double/Int). Secondly I don’t see why random(in:) should be added when it
> is just a different spelling for what is already provided. If my second
> statement is incorrect 

Re: [swift-evolution] [Pitch] Percentage Type

2018-01-13 Thread Xiaodi Wu via swift-evolution
As Erica mentioned about Angle, this seems to be a perfect fit for an
appropriately focused third-party library, but I'm not sure I appreciate
why this should be part of the standard library. In large part, you seem to
have reinvented a decimal type, which is already available in the form of
Foundation.Decimal on all supported platforms.

On Sat, Jan 13, 2018 at 9:07 PM, Jonathan Hull via swift-evolution <
swift-evolution@swift.org> wrote:

> Here is the code I use for percentage myself. (I incorrectly said I use a
> UInt64… I use a UInt32):
>
> ///Represents a percentage with the precision of millionths of 1 (i.e. 4
> decimal places: XX.%). The value is always positive (or zero), but may
> be greater than 100%
> struct Percentage {
> fileprivate(set) var millionths:UInt32
>
>
> fileprivate init(storage:UInt32){
> millionths = storage
> }
>
>
> static var quarter = Percentage(storage: 250_000)
> static var half= Percentage(storage: 500_000)
> static var threeQuarters = Percentage(storage: 750_000)
> static var full= Percentage(storage: 1_000_000)
>
>
> init(millionths:Int) {
> self.millionths = UInt32(millionths)
> }
>
>
> init(_ double:Double, range:ClosedRange = 0...1) {
> if range == 0...1 {
> self.millionths = UInt32(max(double * 1_000_000, 0))
> }else if range == 0...100{
> self.millionths = UInt32(max(double * 10_000, 0))
> }else{
> self.millionths = UInt32(max((double - range.lowerBound
> )/(range.upperBound - range.lowerBound),0))
> }
> }
>
>
> init(_ num:Num, range:ClosedRange = 0...1) {
> if range == 0...1 {
> self.millionths = UInt32(max(num * 1_000_000, 0).integerValue)
> }else if range == 0...100{
> self.millionths = UInt32(max(num * 10_000, 0).integerValue)
> }else{
> self.millionths = UInt32(max((num - range.lowerBound)/(range.
> upperBound - range.lowerBound),0).integerValue)
> }
> }
>
>
> init(_ decimal:Decimal, range:ClosedRange = 0...1) {
> if range == 0...1 {
> self.millionths = NSDecimalNumber(decimal: max(decimal *
> 1_000_000, 0)).uint32Value
> }else if range == 0...100{
> self.millionths = NSDecimalNumber(decimal: max(decimal *
> 10_000, 0)).uint32Value
> }else{
> let shifted = max((decimal - range.lowerBound)/(range.upper
> Bound - range.lowerBound),0)
> self.millionths = NSDecimalNumber(decimal: shifted).
> uint32Value
> }
> }
>
>
> init(hundredths:Int) {
> self.millionths = UInt32(max(hundredths * 10_000, 0))
> }
>
> init(thousandths:Int) {
> self.millionths = UInt32(max(thousandths * 1_000, 0))
> }
>
>
> var isFull:Bool {
> return self.millionths >= 1_000_000
> }
>
>
> var doubleValue:Double{
> return Double(self.millionths)/1_000_000
> }
>
>
> var cgfloatValue:CGFloat{
> return CGFloat(self.millionths)/1_000_000
> }
>
>
> var decimalValue:Decimal {
> return Decimal(self.millionths)/1_000_000
> }
>
>
> var numValue:Num {
> return Num(numerator: Int32(self.millionths), denominator:
> 1_000_000)
> }
>
>
> var hundredths:Int {
> return Int(self.millionths/10_000)
> }
>
>
> var thousandths:Int {
> return Int(self.millionths/1_000)
> }
>
>
> var tenThousandths:Int {
> return Int(self.millionths/100)
> }
>
>
> func map(to range:ClosedRange) -> Num {
> return self.numValue * (range.upperBound - range.lowerBound) +
> range.lowerBound
> }
>
>
> mutating func clip() {
> if self.millionths > 1_000_000 {
> self.millionths = 1_000_000
> }
> }
>
>
> func clipped()->Percentage {
> if self.millionths > 1_000_000 {
> return Percentage.full
> }
> return self
> }
>
>
>
>
> }
>
> extension Percentage:CustomStringConvertible {
> var description: String {
> let num = self.numValue * 100
> if num.isInteger{
> return "\(num)%"
> }
> return "\(num.decimalValue)%"
> }
> }
>
> extension Percentage:ExpressibleByIntegerLiteral {
> init(integerLiteral value: IntegerLiteralType) {
> self.millionths = UInt32(max(value * 10_000, 0))
> }
> }
>
> extension Percentage:Hashable {
> var hashValue: Int {
> return self.millionths.hashValue
> }
>
>
> static func == (lhs:Percentage, rhs:Percentage)->Bool {
> return lhs.millionths == rhs.millionths
> }
> }
>
> extension Percentage:Comparable {
> static func < (lhs:Percentage, rhs:Percentage) -> Bool {
> return lhs.millionths < rhs.millionths
> }
> }
>
> extension Percentage {
> static func + (lhs:Percentage, rhs:Percentage)->Percentage {
> return Percentage(storage: lhs.millionths + 

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

2018-01-13 Thread Xiaodi Wu via swift-evolution
On Fri, Jan 12, 2018 at 10:23 PM, Nate Cook via swift-evolution <
swift-evolution@swift.org> wrote:

> On Jan 12, 2018, at 6:24 PM, Jonathan Hull via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> I think we have different definitions of consistency.  I am fine with the
> ergonomics of (0…100).random() as a convenience, but it really worries me
> here that everything is special cased.  Special cased things are fine for
> individual projects, but not the standard library.  We should make sure
> that the design is flexible and extensible, and that comes in part from
> having a consistent interface.
>
> Also, as I said before, we really shouldn’t be doing these crazy
> contortions to avoid ‘random() % 100’.  Instead we should look for that
> pattern and issue with a warning + fixit to change it to random(in:).  I
> think that will be much more effective in actually changing the behavior in
> the long run.
>
>
> I’m not sure what contortions you’re describing—from what I’ve seen, the
> proposal author is going to revise the proposal to have these ways of
> generating individual values:
>
> In extensions to FixedWidthInteger and BinaryFloatingPoint:
> static func random(in: Range/ClosedRange, using:
> RandomNumberGenerator) -> Self
>
> In an extension to Bool:
> static func random(using: RandomNumberGenerator) -> Self
>

I neglected to comment initially, but this particular extension on Bool
doesn't hold its own weight.

If the desire is for a fair coin, it would be a synonym for a one-liner
that's exquisitely readable: `Double.random(in: 0..<1) < 0.5`.

But of course there will be interest for biased coins, for which an
additional API would be needed, the spelling of which is (a) not easy to
get right and (b) never going to be more readable than the alternative.
Observe how, given `Double.random(in: 0..<1) < 0.25`, it is instantly
obvious the likelihood of `true` vs. `false`.

Put another way, `Bool.random` is not a primitive and doesn't need to be a
standard library API.


>
> If someone still needs a full-width random value as a building-block for
> generating random instances of other types, they should use the `next()`
> method directly on a RandomNumberGenerator. In the example code you sent,
> you could switch to using a RandomNumberGenerator instead of your
> RandomSourceValue, or base your RandomSourceValue generation on a
> RandomNumberGenerator instead of whatever random generator you’re using now.
>
> Finally, tying everything to Range is extremely limiting.  I understand if
> we don’t want to add other types to the standard library, but I should be
> able to build on what we add to do it myself without having to reinvent the
> wheel for each type.  It is important to have a consistent story for these
> things (including multi-dimensional types) so that they can interoperate.
>
>
> We really should be looking at GamePlayKit more for design inspiration.
> There are several use-cases there that are being blatantly ignored in this
> discussion.  For example, what if I want to randomly generate a game world
> (e.g. The square from The Battle For Polytopia” formerly “SuperTribes”)?
> Or what if I want an effect where it randomly fades in letters from a
> String.  (…).random() will be completely inadequate for these things.
>
>
> The goal at this point is to build into the standard library the basis for
> all kinds of other use cases. Your library is one such example of something
> that can be built on top of the protocol and methods that are being
> proposed, as are a variety of other tasks, as I tried to show in the
> playground.
>
> What’s being proposed now is deliberately short of solving every need—the
> additions would handle the hard stuff (correct and safe generation of
> integers and floating-points, along with shuffling collections) and lay the
> groundwork for other libraries to take things farther (by establishing the
> RandomNumberGenerator, a default generator, and a pattern for their use).
>
> Speaking of GameplayKit, you can make GKRandomSource conform to
> RandomNumberGenerator in an extension, making all the GK... sources
> generators. If you’re already depending on those random sources, you’d
> still have access to them with the proposed model.
>
> Nate
>
> Thanks,
> Jon
>
>
>
> On Jan 12, 2018, at 5:11 AM, Letanyan Arumugam 
> wrote:
>
> Nate’s design follows a consistent idea of getting a random value from
> some set of values. Adding the static method random() to a type essentially
> creates an implicit set which you yourself said leads to inconsistency
> (Double/Int). Secondly I don’t see why random(in:) should be added when it
> is just a different spelling for what is already provided. If my second
> statement is incorrect and there’s something I’m missing please correct me?
>
> I think that consistency outweighs the random trapping inconsistency,
> however I would actually be fine if random returned an optional. Though the
> way random is used 

Re: [swift-evolution] [Review] SE-0194: Derived Collection of Enum Cases

2018-01-13 Thread Xiaodi Wu via swift-evolution
On Wed, Jan 10, 2018 at 5:06 AM, Brent Royal-Gordon <br...@architechies.com>
wrote:

> On Jan 9, 2018, at 10:26 PM, Xiaodi Wu via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> I continue to have concerns about this proposal, and I'm gravely and very
> bitterly disappointed that the concerns have not even been acknowledged in
> the Alternatives section, which is in my view the minimum action that an
> author should take when points are raised during a pitch phase, even (and
> especially) when the author disagrees, along with a cogent write-up of why
> the proposed design is superior in the author's view to the alternative. In
> this case, the proposal authors write:
>
>   "The community has not raised any solutions whose APIs differ
> significantly from this proposal, except for solutions which provide
> strictly more functionality."
>
> This is false, as I have offered a solution in the past whose API differs
> entirely from this proposal, and which provides strictly a subset of the
> functionality which goes to the core of the issue at stake.
>
>
> I can't speak for the other co-authors, but for my part, this was an
> oversight and I apologize for it. I think we should have discussed your
> `MyType.self` alternative.
>
> I won't rehash the entire discussion in previous threads, but to summarize
> my objections:
>

Again, I do appreciate the detailed reply. Time is never enough, so I'll
try to be both concise and complete in my reply. Hopefully, it'll live up
to your example in terms of thoroughness.


> 1. `MyType.self` is harder to understand for someone who's never seen it
> than `MyType.allValues`. For instance, the expression
> `AccountStatus.allValues[0]` is completely self-explanatory, while
> `AccountStatus.self[0]` is more obscure and would require a trip to the
> documentation. (And since `self` here is a language keyword, not a real
> member, the most obvious route to the documentation is not available.) In
> my opinion, we should not prefer the `MyType.self` syntax.
>
> 2. Even if the community disagrees with me and thinks `MyType.self` is a
> better syntax than `MyType.allValues`, it is not better *enough* to
> outweigh the costs:
>
> • The metatype solution provides no additional functionality; it is merely
> a matter of which syntax we choose to support, and how much effort this
> support requires.
>
> • Conforming the metatype to `Collection` requires a lot of type system
> features we do not currently have. Currently, structural types cannot
> conform to protocols, and metatypes are a structural type. Metatypes also
> cannot have subscripts currently. Your proposed design has a lot of
> prerequisites. That is not in and of itself disqualifying, but it should be
> weighed against it.
>
> • You suggest that we should add bits and pieces of "`Collection`
> functionality" incrementally as engineering resources become available. The
> problem is that the most valuable part of the "`Collection` functionality"
> is conformance to `Collection` or at least `Sequence`, not the existence of
> any particular members of `Collection`, and this is the part that would
> require the most engineering resources.
>
> • A large part of the work we would do before supporting this conformance
> would be disposed of immediately once we could get it. For instance, all of
> the work to support having a metatype instead of a sequence in a `for-in`
> statement would be thrown away as soon as we could conform to `Sequence`.
> So this looks less like slowly building up pieces of the feature until we
> have all of them in place, and more like creating temporary hacks to
> emulate the feature until we have the time to do it right.
>
> • While this feature is not a showstopper, it is a highly desirable
> convenience. The proposal documents the high demand for this feature, so I
> won't elaborate on this point further.
>
> • Therefore, adopting this design would add a lot of engineering
> complexity before we could fully support a highly desirable feature, merely
> to get a syntax that we *might* prefer.
>
> To summarize the summary: The primary advantage of `MyType.self` is that
> it's elegant. To get that elegance, we must trade away getting a
> fully-functional implementation sooner, spending a lot of engineering
> resources (much of which would be wasted in the end), and—most crucially in
> my opinion—clarity at the point of use. It's not worth it.
>
>
Let me take two steps back, then address your points (1) and (2). One
overarching critique of mine is that you are conflating two (related)
features into one. The stated motivation is the desire to enumerate all the
cases of an enum (let's call this problem A). The present

Re: [swift-evolution] 100% bikeshed topic: DictionaryLiteral

2018-01-12 Thread Xiaodi Wu via swift-evolution
One point to bring up is that what you call libswiftCoreDeprecated.dylib
can be the place that future APIs live until they’re sufficiently mature.

I highly doubt that additions to the Swift standard library past 5.0 will
all be fully baked on arrival, and having everything carved into stone the
moment it’s added seems unwise.

Against this consideration the benefit of enabling a more stable set and a
less stable set of APIs seems to outweigh the start-up time consideration.
Yes, the implication is that most Swift apps will have to incur an
increased runtime cost.
On Fri, Jan 12, 2018 at 18:43 Ted Kremenek via swift-evolution <
swift-evolution@swift.org> wrote:

> Hi Chris,
>
> Instead of responding to each of your point bit-by-bit, I’ll try a
> different tactic to explain my reasoning — which may be wrong — by
> explaining how I see things top down with the tradeoffs they incur.  I’m
> going to say a bunch of things I know *you* know, but others are on this
> thread and I’ll state things for end-to-end clarity.
>
> It seems to me that we are talking about two possible scenarios: (1) the
> status quo of keeping everything in libswiftCore.dylib or (2) splitting
> libswiftCore.dylib into two dylibs, one which includes some of the
> “deprecated” APIs.  I’ll enumerate what I think are the tradeoffs/benefits
> we will see with both scenarios, and see where the mismatch in our “talking
> past each other” is happening.
>
> In both cases (A) and (B), with ABI stability the Standard Library has the
> option to ship in the OS.  Thus applications using Swift on (say) iOS would
> no longer need to include libswiftCore.dylib in the app when running on an
> OS that shipped with the Standard Library.
>
> With that in mind, here are the tradeoffs as I see between scenarios (A)
> and (B):
>
>
> (A) Status quo: Keep shipping everything in libswiftCore.dylib
>
> - Applications running on an OS with the Standard Library would no longer
> have *any* of the currently libswift*.dylib’s embedded inside the
> application bundle because they would just use the one in the OS.
>
> - One benefit of using libswift*.dylibs in the OS as opposed to those
> embedded inside the app bundle is that there is a non-neglible startup time
> improvement, as the code signing verification that happens when an app
> launches would be faster as it would not need to verify each of these
> dylibs that were previously embedded in the app.  We should consider this
> the new baseline for app startup time for an app running on an OS with an
> ABI stable Standard Library.
>
> - We continue to support the deprecated APIs for some time, possibly
> indefinitely, even when better alternatives come around.
>
> (B) Split libswiftCore.dylib into two dylibs, one that gets embedded in
> the app bundle
>
> In the second scenario, we split out the deprecated APIs into a separate
> dylib, say libswiftCoreDeprecated.dylib.  That solution would have the
> following characteristics:
>
> - Like scenario (A), app bundles would not need to embed
> libswiftCore.dylib when running on an OS that had an ABI-stable Standard
> Library.
>
> - Compared to scenario (A), the OS shipping the Standard Library would
> have a slightly smaller libswiftCore.dylib that didn’t carry the bits for
> the deprecated APIs.  This would be a benefit in the code size for the OS,
> but not for the app itself.
>
> - Any app using a deprecated API we put into libswiftCoreDeprecated.dylib
> (e.g., Mirrors) would need to embed libswiftCoreDeprecated.dylib inside
> their app bundle.  Compared to the new baseline I mentioned in (A), such
> apps would have a launch time regression once they started using any API in
> the libSwiftCoreDeprecated.dylib because code signing would need to verify
> the dylib, just like it does today with the libswiftCore.dylib that is
> embedded in every application.  They would also be slightly larger because
> the app bundle has the burden of hosting libswiftCoreDeprecated.dylib,
> instead of compared to scenario (A) where the implementations of the
> deprecated APIs are hosted by the libswiftCore.dylib that ships in the OS.
>
> - Because of binary compatibility concerns, after Swift 5 we would *never*
> be able to “take out” any further APIs from libswiftCore.dylib and put them
> in libswiftCoreDeprecated.dylib.  This factorization can only happen once.
>
> - There is some slight additional complexity added to the compiler and
> build system to support this spit of the Standard Library into multiple
> dylibs.  It’s not a huge concern but it does exist and it is not free both
> in terms of implementing and maintaining.
>
> - We continue to support the deprecated APIs for some time, possibly
> indefinitely, even when better alternatives come around.  We *may* be able
> to completely sunset these APIs by having a future version of the Swift
> compiler simply refuse to build projects that use the deprecated (now
> obsoleted) APIs.  At that point, these apps need to move to using 

Re: [swift-evolution] [pitch] adding toggle to Bool

2018-01-12 Thread Xiaodi Wu via swift-evolution
Agree: toggle makes the most sense to me as well.
On Fri, Jan 12, 2018 at 06:14 David Hart via swift-evolution <
swift-evolution@swift.org> wrote:

>
>
> On 12 Jan 2018, at 07:15, Chris Eidhof via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> Hey SE!
>
> When we have a bunch of nested structs:
>
> struct Sample {
> var bar: Bar
> }
>
> struct Bar {
> var show: Bool
> }
>
> var foo = Sample(bar: Bar(show: false))
>
> It can be repetitive to toggle a deeply nested boolean:
>
> foo.bar.show = !foo.bar.show // duplication
>
> I sometimes add a `toggle` extension on `Bool`
>
> extension Bool {
> mutating func toggle() {
> self = !self
> }
> }
>
> This allows you to write the same code without duplication, and makes the
> intent clearer:
>
> foo.bar.show.toggle()
>
> In other languages, I don't think the `toggle` would make as much sense,
> but the mutable self makes this very useful.
>
> After I posted it on Twitter, it turns out I'm not the only one:
> https://twitter.com/PublicExtension/status/730434956376346624
>
> I would have gone straight to a proposal, but I think we can do some
> bikeshedding about the name of `toggle`?
>
>
> Out of all the versions I heard, toggle is the one that makes the most
> sense to me.
>
> --
> Chris Eidhof
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


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

2018-01-11 Thread Xiaodi Wu via swift-evolution
ouble.random(), yet again suggest a shorthand that enables no additional
behavior in spite of the potential for misunderstanding. What advantage of
having such an API do you see which could overcome this very glaring
drawback?

This type of behavior is found in C, C++, C#, Java, etc. I agree with
> Jonathon in that maybe we could suggest a warning/fixit in Xcode.
>
> tl;dr - Remove `Randomizable`, remove associated type on
> `RandomNumberGenerator`, be consistent with `.random()` with other
> properties and functions with every collection, preserve static `random()`
> and `random(in:)` syntax.
>
> - Alejandro
>
> On Jan 8, 2018, 1:02 PM -0600, Nate Cook via swift-evolution <
> swift-evolution@swift.org>, wrote:
>
> I created a playground to explore this question, starting with a minimal
> subset of the proposal’s additions and building from there. The attached
> playground demonstrates what’s possible with this subset on the first page,
> then uses subsequent pages to explore how the main random facilities of the
> C++ STL work under this model. (In my opinion, they work pretty well!)
>
> The subset in the playground has three main differences from the proposal:
>  - It doesn't include a Randomizable protocol or a random property on
> numeric types.
>  - It doesn't include the static random(in:) methods on numeric types,
> either.
>  - The RandomNumberGenerator protocol doesn't have an associated type.
> Instead, it requires all conforming types to produce UInt64 values.
>
> I’ve tried to include a bit of real-world usage in the playground to
> demonstrate what writing code would look like with these additions. Please
> take a look!
>
> Nate
>
>
> On Dec 2, 2017, at 9:50 PM, Dave Abrahams via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> I don’t have much to say about this other than that I think the discussion
> seems way too narrow, focusing on spelling rather than on functionality and
> composability.  I consider the “generic random number library” design to be
> a mostly-solved problem, in the C++ standard library (
> http://en.cppreference.com/w/cpp/numeric/random).  Whatever goes into the
> Swift standard library does not need to have all those features right away,
> but should support being extended into something having the same general
> shape. IMO the right design strategy is to *implement and use* a Swift
> version of C++’s facilities and only then consider proposing [perhaps a
> subset of] that design for standardization in Swift.
>
> Sent from my iPad
>
> On Dec 2, 2017, at 5:12 PM, Kyle Murray via swift-evolution <
> swift-evolution@swift.org> wrote:
>
>
> On Dec 2, 2017, at 6:02 PM, Xiaodi Wu via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> Instead, we ought to make clear to users both the features and the
> limitations of this API, to encourage use where suitable and to discourage
> use where unsuitable.
>
>
> I like that you're considering the balance here. I've been lightly
> following this thread and want to add my thoughts on keeping crypto and
> pseudorandomness out of the name of at least one random API intended for
> general use.
>
> For someone who doesn't know or care about the subtleties of insecure or
> pseudorandom numbers, I'm not sure that the name insecureRandom is
> effectively much different than badRandom, at least in terms of the
> information it conveys to non-experts. To Greg's point, that's the opposite
> of the signal that the API name should suggest because it's what most
> people should use most of the time. As you say, this API is being designed
> for general use.
>
> There's a cost to adding extra complexity to names, too. I don't think
> it's far-fetched to suspect that people who find insecureRandom in an
> autocomplete listing or search will think "Where's the plain random
> function?"... and then go looking for a community extension that will
> inevitably provide a trivial alias: func random() { return
> insecureRandom() }. That's the sort of adoption I'd expect from something
> for new programmers, like Swift Playgrounds. Someone's introduction to
> randomness in programming should probably involve no more than a
> straightforward mapping from the elementary definition, rather than forcing
> a teaching moment from more advanced math.
>
> I think there are better places for caveat information than in the API
> names themselves; documentation being one clear destination. This is in
> contrast with Unsafe*Pointer, where the safety element is critical enough
> to be elevated to be more than caveat-level information. You can go really
> far and create really cool things before these caveats start to apply.
> Using randomness as a black box in an intr

Re: [swift-evolution] [Review] SE-0194: Derived Collection of Enum Cases

2018-01-10 Thread Xiaodi Wu via swift-evolution
On Wed, Jan 10, 2018 at 5:06 AM, Brent Royal-Gordon <br...@architechies.com>
wrote:

> On Jan 9, 2018, at 10:26 PM, Xiaodi Wu via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> I continue to have concerns about this proposal, and I'm gravely and very
> bitterly disappointed that the concerns have not even been acknowledged in
> the Alternatives section, which is in my view the minimum action that an
> author should take when points are raised during a pitch phase, even (and
> especially) when the author disagrees, along with a cogent write-up of why
> the proposed design is superior in the author's view to the alternative. In
> this case, the proposal authors write:
>
>   "The community has not raised any solutions whose APIs differ
> significantly from this proposal, except for solutions which provide
> strictly more functionality."
>
> This is false, as I have offered a solution in the past whose API differs
> entirely from this proposal, and which provides strictly a subset of the
> functionality which goes to the core of the issue at stake.
>
>
> I can't speak for the other co-authors, but for my part, this was an
> oversight and I apologize for it. I think we should have discussed your
> `MyType.self` alternative.
>
> I won't rehash the entire discussion in previous threads, but to summarize
> my objections:
>

I appreciate the detailed reply below. Time constraints prohibit an
immediate reply with the same level of thoroughness, but I look forward to
composing one within a few days' time. Bear with me.


> 1. `MyType.self` is harder to understand for someone who's never seen it
> than `MyType.allValues`. For instance, the expression
> `AccountStatus.allValues[0]` is completely self-explanatory, while
> `AccountStatus.self[0]` is more obscure and would require a trip to the
> documentation. (And since `self` here is a language keyword, not a real
> member, the most obvious route to the documentation is not available.) In
> my opinion, we should not prefer the `MyType.self` syntax.
>
> 2. Even if the community disagrees with me and thinks `MyType.self` is a
> better syntax than `MyType.allValues`, it is not better *enough* to
> outweigh the costs:
>
> • The metatype solution provides no additional functionality; it is merely
> a matter of which syntax we choose to support, and how much effort this
> support requires.
>
> • Conforming the metatype to `Collection` requires a lot of type system
> features we do not currently have. Currently, structural types cannot
> conform to protocols, and metatypes are a structural type. Metatypes also
> cannot have subscripts currently. Your proposed design has a lot of
> prerequisites. That is not in and of itself disqualifying, but it should be
> weighed against it.
>
> • You suggest that we should add bits and pieces of "`Collection`
> functionality" incrementally as engineering resources become available. The
> problem is that the most valuable part of the "`Collection` functionality"
> is conformance to `Collection` or at least `Sequence`, not the existence of
> any particular members of `Collection`, and this is the part that would
> require the most engineering resources.
>
> • A large part of the work we would do before supporting this conformance
> would be disposed of immediately once we could get it. For instance, all of
> the work to support having a metatype instead of a sequence in a `for-in`
> statement would be thrown away as soon as we could conform to `Sequence`.
> So this looks less like slowly building up pieces of the feature until we
> have all of them in place, and more like creating temporary hacks to
> emulate the feature until we have the time to do it right.
>
> • While this feature is not a showstopper, it is a highly desirable
> convenience. The proposal documents the high demand for this feature, so I
> won't elaborate on this point further.
>
> • Therefore, adopting this design would add a lot of engineering
> complexity before we could fully support a highly desirable feature, merely
> to get a syntax that we *might* prefer.
>
> To summarize the summary: The primary advantage of `MyType.self` is that
> it's elegant. To get that elegance, we must trade away getting a
> fully-functional implementation sooner, spending a lot of engineering
> resources (much of which would be wasted in the end), and—most crucially in
> my opinion—clarity at the point of use. It's not worth it.
>
> Earlier in this thread (or was it in the companion one?), another
> community member suggested that if `allValues` were to conform to
> `Sequence` instead of `Collection`, then even types that have an infinite
> number of possible values could conform to `ValueEn

Re: [swift-evolution] [Review] SE-0194: Derived Collection of Enum Cases

2018-01-09 Thread Xiaodi Wu via swift-evolution
On Mon, Jan 8, 2018 at 1:02 PM, Douglas Gregor via swift-evolution <
swift-evolution@swift.org> wrote:

> Hello Swift community,
>
> The review of SE-0194 "Derived Collection of Enum Cases" begins now and
> runs through January 11, 2018. The proposal is available here:
>
> https://github.com/apple/swift-evolution/blob/master/
> proposals/0194-derived-collection-of-enum-cases.md
>
> Reviews are an important part of the Swift evolution process. All reviews
> should be sent to the swift-evolution mailing list at
>
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
> or, if you would like to keep your feedback private, directly to the
> review manager. When replying, please try to keep the proposal link at the
> top of the message:
>
> Proposal link:
>
> https://github.com/apple/swift-evolution/blob/master/
> proposals/0194-derived-collection-of-enum-cases.md
>
> Reply text
>
> Other replies
>
>
> What
> goes into a review?
>
> The goal of the review process is to improve the proposal under review
> through constructive criticism and, eventually, determine the direction of
> Swift. When writing your review, here are some questions you might want to
> answer in your review:
>
>- What is your evaluation of the proposal?
>
> I continue to have concerns about this proposal, and I'm gravely and very
bitterly disappointed that the concerns have not even been acknowledged in
the Alternatives section, which is in my view the minimum action that an
author should take when points are raised during a pitch phase, even (and
especially) when the author disagrees, along with a cogent write-up of why
the proposed design is superior in the author's view to the alternative. In
this case, the proposal authors write:

  "The community has not raised any solutions whose APIs differ
significantly from this proposal, except for solutions which provide
strictly more functionality."

This is false, as I have offered a solution in the past whose API differs
entirely from this proposal, and which provides strictly a subset of the
functionality which goes to the core of the issue at stake.

In the past, I have stated on this list that once a statement has been
made, it should not be repeated simply because one is disappointed in the
outcome, as one should operate on the presumption that all actors proceed
in good faith and have already considered the statement. Here, however,
given that the write-up literally denies the existence of what I have
already written, I will restate my concerns here once again. I would expect
that on revision the authors will properly record a considered reply.

My objection to the "ValueEnumerable" design--especially in its generalized
form here (versus "CaseEnumerable")--is that the protocol's semantics (and,
we'll recall, protocols in Swift must offer semantics that make possible
useful generic algorithms) are so broad as to be little more than
essentially what it means to be a type.

Earlier in this thread (or was it in the companion one?), another community
member suggested that if `allValues` were to conform to `Sequence` instead
of `Collection`, then even types that have an infinite number of possible
values could conform to `ValueEnumerable`. Here's the rub: the definition
of a type, or at least one of them, _is_ precisely the set of all possible
values of a variable. If unconstrained by finiteness, then *all types*
would meet the semantic requirements of `ValueEnumerable`.

As proposed, "`ValueEnumerable`...indicate[s] that a type has a finite,
enumerable set of values"; now, we have the constraint that the type merely
must have an upper bound in terms of memory referenced. Brent just wrote
that he might later propose to extend `ValueEnumerable` to `Bool` and
`Optional`, but theoretically and practically speaking it appears that it
can correctly be extended to any type in the standard library that is not a
`Sequence`, and with minimal effort even `Collection` types of fixed size
(e.g., CollectionOfOne with the right constraints as to the generic type
T).

Put another way, there are two issues with generalizing the very specific
use case of "I want to know all the cases of an enum" to what is proposed
here in terms of a protocol. First, "ValueEnumerable"-ness is neither
universal to all enums (as those with associated types, indirect cases
(think of all those tutorials about linked lists implemented as Swift
enums), etc., are clearly not enumerable) nor unique as a property of
enums, yet this proposal first makes a large generalization of the proposed
protocol's semantics when the stated motivation is only about enums, then
proceeds only to implement protocol conformance for enums. Second, the
collection of all values is properly just the type and not a property of
the type, for the reasons outlined above.

So far, the justification I have heard for ignoring this objection is that
(a) lots of people want the 

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

2018-01-09 Thread Xiaodi Wu via swift-evolution
ut not all can be rewound or skipped ahead, so it’s something
where the ultimate hierarchy of protocols and their methods will depend on
the concrete types on offer.

- I really appreciate that you made a playground :-)
>
> Thanks,
> Jon
>
>
> On Jan 8, 2018, at 11:02 AM, Nate Cook via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> I created a playground to explore this question, starting with a minimal
> subset of the proposal’s additions and building from there. The attached
> playground demonstrates what’s possible with this subset on the first page,
> then uses subsequent pages to explore how the main random facilities of the
> C++ STL work under this model. (In my opinion, they work pretty well!)
>
> The subset in the playground has three main differences from the proposal:
>  - It doesn't include a Randomizable protocol or a random property on
> numeric types.
>  - It doesn't include the static random(in:) methods on numeric types,
> either.
>  - The RandomNumberGenerator protocol doesn't have an associated type.
> Instead, it requires all conforming types to produce UInt64 values.
>
> I’ve tried to include a bit of real-world usage in the playground to
> demonstrate what writing code would look like with these additions. Please
> take a look!
>
> Nate
>
> 
>
>
> On Dec 2, 2017, at 9:50 PM, Dave Abrahams via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> I don’t have much to say about this other than that I think the discussion
> seems way too narrow, focusing on spelling rather than on functionality and
> composability.  I consider the “generic random number library” design to be
> a mostly-solved problem, in the C++ standard library (
> http://en.cppreference.com/w/cpp/numeric/random).  Whatever goes into the
> Swift standard library does not need to have all those features right away,
> but should support being extended into something having the same general
> shape. IMO the right design strategy is to *implement and use* a Swift
> version of C++’s facilities and only then consider proposing [perhaps a
> subset of] that design for standardization in Swift.
>
> Sent from my iPad
>
> On Dec 2, 2017, at 5:12 PM, Kyle Murray via swift-evolution <
> swift-evolution@swift.org> wrote:
>
>
> On Dec 2, 2017, at 6:02 PM, Xiaodi Wu via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> Instead, we ought to make clear to users both the features and the
> limitations of this API, to encourage use where suitable and to discourage
> use where unsuitable.
>
>
> I like that you're considering the balance here. I've been lightly
> following this thread and want to add my thoughts on keeping crypto and
> pseudorandomness out of the name of at least one random API intended for
> general use.
>
> For someone who doesn't know or care about the subtleties of insecure or
> pseudorandom numbers, I'm not sure that the name insecureRandom is
> effectively much different than badRandom, at least in terms of the
> information it conveys to non-experts. To Greg's point, that's the opposite
> of the signal that the API name should suggest because it's what most
> people should use most of the time. As you say, this API is being designed
> for general use.
>
> There's a cost to adding extra complexity to names, too. I don't think
> it's far-fetched to suspect that people who find insecureRandom in an
> autocomplete listing or search will think "Where's the plain random
> function?"... and then go looking for a community extension that will
> inevitably provide a trivial alias: func random() { return
> insecureRandom() }. That's the sort of adoption I'd expect from something
> for new programmers, like Swift Playgrounds. Someone's introduction to
> randomness in programming should probably involve no more than a
> straightforward mapping from the elementary definition, rather than forcing
> a teaching moment from more advanced math.
>
> I think there are better places for caveat information than in the API
> names themselves; documentation being one clear destination. This is in
> contrast with Unsafe*Pointer, where the safety element is critical enough
> to be elevated to be more than caveat-level information. You can go really
> far and create really cool things before these caveats start to apply.
> Using randomness as a black box in an intro programming environment seems
> like a much more common scenario than someone attempting to roll their
> first crypto by only reading API names and hoping for the best.
>
> -Kyle
>
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-

Re: [swift-evolution] 100% bikeshed topic: DictionaryLiteral

2018-01-08 Thread Xiaodi Wu via swift-evolution
On Tue, Jan 9, 2018 at 00:40 Nevin Brackett-Rozinsky <
nevin.brackettrozin...@gmail.com> wrote:

> On Mon, Jan 8, 2018 at 11:53 PM, Xiaodi Wu via swift-evolution <
> swift-evolution@swift.org> wrote:
>
>> Thank you for the clarification. It occurred to me in the shower that
>> this might be the case, and that I was entirely mistaken as to what we were
>> talking about.
>>
>> Yes, then, I wholeheartedly agree on this point. Out of curiosity, why
>> are there source stability issues to 'typealias DictionaryLiteral<Key,
>> Value> = [(Key, Value)]'?
>
>
> Because at the point of use, “DictionaryLiteral” is instantiated with an
> actual dictionary literal, eg. “[a: 1, b: 2, c: 3]”, and that syntax isn’t
> available for an array of key-value pairs.
>

Why do we need available syntax? Sure, conformance of [(Key, Value)] to
ExpressibleByDictionaryLiteral can't be written in Swift, but we could make
this a built-in conformance. Literals are magical in many ways no matter
what.

As near as I can tell, the convenience of that spelling is the entire
> *raison-d’être* for “DictionaryLiteral” in the first place.
>
> The ulterior question of whether preserving “DictionaryLiteral” is
> worthwhile, is apparently out of scope. Personally, I have a hard time
> imagining a compelling use-case outside of the standard library, and I
> doubt it’s being used “in the wild” (I checked several projects in the
> source-compatibility suite and found zero occurrences).
>

I have seen examples where its use is encouraged, and I see no reason to
address this "ulterior question."

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


Re: [swift-evolution] 100% bikeshed topic: DictionaryLiteral

2018-01-08 Thread Xiaodi Wu via swift-evolution
Thank you for the clarification. It occurred to me in the shower that this
might be the case, and that I was entirely mistaken as to what we were
talking about.

Yes, then, I wholeheartedly agree on this point. Out of curiosity, why are
there source stability issues to 'typealias DictionaryLiteral =
[(Key, Value)]'?
On Mon, Jan 8, 2018 at 23:25 Nate Cook  wrote:

>
> On Jan 8, 2018, at 9:07 PM, Xiaodi Wu  wrote:
>
> While there’s nothing specifically to do with a dictionary, it is a
> literal in at least one essential respect. Like other literals, it doesn’t
> have a type, but values that are expressed by them do acquire a type given
> the context.
>
>
> This confusion is why we really need to rename this—there are two separate
> things:
>
> 1) *Dictionary literals.* These are written as comma-separated key-value
> pairs, with each key-value pair separated by a colon—[a: b, c: d, e: f].
> Most users of Swift have probably only ever used these to create instances
> of the Dictionary type, but any type that conforms to
> ExpressibleByDictionaryLiteral can be expressed using one. Crucially, like
> integer literals that can express an `Int` value, a `UInt8` value, or a
> value of any other integer or floating-point type, dictionary literals have 
> *no
> concrete type* until they’re evaluated in context.
>
> 2) *The `DictionaryLiteral` type.* This is a generic type that conforms
> to ExpressibleByDictionaryLiteral, but is otherwise an unremarkable
> collection with `(Key, Value)` elements. You can see its declaration here:
> https://github.com/apple/swift/blob/master/stdlib/public/core/Mirror.swift#L855.
> Despite the name, `DictionaryLiteral` is not a literal—it’s a concrete type
> and can’t be used to express dictionaries or other types that conform to
> `ExpressibleByDictionaryLiteral`.
>
> It’s #2 that we’re talking about renaming, and while I think both parts of
> the name (“Dictionary” and “Literal”) are inaccurate, “Literal” is more
> problematic because of the confusion it causes with lower-case literals.
>
> Nate
>
> Yes, it's not a dictionary, but neither is an integer literal an integer
> (or even necessarily an integer you can create from such a literal: it can
> be a floating-point value you create from that literal), etc. Would
> "ordered collection of key-value pairs" be more "correct"? By the same
> token, we ought to be renaming integer literals "ordered collection of
> digits without interposed decimal point."
>
> But essentially every user will have encountered this spelling in the
> context of dictionaries: in other words, its name has a good basis in
> reality because it is the (only) literal spelling that can be used to
> create a dictionary, and when you say "hey, that spelling you use for a
> literal to instantiate a dictionary in Swift," everyone will know what
> you're talking about.
>
> No, I think we ought to do nothing. It's not only "not bad," but as far as
> I can tell quite superior to the alternatives in essentially every respect.
> In the alternative, maybe "KeyValueLiteral" or something of that sort, but
> I still would consider that to be strictly inferior to "DictionaryLiteral".
>
>
> On Mon, Jan 8, 2018 at 20:24 Nate Cook via swift-evolution <
> swift-evolution@swift.org> wrote:
>
>>
>> > On Jan 8, 2018, at 6:29 PM, Ben Cohen via swift-evolution <
>> swift-evolution@swift.org> wrote:
>> >
>> > There exists in the standard library a type `DictionaryLiteral` that
>> deserves naming re-consideration before we declare ABI Stability, because
>> it’s confusingly misnamed, being neither a Dictionary (it doesn’t provide
>> key-based lookup of values) nor a Literal.
>> >
>> > Instead, it’s just an immutable collection of key-value pairs you can
>> create _from_ a literal.
>> >
>> > I’m canvassing for opinions on what it ought to be called.  Some
>> suggestions so far:
>> >
>> > - `AssociationCollection`: Following the term of art from some other
>> languages. Slightly obscure-sounding to developers not already familiar.
>> Also “association” and “associative” are confusingly similar, which brings
>> back the is-this-a-dictionary problem.
>> > - `KeyValueCollection`: Problematic because key-value comes up in a
>> totally different context in Cocoa.
>> > - `PairCollection`: “Pair” is kinda nondescript.
>> > - Do nothing. It’s not so bad.
>>
>> Agreed so far, and I'd like to add CollectionOfPairs to the list.
>>
>> Some more fun facts about this type:
>> - Besides Dictionary, it's the only other type in the standard library
>> that is expressible by a dictionary literal
>> - Unlike Dictionary, it *does* maintain the order of its pairs
>> - Unlike Dictionary (part 2), it *doesn't* require the first element of
>> the pairs to be Hashable
>>
>> Nate
>>
>> > The old name can live on indefinitely via a typealias (which has no ABI
>> consequences, so could be retired at a later date once everyone has had
>> plenty of time to address the 

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

2018-01-08 Thread Xiaodi Wu via swift-evolution
Agreed. This simplification is more or less precisely the shape of the
proposal that I was hoping for.

I'm worried that "optional" `random()` and "non-optional" `random()` are
spelled the same way, especially as the type is not always obvious when,
say, a range or collection is referred to by variable name and not as a
literal. And I do think that may become even more problematic should we
decide that some ranges (i.e., the countable ones) ought to conform to
Collection. (But more on that later.)

But besides that concern (which, I would hope, should not be glossed over),
I do like the direction of Nate's playground.


On Mon, Jan 8, 2018 at 5:37 PM, David Hart via swift-evolution <
swift-evolution@swift.org> wrote:

> Unfortunately, it wasn’t my only worry. The simplifications from dropping
> Randomizable and random(in: ) are also very welcome for me.
>
>
> On 8 Jan 2018, at 23:08, Alejandro Alonso <aalonso...@outlook.com> wrote:
>
> I made changes last night that uses methods rather than properties if
> that’s all you’re worried about.
>
> Sent from my iPhone
>
> On Jan 8, 2018, at 15:27, David Hart via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> I much prefer the API from Nate Cook compared to the previous proposal.
> Its simpler, while still very powerful, and closer to Swift conventions
> (method instead of property).
>
> On 8 Jan 2018, at 20:02, Nate Cook via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> I created a playground to explore this question, starting with a minimal
> subset of the proposal’s additions and building from there. The attached
> playground demonstrates what’s possible with this subset on the first page,
> then uses subsequent pages to explore how the main random facilities of the
> C++ STL work under this model. (In my opinion, they work pretty well!)
>
> The subset in the playground has three main differences from the proposal:
>  - It doesn't include a Randomizable protocol or a random property on
> numeric types.
>  - It doesn't include the static random(in:) methods on numeric types,
> either.
>  - The RandomNumberGenerator protocol doesn't have an associated type.
> Instead, it requires all conforming types to produce UInt64 values.
>
> I’ve tried to include a bit of real-world usage in the playground to
> demonstrate what writing code would look like with these additions. Please
> take a look!
>
> Nate
>
> 
>
> On Dec 2, 2017, at 9:50 PM, Dave Abrahams via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> I don’t have much to say about this other than that I think the discussion
> seems way too narrow, focusing on spelling rather than on functionality and
> composability.  I consider the “generic random number library” design to be
> a mostly-solved problem, in the C++ standard library (
> http://en.cppreference.com/w/cpp/numeric/random).  Whatever goes into the
> Swift standard library does not need to have all those features right away,
> but should support being extended into something having the same general
> shape. IMO the right design strategy is to *implement and use* a Swift
> version of C++’s facilities and only then consider proposing [perhaps a
> subset of] that design for standardization in Swift.
>
> Sent from my iPad
>
> On Dec 2, 2017, at 5:12 PM, Kyle Murray via swift-evolution <
> swift-evolution@swift.org> wrote:
>
>
> On Dec 2, 2017, at 6:02 PM, Xiaodi Wu via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> Instead, we ought to make clear to users both the features and the
> limitations of this API, to encourage use where suitable and to discourage
> use where unsuitable.
>
>
> I like that you're considering the balance here. I've been lightly
> following this thread and want to add my thoughts on keeping crypto and
> pseudorandomness out of the name of at least one random API intended for
> general use.
>
> For someone who doesn't know or care about the subtleties of insecure or
> pseudorandom numbers, I'm not sure that the name insecureRandom is
> effectively much different than badRandom, at least in terms of the
> information it conveys to non-experts. To Greg's point, that's the opposite
> of the signal that the API name should suggest because it's what most
> people should use most of the time. As you say, this API is being designed
> for general use.
>
> There's a cost to adding extra complexity to names, too. I don't think
> it's far-fetched to suspect that people who find insecureRandom in an
> autocomplete listing or search will think "Where's the plain random
> function?"... and then go looking for a community extension that will
> inevitably provide a trivial alia

Re: [swift-evolution] 100% bikeshed topic: DictionaryLiteral

2018-01-08 Thread Xiaodi Wu via swift-evolution
While there’s nothing specifically to do with a dictionary, it is a literal
in at least one essential respect. Like other literals, it doesn’t have a
type, but values that are expressed by them do acquire a type given the
context.

Yes, it's not a dictionary, but neither is an integer literal an integer
(or even necessarily an integer you can create from such a literal: it can
be a floating-point value you create from that literal), etc. Would
"ordered collection of key-value pairs" be more "correct"? By the same
token, we ought to be renaming integer literals "ordered collection of
digits without interposed decimal point."

But essentially every user will have encountered this spelling in the
context of dictionaries: in other words, its name has a good basis in
reality because it is the (only) literal spelling that can be used to
create a dictionary, and when you say "hey, that spelling you use for a
literal to instantiate a dictionary in Swift," everyone will know what
you're talking about.

No, I think we ought to do nothing. It's not only "not bad," but as far as
I can tell quite superior to the alternatives in essentially every respect.
In the alternative, maybe "KeyValueLiteral" or something of that sort, but
I still would consider that to be strictly inferior to "DictionaryLiteral".


On Mon, Jan 8, 2018 at 20:24 Nate Cook via swift-evolution <
swift-evolution@swift.org> wrote:

>
> > On Jan 8, 2018, at 6:29 PM, Ben Cohen via swift-evolution <
> swift-evolution@swift.org> wrote:
> >
> > There exists in the standard library a type `DictionaryLiteral` that
> deserves naming re-consideration before we declare ABI Stability, because
> it’s confusingly misnamed, being neither a Dictionary (it doesn’t provide
> key-based lookup of values) nor a Literal.
> >
> > Instead, it’s just an immutable collection of key-value pairs you can
> create _from_ a literal.
> >
> > I’m canvassing for opinions on what it ought to be called.  Some
> suggestions so far:
> >
> > - `AssociationCollection`: Following the term of art from some other
> languages. Slightly obscure-sounding to developers not already familiar.
> Also “association” and “associative” are confusingly similar, which brings
> back the is-this-a-dictionary problem.
> > - `KeyValueCollection`: Problematic because key-value comes up in a
> totally different context in Cocoa.
> > - `PairCollection`: “Pair” is kinda nondescript.
> > - Do nothing. It’s not so bad.
>
> Agreed so far, and I'd like to add CollectionOfPairs to the list.
>
> Some more fun facts about this type:
> - Besides Dictionary, it's the only other type in the standard library
> that is expressible by a dictionary literal
> - Unlike Dictionary, it *does* maintain the order of its pairs
> - Unlike Dictionary (part 2), it *doesn't* require the first element of
> the pairs to be Hashable
>
> Nate
>
> > The old name can live on indefinitely via a typealias (which has no ABI
> consequences, so could be retired at a later date once everyone has had
> plenty of time to address the deprecation warnings). Removing it as not
> carrying its weight (and instead using `[(Key,Value)]`, which is basically
> what it’s a wrapper for) is probably off the table for source stability
> reasons.
> >
> > Any further thoughts welcome.
> >
> >
> >
> > ___
> > 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] [Review] SE 0192 - Non-Exhaustive Enums

2018-01-05 Thread Xiaodi Wu via swift-evolution
On Fri, Jan 5, 2018 at 03:11 Jonathan Hull <jh...@gbis.com> wrote:

> On Jan 4, 2018, at 11:02 PM, Xiaodi Wu <xiaodi...@gmail.com> wrote:
>
>
> On Fri, Jan 5, 2018 at 01:56 Jonathan Hull <jh...@gbis.com> wrote:
>
>> On Jan 4, 2018, at 10:31 PM, Xiaodi Wu via swift-evolution <
>> swift-evolution@swift.org> wrote:
>>
>>
>> On Fri, Jan 5, 2018 at 00:21 Cheyo Jimenez <ch...@masters3d.com> wrote:
>>
>>
>>> On Jan 4, 2018, at 4:37 PM, Xiaodi Wu <xiaodi...@gmail.com> wrote:
>>>
>>> On Thu, Jan 4, 2018 at 19:29 Cheyo J. Jimenez <ch...@masters3d.com>
>>> wrote:
>>>
>>> We seem to agree that, by virtue of not supporting use in a pattern and
>>> being placed at the end, the feature is a flavor of default. I’m still not
>>> sure I understand why you believe it should not be a flavor of default
>>> going forward.
>>>
>>>
>>>> You still haven’t answered my question, though—what’s the use case for
>>>> the feature you propose?
>>>>
>>>>
>>>> My use case would be distinguishing between compile time known cases vs
>>>> “future only” cases (or unknown cases).
>>>>
>>>
>>> I understand that the feature you propose would allow you to make such a
>>> distinction, but again, what is your use case for doing so?
>>>
>>> Breaking out early by checking unknown cases first. I admit this is not
>>> deal breaker, just a different style I’d like to see supported in the
>>> future.
>>>
>>
>> I'm still not sure I understand. How can the machine know that it's
>> dealing with an unknown case without first checking if it matches any known
>> case?
>>
>>
>> I had the same thought as Cheyo.  It isn’t a deal breaker… I like the
>> compromise, but I would prefer it trigger only on an actual unknown case
>> (as opposed to acting like default). I like to break failure cases out at
>> the top when possible. I don’t see any good reason not to support that
>> style.
>>
>> To answer your question, in the naive sense, it basically is the same
>> question as asking if it is a known case (and then taking the inverse).
>> That doesn’t mean actually checking each case separately though. For
>> example, if the enum cases are internally represented as an unsigned
>> integer, and they are all together in a block, the compiler could simply
>> check that it is greater than the max known value. You could probably even
>> do a bit mask comparison in some cases...
>>
>
> These are obvious optimizations, but why does this require new syntax?
>
>
> I am not sure I understand what you are asking. There isn’t additional
> syntax.  We are just arguing over the name + behavior of ‘unexpected:’.
> You want it to behave like ‘default’ and I am saying that stops the use
> case I mention above.
>

Cheyo said he wants “unexpected case” to work in pattern matching, as well
as a new “case *” that is distinct from “case _”. This is additional
syntax. When asked what the use case was for these suggestions, he said he
wants to distinguish between known and unknown cases at the beginning of
the switch.


>
> What do you gain from writing the unknown case first?
>
> I know where to look for the failure cases.  I also tend put a bunch of
> guard statements near the beginning of a function.  It is just a
> programming style.
>
> With my behavior of ‘unexpected:’ you can put it wherever you want.  Why
> limit that by forcing it to go at the end?
>

As pointed out earlier (by one of the core team members, I think),
meaningful resilience would mean that the unexpected or unknown case should
have useful work executed at runtime; the intention is that the user
*shouldn’t* be treating it as a runtime “failure case,” as it effectively
makes adding an enum case a change that is incompatible with existing
binaries (i.e., not terribly resilient).

As you and I seem to agree, reaching an unexpected case requires at least
notionally considering which cases are expected in the first place. This is
the dictionary definition of a default, and Swift usage is to put the
default case at the end of a switch statement. Adding new syntax as Cheyo
suggests to enable putting it elsewhere, merely for “style,” doesn’t seem
to pass the bar for new syntax, nor is it consistent with existing Swift
usage.

Isn't this basically the same thing as asking for the ability to write the
> default case first, a frequently suggested and rejected syntax addition?
>
>
> No.  I don’t think I have ever heard that asked for,
>

It has been asked for more than once on this list.

but putt

Re: [swift-evolution] [Review] SE 0192 - Non-Exhaustive Enums

2018-01-04 Thread Xiaodi Wu via swift-evolution
On Fri, Jan 5, 2018 at 01:56 Jonathan Hull <jh...@gbis.com> wrote:

> On Jan 4, 2018, at 10:31 PM, Xiaodi Wu via swift-evolution <
> swift-evolution@swift.org> wrote:
>
>
> On Fri, Jan 5, 2018 at 00:21 Cheyo Jimenez <ch...@masters3d.com> wrote:
>
>
>> On Jan 4, 2018, at 4:37 PM, Xiaodi Wu <xiaodi...@gmail.com> wrote:
>>
>> On Thu, Jan 4, 2018 at 19:29 Cheyo J. Jimenez <ch...@masters3d.com>
>> wrote:
>>
>> We seem to agree that, by virtue of not supporting use in a pattern and
>> being placed at the end, the feature is a flavor of default. I’m still not
>> sure I understand why you believe it should not be a flavor of default
>> going forward.
>>
>>
>>> You still haven’t answered my question, though—what’s the use case for
>>> the feature you propose?
>>>
>>>
>>> My use case would be distinguishing between compile time known cases vs
>>> “future only” cases (or unknown cases).
>>>
>>
>> I understand that the feature you propose would allow you to make such a
>> distinction, but again, what is your use case for doing so?
>>
>> Breaking out early by checking unknown cases first. I admit this is not
>> deal breaker, just a different style I’d like to see supported in the
>> future.
>>
>
> I'm still not sure I understand. How can the machine know that it's
> dealing with an unknown case without first checking if it matches any known
> case?
>
>
> I had the same thought as Cheyo.  It isn’t a deal breaker… I like the
> compromise, but I would prefer it trigger only on an actual unknown case
> (as opposed to acting like default). I like to break failure cases out at
> the top when possible. I don’t see any good reason not to support that
> style.
>
> To answer your question, in the naive sense, it basically is the same
> question as asking if it is a known case (and then taking the inverse).
> That doesn’t mean actually checking each case separately though. For
> example, if the enum cases are internally represented as an unsigned
> integer, and they are all together in a block, the compiler could simply
> check that it is greater than the max known value. You could probably even
> do a bit mask comparison in some cases...
>

These are obvious optimizations, but why does this require new syntax? What
do you gain from writing the unknown case first? Isn't this basically the
same thing as asking for the ability to write the default case first, a
frequently suggested and rejected syntax addition?

If it is inefficient for some reason, the compiler should be free to
> rearrange the order of things, as long as it doesn’t change the outcome.
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Review] SE 0192 - Non-Exhaustive Enums

2018-01-04 Thread Xiaodi Wu via swift-evolution
s/0192-non-exhaustive-enums.md#future-directions>.
>>> The above example if from there.
>>>
>>> I am fine with `unknown case` being required to be at the end of the
>>> switch for now.
>>>
>>> I think of `unknown case` as a pattern that only matches unknown cases
>>> no matter where on the switch it is.
>>>
>>> This is why I do not think that `default unknown` would work well once
>>> `unknown case` can be used a pattern.
>>>
>>> We can start a new thread on this if you’d like.
>>>
>>
>> The reason I put forward “default unknown” is precisely because the
>> proposed feature *cannot* be used in a pattern and therefore seems more apt
>> as not a case.
>>
>> It can not be used in a pattern now but you could in the future if left
>> as `case`.
>>
>>
>> It actually makes it more natural to use in the given example above
>> because “default unknown” could actually be used to provide compile-time
>> exhaustiveness checking for such a tuple pattern, whereas without being
>> able to use “unknown case” in a pattern you can’t write “case (unknown
>> case, _)”.
>>
>>
>> The way `unknown case` enforces  compile-time exhaustiveness is by only
>> matching unknown cases. The implementation may be more close to default by
>> the virtue of being forced to go at the end of the switch statement now but
>> that should not dictate the user experience.
>>
>
> We seem to agree that, by virtue of not supporting use in a pattern and
> being placed at the end, the feature is a flavor of default. I’m still not
> sure I understand why you believe it should not be a flavor of default
> going forward.
>
>
>> You still haven’t answered my question, though—what’s the use case for
>> the feature you propose?
>>
>>
>> My use case would be distinguishing between compile time known cases vs
>> “future only” cases (or unknown cases).
>>
>
> I understand that the feature you propose would allow you to make such a
> distinction, but again, what is your use case for doing so?
>
>
> Breaking out early by checking unknown cases first. I admit this is not
> deal breaker, just a different style I’d like to see supported in the
> future.
>

I'm still not sure I understand. How can the machine know that it's dealing
with an unknown case without first checking if it matches any known case?


>
> This depends on generalized `unknown case` patterns which is out of scope.
>> I am happy to talk more about this on a different thread when this proposal
>> gets approved.
>>
>>
>>
>>
>>
>>>
>>>
>>>
>>>
>>>
>>>>
>>>>>
>>>>>
>>>>> I'll add these points to the "Alternatives Considered" section in the
>>>>> PR later today.
>>>>>
>>>>> Jordan
>>>>>
>>>>>
>>>>> On Jan 3, 2018, at 22:56, Xiaodi Wu <xiaodi...@gmail.com> wrote:
>>>>>
>>>>> As has already been said, “case unknown” is source-breaking because it
>>>>> conflicts with any real cases named “unknown”; “\unknown” looks like a key
>>>>> path but isn’t, and I wonder if it would potentially conflict with 
>>>>> existing
>>>>> key paths.
>>>>>
>>>>> In any case, my point was not to bikeshed the “unknown” part, but to
>>>>> ask whether any consideration had been made to have the feature presented
>>>>> as a flavor of default instead of a flavor of case.
>>>>>
>>>>> On Wed, Jan 3, 2018 at 23:57 Cheyo Jimenez <ch...@masters3d.com>
>>>>> wrote:
>>>>>
>>>>>>
>>>>>>
>>>>>> On Jan 3, 2018, at 6:52 PM, Xiaodi Wu via swift-evolution <
>>>>>> swift-evolution@swift.org> wrote:
>>>>>>
>>>>>> This is a very nice revision. One bikeshedding thought:
>>>>>>
>>>>>> Since "unknown case" is presented as a special kind of "default",
>>>>>> can't be mixed with "default", and can't be used in case patterns, why 
>>>>>> not
>>>>>> "default unknown" (or "unknown default") instead of "unknown case"?
>>>>>>
>>>>>>
>>>>>> `case _ :` is already a special case of default.
>>>>>> I’d rather have `case unknown :`
>>>&

Re: [swift-evolution] Renaming SwiftObject

2018-01-04 Thread Xiaodi Wu via swift-evolution
If it’s the base class for all Swift class types, I think “SwiftObject” is
ideal and the proposed renaming is sensible. What does it matter that it’s
an Obj-C object? Why does that have to be in the name? Let’s not bikeshed
this and keep it simple.

On Thu, Jan 4, 2018 at 22:21 Félix Cloutier via swift-evolution <
swift-evolution@swift.org> wrote:

> I'll bite. Shouldn't that name encode that it's an Objective-C object?
> Like Swift.ObjCBase?
>
>
> Le 4 janv. 2018 à 22:10, Greg Parker via swift-evolution <
> swift-evolution@swift.org> a écrit :
>
> SwiftObject is an Objective-C class that is the base class of all "pure
> Swift" class types. It needs to be renamed for the Swift stable ABI in
> order to avoid ObjC class name collisions between the stable ABI's Swift
> runtime and the runtime embedded into existing Swift apps.
>
> I suggest `Swift._Object`, mangled as _TtCs7_Object like other Swift ObjC
> class names.
>
> Any comments?
>
> https://github.com/apple/swift/pull/13748
>
>
> --
> Greg Parker gpar...@apple.com Runtime Wrangler
>
>
> ___
> 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] [Review] SE 0192 - Non-Exhaustive Enums

2018-01-04 Thread Xiaodi Wu via swift-evolution
he
> proposed feature *cannot* be used in a pattern and therefore seems more apt
> as not a case.
>
> It can not be used in a pattern now but you could in the future if left as
> `case`.
>
>
> It actually makes it more natural to use in the given example above
> because “default unknown” could actually be used to provide compile-time
> exhaustiveness checking for such a tuple pattern, whereas without being
> able to use “unknown case” in a pattern you can’t write “case (unknown
> case, _)”.
>
>
> The way `unknown case` enforces  compile-time exhaustiveness is by only
> matching unknown cases. The implementation may be more close to default by
> the virtue of being forced to go at the end of the switch statement now but
> that should not dictate the user experience.
>

We seem to agree that, by virtue of not supporting use in a pattern and
being placed at the end, the feature is a flavor of default. I’m still not
sure I understand why you believe it should not be a flavor of default
going forward.


> You still haven’t answered my question, though—what’s the use case for the
> feature you propose?
>
>
> My use case would be distinguishing between compile time known cases vs
> “future only” cases (or unknown cases).
>

I understand that the feature you propose would allow you to make such a
distinction, but again, what is your use case for doing so?

This depends on generalized `unknown case` patterns which is out of scope.
> I am happy to talk more about this on a different thread when this proposal
> gets approved.
>
>
>
>
>
>>
>>
>>
>>
>>
>>>
>>>>
>>>>
>>>> I'll add these points to the "Alternatives Considered" section in the
>>>> PR later today.
>>>>
>>>> Jordan
>>>>
>>>>
>>>> On Jan 3, 2018, at 22:56, Xiaodi Wu <xiaodi...@gmail.com> wrote:
>>>>
>>>> As has already been said, “case unknown” is source-breaking because it
>>>> conflicts with any real cases named “unknown”; “\unknown” looks like a key
>>>> path but isn’t, and I wonder if it would potentially conflict with existing
>>>> key paths.
>>>>
>>>> In any case, my point was not to bikeshed the “unknown” part, but to
>>>> ask whether any consideration had been made to have the feature presented
>>>> as a flavor of default instead of a flavor of case.
>>>>
>>>> On Wed, Jan 3, 2018 at 23:57 Cheyo Jimenez <ch...@masters3d.com> wrote:
>>>>
>>>>>
>>>>>
>>>>> On Jan 3, 2018, at 6:52 PM, Xiaodi Wu via swift-evolution <
>>>>> swift-evolution@swift.org> wrote:
>>>>>
>>>>> This is a very nice revision. One bikeshedding thought:
>>>>>
>>>>> Since "unknown case" is presented as a special kind of "default",
>>>>> can't be mixed with "default", and can't be used in case patterns, why not
>>>>> "default unknown" (or "unknown default") instead of "unknown case"?
>>>>>
>>>>>
>>>>> `case _ :` is already a special case of default.
>>>>> I’d rather have `case unknown :`
>>>>> `unknown case :` is weird because of the order of `case`.
>>>>>
>>>>> Another alternative is `case \unknown :`
>>>>> `\unknown` would also allow pattern matching.
>>>>>
>>>>>
>>>>>
>>>>>
>>>>>
>>>>> On Wed, Jan 3, 2018 at 8:05 PM, Jordan Rose via swift-evolution <
>>>>> swift-evolution@swift.org> wrote:
>>>>>
>>>>>> On Jan 2, 2018, at 18:07, Jordan Rose <jordan_r...@apple.com> wrote:
>>>>>>
>>>>>> [Proposal:
>>>>>> https://github.com/apple/swift-evolution/blob/master/proposals/0192-non-exhaustive-enums.md
>>>>>> ]
>>>>>>
>>>>>> Whew! Thanks for your feedback, everyone. On the lighter side of
>>>>>> feedback—naming things—it seems that most people seem to like '
>>>>>> *@frozen*', and that does in fact have the connotations we want it
>>>>>> to have. I like it too.
>>>>>>
>>>>>> More seriously, this discussion has convinced me that it's worth
>>>>>> including what the proposal discusses as a *'future' case*. The key
>>>>>> point that swayed me is that this can produce a *warning* when the
&

Re: [swift-evolution] [Review] SE 0192 - Non-Exhaustive Enums

2018-01-04 Thread Xiaodi Wu via swift-evolution
On Thu, Jan 4, 2018 at 18:39 Cheyo J. Jimenez <ch...@masters3d.com> wrote:

>
> On Jan 4, 2018, at 2:55 PM, Xiaodi Wu <xiaodi...@gmail.com> wrote:
>
>
> On Thu, Jan 4, 2018 at 17:15 Cheyo J. Jimenez <ch...@masters3d.com> wrote:
>
>> On Jan 4, 2018, at 11:53 AM, Xiaodi Wu <xiaodi...@gmail.com> wrote:
>>
>>
>> On Thu, Jan 4, 2018 at 13:46 Cheyo Jimenez <ch...@masters3d.com> wrote:
>>
>>>
>>>
>>> On Jan 4, 2018, at 10:49 AM, Jordan Rose <jordan_r...@apple.com> wrote:
>>>
>>> I'll admit I hadn't thought of using "unknown default" (or "default
>>> unknown"). I don't think that's terrible, but I mildly prefer `unknown
>>> case` because it builds on the "pun" that enum elements are also defined
>>> using 'case'. If anything hits this part of the switch, it really will be
>>> an "unknown case", i.e. a statically-unknown enum element.
>>>
>>> To Cheyo's point, if this *were* to be a single token I'd probably
>>> spell it #unknown, like #available. Then we'd have `case #unknown:` and
>>> something that naturally expands to other pattern positions. I found that
>>> less aesthetically pleasing, though, and so a context-sensitive keyword
>>> seemed like the way to go.
>>>
>>> (For the record, though, I wouldn't describe `case _` as a special case
>>> of `default`. They do exactly the same thing, and `_` is a useful pattern
>>> in other contexts, so if anything the current `default` should be thought
>>> of as syntactic sugar for `case _`.)
>>>
>>>
>>> Can case _ be mixed with unknown case? How can we match all compile time
>>> known cases but exclude future cases?
>>>
>>
>> What’s your use case for that? That eliminates the possibility of
>> “unknown case” giving you compile-time warnings for subsequently added
>> cases, which was the entire purpose of adding the syntax in the first place.
>>
>>
>> I was thinking of a generalized `unknown case` pattern but that is out
>> of scope for this proposal.
>> <https://github.com/apple/swift-evolution/pull/777/files#diff-a68dc745ee86d09566b232b6954c5158R321>
>>
>>
>> switch excuse {
>>  case .eatenByPet :
>>//…
>>  unknown case:
>>// …
>>  case _:
>>// …
>>  }
>>
>>
>> Should there be something like `case *` that would capture all currently
>>> known cases during compile time? case * and case _ would be the same in
>>> exhaustive enums.
>>>
>>
>> This is why I was suggesting another pattern that only captures known
>> cases at compile time:
>>
>> switch excuse {
>>  case .eatenByPet :
>>//…
>>  case * : //  All cases captured at compile time.
>>// …
>>  unknown case:
>>// …
>>  }
>>
>
> Sorry, I don’t understand. However you spell it, what is your use case for
> this? The stated purpose of “unknown case” is to gain compile-time
> exhaustiveness testing, but this would not allow for that.
>
>
>
>
>
> switch (excuse, notifiedTeacherBeforeDeadline) {case (.eatenByPet, true):
>   // …case (.thoughtItWasDueNextWeek, true):
>   // …case (unknown case, true):
>   // …case (_, false):
>   // …}
>
>
> Im referring to the future direction section in the new PR
> <https://github.com/jrose-apple/swift-evolution/blob/6061c01fb4a6d742ba7213f46979c9b82891fc14/proposals/0192-non-exhaustive-enums.md#future-directions>.
> The above example if from there.
>
> I am fine with `unknown case` being required to be at the end of the
> switch for now.
>
> I think of `unknown case` as a pattern that only matches unknown cases no
> matter where on the switch it is.
>
> This is why I do not think that `default unknown` would work well once
> `unknown case` can be used a pattern.
>
> We can start a new thread on this if you’d like.
>

The reason I put forward “default unknown” is precisely because the
proposed feature *cannot* be used in a pattern and therefore seems more apt
as not a case.

It actually makes it more natural to use in the given example above because
“default unknown” could actually be used to provide compile-time
exhaustiveness checking for such a tuple pattern, whereas without being
able to use “unknown case” in a pattern you can’t write “case (unknown
case, _)”.

You still haven’t answered my question, though—what’s the use case for the
feature you propose?


>
>
>
>
>
>>
>>>
>>>
>>> I'll add these points to the "Alternatives Consi

Re: [swift-evolution] [Review] SE 0192 - Non-Exhaustive Enums

2018-01-04 Thread Xiaodi Wu via swift-evolution
On Thu, Jan 4, 2018 at 17:15 Cheyo J. Jimenez <ch...@masters3d.com> wrote:

> On Jan 4, 2018, at 11:53 AM, Xiaodi Wu <xiaodi...@gmail.com> wrote:
>
>
> On Thu, Jan 4, 2018 at 13:46 Cheyo Jimenez <ch...@masters3d.com> wrote:
>
>>
>>
>> On Jan 4, 2018, at 10:49 AM, Jordan Rose <jordan_r...@apple.com> wrote:
>>
>> I'll admit I hadn't thought of using "unknown default" (or "default
>> unknown"). I don't think that's terrible, but I mildly prefer `unknown
>> case` because it builds on the "pun" that enum elements are also defined
>> using 'case'. If anything hits this part of the switch, it really will be
>> an "unknown case", i.e. a statically-unknown enum element.
>>
>> To Cheyo's point, if this *were* to be a single token I'd probably spell
>> it #unknown, like #available. Then we'd have `case #unknown:` and something
>> that naturally expands to other pattern positions. I found that less
>> aesthetically pleasing, though, and so a context-sensitive keyword seemed
>> like the way to go.
>>
>> (For the record, though, I wouldn't describe `case _` as a special case
>> of `default`. They do exactly the same thing, and `_` is a useful pattern
>> in other contexts, so if anything the current `default` should be thought
>> of as syntactic sugar for `case _`.)
>>
>>
>> Can case _ be mixed with unknown case? How can we match all compile time
>> known cases but exclude future cases?
>>
>
> What’s your use case for that? That eliminates the possibility of “unknown
> case” giving you compile-time warnings for subsequently added cases, which
> was the entire purpose of adding the syntax in the first place.
>
>
> I was thinking of a generalized `unknown case` pattern but that is out of
> scope for this proposal.
> <https://github.com/apple/swift-evolution/pull/777/files#diff-a68dc745ee86d09566b232b6954c5158R321>
>
>
> switch excuse {
>  case .eatenByPet :
>//…
>  unknown case:
>// …
>  case _:
>// …
>  }
>
>
> Should there be something like `case *` that would capture all currently
>> known cases during compile time? case * and case _ would be the same in
>> exhaustive enums.
>>
>
> This is why I was suggesting another pattern that only captures known
> cases at compile time:
>
> switch excuse {
>  case .eatenByPet :
>//…
>  case * : //  All cases captured at compile time.
>// …
>  unknown case:
>// …
>  }
>

Sorry, I don’t understand. However you spell it, what is your use case for
this? The stated purpose of “unknown case” is to gain compile-time
exhaustiveness testing, but this would not allow for that.



>
>>
>>
>> I'll add these points to the "Alternatives Considered" section in the PR
>> later today.
>>
>> Jordan
>>
>>
>> On Jan 3, 2018, at 22:56, Xiaodi Wu <xiaodi...@gmail.com> wrote:
>>
>> As has already been said, “case unknown” is source-breaking because it
>> conflicts with any real cases named “unknown”; “\unknown” looks like a key
>> path but isn’t, and I wonder if it would potentially conflict with existing
>> key paths.
>>
>> In any case, my point was not to bikeshed the “unknown” part, but to ask
>> whether any consideration had been made to have the feature presented as a
>> flavor of default instead of a flavor of case.
>>
>> On Wed, Jan 3, 2018 at 23:57 Cheyo Jimenez <ch...@masters3d.com> wrote:
>>
>>>
>>>
>>> On Jan 3, 2018, at 6:52 PM, Xiaodi Wu via swift-evolution <
>>> swift-evolution@swift.org> wrote:
>>>
>>> This is a very nice revision. One bikeshedding thought:
>>>
>>> Since "unknown case" is presented as a special kind of "default", can't
>>> be mixed with "default", and can't be used in case patterns, why not
>>> "default unknown" (or "unknown default") instead of "unknown case"?
>>>
>>>
>>> `case _ :` is already a special case of default.
>>> I’d rather have `case unknown :`
>>> `unknown case :` is weird because of the order of `case`.
>>>
>>> Another alternative is `case \unknown :`
>>> `\unknown` would also allow pattern matching.
>>>
>>>
>>>
>>>
>>>
>>> On Wed, Jan 3, 2018 at 8:05 PM, Jordan Rose via swift-evolution <
>>> swift-evolution@swift.org> wrote:
>>>
>>>> On Jan 2, 2018, at 18:07, Jordan Rose <jordan_r...@apple.com> wrote:
>>>&g

Re: [swift-evolution] [Review] SE 0192 - Non-Exhaustive Enums

2018-01-04 Thread Xiaodi Wu via swift-evolution
On Thu, Jan 4, 2018 at 13:46 Cheyo Jimenez <ch...@masters3d.com> wrote:

>
>
> On Jan 4, 2018, at 10:49 AM, Jordan Rose <jordan_r...@apple.com> wrote:
>
> I'll admit I hadn't thought of using "unknown default" (or "default
> unknown"). I don't think that's terrible, but I mildly prefer `unknown
> case` because it builds on the "pun" that enum elements are also defined
> using 'case'. If anything hits this part of the switch, it really will be
> an "unknown case", i.e. a statically-unknown enum element.
>
> To Cheyo's point, if this *were* to be a single token I'd probably spell
> it #unknown, like #available. Then we'd have `case #unknown:` and something
> that naturally expands to other pattern positions. I found that less
> aesthetically pleasing, though, and so a context-sensitive keyword seemed
> like the way to go.
>
> (For the record, though, I wouldn't describe `case _` as a special case of
> `default`. They do exactly the same thing, and `_` is a useful pattern in
> other contexts, so if anything the current `default` should be thought of
> as syntactic sugar for `case _`.)
>
>
> Can case _ be mixed with unknown case? How can we match all compile time
> known cases but exclude future cases?
>

What’s your use case for that? That eliminates the possibility of “unknown
case” giving you compile-time warnings for subsequently added cases, which
was the entire purpose of adding the syntax in the first place.

Should be something like `case *` that would capture all currently known
> cases during compile time? case * and case _ would be the same in
> exhaustive enums.
>
>
>
> I'll add these points to the "Alternatives Considered" section in the PR
> later today.
>
> Jordan
>
>
> On Jan 3, 2018, at 22:56, Xiaodi Wu <xiaodi...@gmail.com> wrote:
>
> As has already been said, “case unknown” is source-breaking because it
> conflicts with any real cases named “unknown”; “\unknown” looks like a key
> path but isn’t, and I wonder if it would potentially conflict with existing
> key paths.
>
> In any case, my point was not to bikeshed the “unknown” part, but to ask
> whether any consideration had been made to have the feature presented as a
> flavor of default instead of a flavor of case.
>
> On Wed, Jan 3, 2018 at 23:57 Cheyo Jimenez <ch...@masters3d.com> wrote:
>
>>
>>
>> On Jan 3, 2018, at 6:52 PM, Xiaodi Wu via swift-evolution <
>> swift-evolution@swift.org> wrote:
>>
>> This is a very nice revision. One bikeshedding thought:
>>
>> Since "unknown case" is presented as a special kind of "default", can't
>> be mixed with "default", and can't be used in case patterns, why not
>> "default unknown" (or "unknown default") instead of "unknown case"?
>>
>>
>> `case _ :` is already a special case of default.
>> I’d rather have `case unknown :`
>> `unknown case :` is weird because of the order of `case`.
>>
>> Another alternative is `case \unknown :`
>> `\unknown` would also allow pattern matching.
>>
>>
>>
>>
>>
>> On Wed, Jan 3, 2018 at 8:05 PM, Jordan Rose via swift-evolution <
>> swift-evolution@swift.org> wrote:
>>
>>> On Jan 2, 2018, at 18:07, Jordan Rose <jordan_r...@apple.com> wrote:
>>>
>>> [Proposal:
>>> https://github.com/apple/swift-evolution/blob/master/proposals/0192-non-exhaustive-enums.md
>>> ]
>>>
>>> Whew! Thanks for your feedback, everyone. On the lighter side of
>>> feedback—naming things—it seems that most people seem to like '*@frozen*',
>>> and that does in fact have the connotations we want it to have. I like it
>>> too.
>>>
>>> More seriously, this discussion has convinced me that it's worth
>>> including what the proposal discusses as a *'future' case*. The key
>>> point that swayed me is that this can produce a *warning* when the
>>> switch is missing a case rather than an *error,* which both provides
>>> the necessary compiler feedback to update your code and allows your
>>> dependencies to continue compiling when you update to a newer SDK. I know
>>> people on both sides won't be 100% satisfied with this, but does it seem
>>> like a reasonable compromise?
>>>
>>> The next question is how to spell it. I'm leaning towards `unexpected
>>> case:`, which (a) is backwards-compatible, and (b) also handles "private
>>> cases", either the fake kind that you can do in C (as described in the
>>> proposal), or some real feature w

Re: [swift-evolution] [swift-evolution-announce] [Review] SE 0192 - Non-Exhaustive Enums

2018-01-03 Thread Xiaodi Wu via swift-evolution
As has already been said, “case unknown” is source-breaking because it
conflicts with any real cases named “unknown”; “\unknown” looks like a key
path but isn’t, and I wonder if it would potentially conflict with existing
key paths.

In any case, my point was not to bikeshed the “unknown” part, but to ask
whether any consideration had been made to have the feature presented as a
flavor of default instead of a flavor of case.

On Wed, Jan 3, 2018 at 23:57 Cheyo Jimenez <ch...@masters3d.com> wrote:

>
>
> On Jan 3, 2018, at 6:52 PM, Xiaodi Wu via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> This is a very nice revision. One bikeshedding thought:
>
> Since "unknown case" is presented as a special kind of "default", can't be
> mixed with "default", and can't be used in case patterns, why not "default
> unknown" (or "unknown default") instead of "unknown case"?
>
>
> `case _ :` is already a special case of default.
> I’d rather have `case unknown :`
> `unknown case :` is weird because of the order of `case`.
>
> Another alternative is `case \unknown :`
> `\unknown` would also allow pattern matching.
>
>
>
>
>
> On Wed, Jan 3, 2018 at 8:05 PM, Jordan Rose via swift-evolution <
> swift-evolution@swift.org> wrote:
>
>> On Jan 2, 2018, at 18:07, Jordan Rose <jordan_r...@apple.com> wrote:
>>
>> [Proposal:
>> https://github.com/apple/swift-evolution/blob/master/proposals/0192-non-exhaustive-enums.md
>> ]
>>
>> Whew! Thanks for your feedback, everyone. On the lighter side of
>> feedback—naming things—it seems that most people seem to like '*@frozen*',
>> and that does in fact have the connotations we want it to have. I like it
>> too.
>>
>> More seriously, this discussion has convinced me that it's worth
>> including what the proposal discusses as a *'future' case*. The key
>> point that swayed me is that this can produce a *warning* when the
>> switch is missing a case rather than an *error,* which both provides the
>> necessary compiler feedback to update your code and allows your
>> dependencies to continue compiling when you update to a newer SDK. I know
>> people on both sides won't be 100% satisfied with this, but does it seem
>> like a reasonable compromise?
>>
>> The next question is how to spell it. I'm leaning towards `unexpected
>> case:`, which (a) is backwards-compatible, and (b) also handles "private
>> cases", either the fake kind that you can do in C (as described in the
>> proposal), or some real feature we might add to Swift some day. `unknown
>> case:` isn't bad either.
>>
>> I too would like to just do `unknown:` or `unexpected:` but that's
>> technically a source-breaking change:
>>
>> switch foo {
>> case bar:
>>   unknown:
>>   while baz() {
>> while garply() {
>>   if quux() {
>> break unknown
>>   }
>> }
>>   }
>> }
>>
>>
>> Another downside of the `unexpected case:` spelling is that it doesn't
>> work as part of a larger pattern. I don't have a good answer for that one,
>> but perhaps it's acceptable for now.
>>
>> I'll write up a revision of the proposal soon and make sure the core team
>> gets my recommendation when they discuss the results of the review.
>>
>> ---
>>
>> I'll respond to a few of the more intricate discussions tomorrow,
>> including the syntax of putting a new declaration inside the enum rather
>> than outside. Thank you again, everyone, and happy new year!
>>
>>
>> I ended up doing these in the opposite order, writing up the new proposal
>> first and not yet responding to the discussion that's further out. You can
>> read my revisions at https://github.com/apple/swift-evolution/pull/777.
>>
>> In particular, I want to at least address:
>> - Dave D and Drew C's points about versioned libraries / linking
>> semantics of modules.
>> - Jason M's point about migration
>> and I'll do one more pass over the thread to see if there's anything else
>> I didn't address directly. (That doesn't mean everyone who disagrees, just
>> messages where I think there's more I can do to explain why the proposal is
>> the way it is.)
>>
>> Jordan
>>
>> P.S. Enjoying the Disney references. Thanks, Nevin and Dave. :-)
>>
>> ___
>> swift-evolution mailing list
>> swift-evolution@swift.org
>> https://lists.swift.org/mailman/listinfo/swift-evolution
>>
>>
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [swift-evolution-announce] [Review] SE 0192 - Non-Exhaustive Enums

2018-01-03 Thread Xiaodi Wu via swift-evolution
This is a very nice revision. One bikeshedding thought:

Since "unknown case" is presented as a special kind of "default", can't be
mixed with "default", and can't be used in case patterns, why not "default
unknown" (or "unknown default") instead of "unknown case"?


On Wed, Jan 3, 2018 at 8:05 PM, Jordan Rose via swift-evolution <
swift-evolution@swift.org> wrote:

> On Jan 2, 2018, at 18:07, Jordan Rose  wrote:
>
> [Proposal: https://github.com/apple/swift-evolution/blob/
> master/proposals/0192-non-exhaustive-enums.md]
>
> Whew! Thanks for your feedback, everyone. On the lighter side of
> feedback—naming things—it seems that most people seem to like '*@frozen*',
> and that does in fact have the connotations we want it to have. I like it
> too.
>
> More seriously, this discussion has convinced me that it's worth including
> what the proposal discusses as a *'future' case*. The key point that
> swayed me is that this can produce a *warning* when the switch is missing
> a case rather than an *error,* which both provides the necessary compiler
> feedback to update your code and allows your dependencies to continue
> compiling when you update to a newer SDK. I know people on both sides won't
> be 100% satisfied with this, but does it seem like a reasonable compromise?
>
> The next question is how to spell it. I'm leaning towards `unexpected
> case:`, which (a) is backwards-compatible, and (b) also handles "private
> cases", either the fake kind that you can do in C (as described in the
> proposal), or some real feature we might add to Swift some day. `unknown
> case:` isn't bad either.
>
> I too would like to just do `unknown:` or `unexpected:` but that's
> technically a source-breaking change:
>
> switch foo {
> case bar:
>   unknown:
>   while baz() {
> while garply() {
>   if quux() {
> break unknown
>   }
> }
>   }
> }
>
>
> Another downside of the `unexpected case:` spelling is that it doesn't
> work as part of a larger pattern. I don't have a good answer for that one,
> but perhaps it's acceptable for now.
>
> I'll write up a revision of the proposal soon and make sure the core team
> gets my recommendation when they discuss the results of the review.
>
> ---
>
> I'll respond to a few of the more intricate discussions tomorrow,
> including the syntax of putting a new declaration inside the enum rather
> than outside. Thank you again, everyone, and happy new year!
>
>
> I ended up doing these in the opposite order, writing up the new proposal
> first and not yet responding to the discussion that's further out. You can
> read my revisions at https://github.com/apple/swift-evolution/pull/777.
>
> In particular, I want to at least address:
> - Dave D and Drew C's points about versioned libraries / linking semantics
> of modules.
> - Jason M's point about migration
> and I'll do one more pass over the thread to see if there's anything else
> I didn't address directly. (That doesn't mean everyone who disagrees, just
> messages where I think there's more I can do to explain why the proposal is
> the way it is.)
>
> Jordan
>
> P.S. Enjoying the Disney references. Thanks, Nevin and Dave. :-)
>
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [swift-evolution-announce] [Review] SE 0192 - Non-Exhaustive Enums

2018-01-02 Thread Xiaodi Wu via swift-evolution
On Tue, Jan 2, 2018 at 8:49 PM, Matthew Johnson <matt...@anandabits.com>
wrote:

>
> On Jan 2, 2018, at 8:45 PM, Xiaodi Wu via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> On Tue, Jan 2, 2018 at 8:07 PM, Jordan Rose via swift-evolution <
> swift-evolution@swift.org> wrote:
>
>> [Proposal: https://github.com/apple/swift-evolution/blob/mas
>> ter/proposals/0192-non-exhaustive-enums.md]
>>
>> Whew! Thanks for your feedback, everyone. On the lighter side of
>> feedback—naming things—it seems that most people seem to like '*@frozen*',
>> and that does in fact have the connotations we want it to have. I like it
>> too.
>>
>> More seriously, this discussion has convinced me that it's worth
>> including what the proposal discusses as a *'future' case*. The key
>> point that swayed me is that this can produce a *warning* when the
>> switch is missing a case rather than an *error,* which both provides the
>> necessary compiler feedback to update your code and allows your
>> dependencies to continue compiling when you update to a newer SDK. I know
>> people on both sides won't be 100% satisfied with this, but does it seem
>> like a reasonable compromise?
>>
>> The next question is how to spell it. I'm leaning towards `unexpected
>> case:`, which (a) is backwards-compatible, and (b) also handles "private
>> cases", either the fake kind that you can do in C (as described in the
>> proposal), or some real feature we might add to Swift some day. `unknown
>> case:` isn't bad either.
>>
>> I too would like to just do `unknown:` or `unexpected:` but that's
>> technically a source-breaking change:
>>
>> switch foo {
>> case bar:
>>   unknown:
>>   while baz() {
>> while garply() {
>>   if quux() {
>> break unknown
>>   }
>> }
>>   }
>> }
>>
>>
>> Another downside of the `unexpected case:` spelling is that it doesn't
>> work as part of a larger pattern. I don't have a good answer for that one,
>> but perhaps it's acceptable for now.
>>
>> I'll write up a revision of the proposal soon and make sure the core team
>> gets my recommendation when they discuss the results of the review.
>>
>> ---
>>
>> I'll respond to a few of the more intricate discussions tomorrow,
>> including the syntax of putting a new declaration inside the enum rather
>> than outside. Thank you again, everyone, and happy new year!
>>
>
> I do like this spelling of `@frozen`, and `unknown case` looks perfectly
> cromulent to me. If this is the path to go down, I'd urge more explicit
> design as to what happens when `unknown case` and `default` are mixed. I
> would imagine the most consistent design would be:
>
> `unknown case` should allow `default` to be omitted if the switch is
> otherwise exhaustive, obviously.
> `default` should allow `unknown case` to be omitted, just like any other
> case may then be omitted.
> `unknown case` before `default` should be allowed, just like any other
> case before `default`; in that case, only known cases not otherwise matched
> reach the `default`.
> `default` before `unknown case` makes the latter unreachable, just like
> any other case after `default`.
>
> The issue here remains that of testability. I wonder if, for such
> purposes, unknown case should be instantiable when testably imported, with
> some grammar. In its simplest and yet most exotic form, we could imagine
> code that testably imports the enum to be allowed to instantiate any
> made-up case whatsoever (e.g., `@testable import Foo.MyEnum; let x = MyEnum.
> asdfasdfasdfNonexistent`).
>
>
> What should happen when an unknown case instantiated via a testability
> mechanism is passed to the library that vended the enum (which is able to
> truly exhaustively switch over the enum)?  I would like to see a solution
> to the testability problem and answering this question seems to be the most
> difficult part of finding a solution.  The best answer is not obvious to me.
>

Indeed, you're quite right. And the whole notion is actually half-baked
because a @testable import should treat the enum as though internal and
therefore exhaustive.

It would appear, however, that testability would require the library itself
to handle unknown cases. That seems annoying but potentially justifiable.
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [swift-evolution-announce] [Review] SE 0192 - Non-Exhaustive Enums

2018-01-02 Thread Xiaodi Wu via swift-evolution
On Tue, Jan 2, 2018 at 8:07 PM, Jordan Rose via swift-evolution <
swift-evolution@swift.org> wrote:

> [Proposal: https://github.com/apple/swift-evolution/blob/
> master/proposals/0192-non-exhaustive-enums.md]
>
> Whew! Thanks for your feedback, everyone. On the lighter side of
> feedback—naming things—it seems that most people seem to like '*@frozen*',
> and that does in fact have the connotations we want it to have. I like it
> too.
>
> More seriously, this discussion has convinced me that it's worth including
> what the proposal discusses as a *'future' case*. The key point that
> swayed me is that this can produce a *warning* when the switch is missing
> a case rather than an *error,* which both provides the necessary compiler
> feedback to update your code and allows your dependencies to continue
> compiling when you update to a newer SDK. I know people on both sides won't
> be 100% satisfied with this, but does it seem like a reasonable compromise?
>
> The next question is how to spell it. I'm leaning towards `unexpected
> case:`, which (a) is backwards-compatible, and (b) also handles "private
> cases", either the fake kind that you can do in C (as described in the
> proposal), or some real feature we might add to Swift some day. `unknown
> case:` isn't bad either.
>
> I too would like to just do `unknown:` or `unexpected:` but that's
> technically a source-breaking change:
>
> switch foo {
> case bar:
>   unknown:
>   while baz() {
> while garply() {
>   if quux() {
> break unknown
>   }
> }
>   }
> }
>
>
> Another downside of the `unexpected case:` spelling is that it doesn't
> work as part of a larger pattern. I don't have a good answer for that one,
> but perhaps it's acceptable for now.
>
> I'll write up a revision of the proposal soon and make sure the core team
> gets my recommendation when they discuss the results of the review.
>
> ---
>
> I'll respond to a few of the more intricate discussions tomorrow,
> including the syntax of putting a new declaration inside the enum rather
> than outside. Thank you again, everyone, and happy new year!
>

I do like this spelling of `@frozen`, and `unknown case` looks perfectly
cromulent to me. If this is the path to go down, I'd urge more explicit
design as to what happens when `unknown case` and `default` are mixed. I
would imagine the most consistent design would be:

`unknown case` should allow `default` to be omitted if the switch is
otherwise exhaustive, obviously.
`default` should allow `unknown case` to be omitted, just like any other
case may then be omitted.
`unknown case` before `default` should be allowed, just like any other case
before `default`; in that case, only known cases not otherwise matched
reach the `default`.
`default` before `unknown case` makes the latter unreachable, just like any
other case after `default`.

The issue here remains that of testability. I wonder if, for such purposes,
unknown case should be instantiable when testably imported, with some
grammar. In its simplest and yet most exotic form, we could imagine code
that testably imports the enum to be allowed to instantiate any made-up
case whatsoever (e.g., `@testable import Foo.MyEnum; let x =
MyEnum.asdfasdfasdfNonexistent`).
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Review] SE 0192 - Non-Exhaustive Enums

2018-01-02 Thread Xiaodi Wu via swift-evolution
On Tue, Jan 2, 2018 at 8:25 PM, Matthew Johnson 
wrote:

>
> On Jan 2, 2018, at 3:41 PM, Xiaodi Wu  wrote:
>
> On Tue, Jan 2, 2018 at 3:27 PM, Kevin Nattinger 
> wrote:
>
>> [...]
>>
>> in what other circumstances do we insist that the compiler inform the end
>>> user about future additions to the API at compile time?
>>>
>>>
>>> This isn’t a request for the compiler to inform the user about future
>>> additions to an API.  It is a request to validate the compiler’s knowledge
>>> of the *current* state of an API with the *current* state of the source
>>> code.
>>>
>>
>> Well, it's of course impossible to inform the user about future
>> additions, so that's poorly phrased on my part. It's about the compiler
>> informing the end user about *new* additions, part of the *current* state
>> of the API, that have cropped up since the user last revised the code when
>> the API was in a *previous* state (or, indistinguishably, members of which
>> a user is unaware regardless of the temporal sequence of when such members
>> were added). In what other circumstances do we insist that the compiler
>> perform this service?
>>
>>
>> Enums. That's literally how they work today. You are arguing in favor of
>> actively removing compiler-aided correctness.
>>
>> There's also protocol requirements
>>
>
> No, that's now how enums work today, and it's not how protocol
> requirements work today. Enums today are all semantically exhaustive; if a
> case is added in a later version of a library, it's semantically a
> *different* enum type that happens to share the same name. Not considering
> all the cases of an exhaustive enum is an _error_, not a _warning_, because
> there is no basis on which to proceed. This will not change with the
> proposal. Likewise, adding a protocol requirement without a default
> implementation is source-breaking. The result is a compiler _error_.
>
> The question is, what non-source breaking API additions today cause the
> compiler to inform the end user of such additions?
>
>
> Posing the question this way takes it as a given that adding a case to a
> resilient enum is non-source breaking with a full stop.
>

Ah, yes. As I wrote in an earlier email in reply to Jon and others, it
seems we have a fundamental difference here. I take it as a given, full
stop, that this is what we are setting out to do. If it is not, then we are
trying to design with different end goals in mind.

The position of everyone asking for something like `future` / `unknown` as
> an alternative to `default` is exactly that this should not be the case.
> Instead, adding a case should always be binary compatible and should be
> source compatible by default, but authors should have the ability to opt-in
> to making case additions be source-breaking for individual switch
> statements.
>
> When you view it this way we are not asking the compiler to inform us of a
> non-source breaking addition.  We are asking the compiler to treat an
> addition as source breaking in a specific context.
>
> The answer is: none whatsoever. Not new methods or properties on a type,
> not even new protocol requirements that have a default implementation.
>
>
> and, arguably, deprecated methods with a proper message ("use foo
>> instead").
>>
>
>
>
>
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Review] SE 0192 - Non-Exhaustive Enums

2018-01-02 Thread Xiaodi Wu via swift-evolution
On Tue, Jan 2, 2018 at 7:02 PM, Goffredo Marocchi <pana...@gmail.com> wrote:

>
> On 3 Jan 2018, at 00:38, Xiaodi Wu via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> On Tue, Jan 2, 2018 at 4:31 PM, Jonathan Hull <jh...@gbis.com> wrote:
>
>> I think there are a couple of different definitions running around, and
>> that is confusing things.
>>
>> In my mind, ‘unexpected:’ catches only cases which were unknown at
>> compile time. Adding cases to an enum *should* be a source-breaking change.
>> That is the whole point of this.  We should have to update the switch
>> (either by handling new case explicitly, or by adding default) before
>> successfully compiling.  What ‘unexpected:’ protects against are changes to
>> a linked binary (e.g. iOS) that are now vending cases we didn’t know about
>> when we were compiled.
>>
>> I’ll say it again… framing this idea as one of exhaustiveness is really
>> confusing.  Enums should just always be exhaustive in swift.  There may be
>> cases where we need to use ‘unexpected:’ to handle unexpected/future cases
>> exhaustively.  If we annotate an enum as @frozen, then we won’t need to do
>> that to be exhaustive because we know it won’t change out from under us.
>> Always exhaustive. Much less confusing…
>>
>> Thanks,
>> Jon
>>
>
> I think, then, you fundamentally disagree with the starting premise of the
> proposal, which is specifically the addition of nonexhaustive enums to the
> language, and making them the default sort of enum so that adding cases *is
> not* a source-breaking change. If your whole purpose is to change the
> proposal so that adding cases will _always_ be a source-breaking change and
> enums are _never_ nonexhaustive, then I'm not sure how to proceed in the
> discussion as we're working towards diametrically opposite goals.
>
>
> The main issue is a resilience issue and it mainly affects binary
> frameworks the app links with at runtime and does not package them (read
> mostly Apple ones for the moment)... the fact that enum changes are source
> breaking is the whole entire point of swift’s enum and a best practice
> warning to always have turned on even before with Objective-C. Our goal,
> and yours goal should be the one and the same too IMHO, is not to throw the
> proverbial baby out with the bath water.
>
> We should look for a solution that allows what Apple and OS framework
> authors need and also what is best for app developers and if we need
> something to do this we pause this proposal until that something is ready
> and merged.
>
>
Hmm, I think indeed we disagree fundamentally on what this proposal is
about, or the desired end goal.

If I understand correctly, *your* end goal is simply to enable something
like `@_fixed_layout` for enums, an optimization hint to allow binary
frameworks to add cases without being shipped with apps. You want no
semantic changes to how enums work.

*My* understand of this proposals goal--and I support it--is that it takes
this ABI compatibility problem as a starting point and discovers that there
are fundamentally two semantic categories of enums, ones that are
necessarily exhaustive (there's either something or nothing for an Optional
value, there are three possible comparison results for comparable types,
there are four sides to a rectangular window, etc.) and ones that are not.
It discovers that, empirically, most enums are nonexhaustive, and proposes
changes to the grammar so that Swift distinguishes between these two so as
to prompt developers to deal with the issue of nonexhaustiveness where the
semantics require it. The goal, then, is to introduce new spellings and
semantics to distinguish between two different flavors of enum. Like `open`
vs. `public` for classes, this has implications for ABI compatibility but
isn't just about ABI compatibility.

I was laboring under the idea that we were working to make such a
wide-ranging change as ergonomic as possible, but it seems like you and Jon
do not want such a change at all.


> On Jan 2, 2018, at 1:41 PM, Xiaodi Wu via swift-evolution <
>> swift-evolution@swift.org> wrote:
>>
>> On Tue, Jan 2, 2018 at 3:27 PM, Kevin Nattinger <sw...@nattinger.net>
>> wrote:
>>
>>> [...]
>>>
>>> in what other circumstances do we insist that the compiler inform the
>>>> end user about future additions to the API at compile time?
>>>>
>>>>
>>>> This isn’t a request for the compiler to inform the user about future
>>>> additions to an API.  It is a request to validate the compiler’s knowledge
>>>> of the *current* state of an API with the *current* state of the
>>>> source code

Re: [swift-evolution] [Review] SE 0192 - Non-Exhaustive Enums

2018-01-02 Thread Xiaodi Wu via swift-evolution
On Tue, Jan 2, 2018 at 4:31 PM, Jonathan Hull <jh...@gbis.com> wrote:

> I think there are a couple of different definitions running around, and
> that is confusing things.
>
> In my mind, ‘unexpected:’ catches only cases which were unknown at compile
> time. Adding cases to an enum *should* be a source-breaking change. That is
> the whole point of this.  We should have to update the switch (either by
> handling new case explicitly, or by adding default) before successfully
> compiling.  What ‘unexpected:’ protects against are changes to a linked
> binary (e.g. iOS) that are now vending cases we didn’t know about when we
> were compiled.
>
> I’ll say it again… framing this idea as one of exhaustiveness is really
> confusing.  Enums should just always be exhaustive in swift.  There may be
> cases where we need to use ‘unexpected:’ to handle unexpected/future cases
> exhaustively.  If we annotate an enum as @frozen, then we won’t need to do
> that to be exhaustive because we know it won’t change out from under us.
> Always exhaustive. Much less confusing…
>
> Thanks,
> Jon
>

I think, then, you fundamentally disagree with the starting premise of the
proposal, which is specifically the addition of nonexhaustive enums to the
language, and making them the default sort of enum so that adding cases *is
not* a source-breaking change. If your whole purpose is to change the
proposal so that adding cases will _always_ be a source-breaking change and
enums are _never_ nonexhaustive, then I'm not sure how to proceed in the
discussion as we're working towards diametrically opposite goals.

On Jan 2, 2018, at 1:41 PM, Xiaodi Wu via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> On Tue, Jan 2, 2018 at 3:27 PM, Kevin Nattinger <sw...@nattinger.net>
> wrote:
>
>> [...]
>>
>> in what other circumstances do we insist that the compiler inform the end
>>> user about future additions to the API at compile time?
>>>
>>>
>>> This isn’t a request for the compiler to inform the user about future
>>> additions to an API.  It is a request to validate the compiler’s knowledge
>>> of the *current* state of an API with the *current* state of the source
>>> code.
>>>
>>
>> Well, it's of course impossible to inform the user about future
>> additions, so that's poorly phrased on my part. It's about the compiler
>> informing the end user about *new* additions, part of the *current* state
>> of the API, that have cropped up since the user last revised the code when
>> the API was in a *previous* state (or, indistinguishably, members of which
>> a user is unaware regardless of the temporal sequence of when such members
>> were added). In what other circumstances do we insist that the compiler
>> perform this service?
>>
>>
>> Enums. That's literally how they work today. You are arguing in favor of
>> actively removing compiler-aided correctness.
>>
>> There's also protocol requirements
>>
>
> No, that's now how enums work today, and it's not how protocol
> requirements work today. Enums today are all semantically exhaustive; if a
> case is added in a later version of a library, it's semantically a
> *different* enum type that happens to share the same name. Not considering
> all the cases of an exhaustive enum is an _error_, not a _warning_, because
> there is no basis on which to proceed. This will not change with the
> proposal. Likewise, adding a protocol requirement without a default
> implementation is source-breaking. The result is a compiler _error_.
>
> The question is, what non-source breaking API additions today cause the
> compiler to inform the end user of such additions? The answer is: none
> whatsoever. Not new methods or properties on a type, not even new protocol
> requirements that have a default implementation.
>
>
> and, arguably, deprecated methods with a proper message ("use foo
>> instead").
>>
>
>
> ___
> 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] [Review] SE 0192 - Non-Exhaustive Enums

2018-01-02 Thread Xiaodi Wu via swift-evolution
On Tue, Jan 2, 2018 at 3:27 PM, Kevin Nattinger  wrote:

> [...]
>
> in what other circumstances do we insist that the compiler inform the end
>> user about future additions to the API at compile time?
>>
>>
>> This isn’t a request for the compiler to inform the user about future
>> additions to an API.  It is a request to validate the compiler’s knowledge
>> of the *current* state of an API with the *current* state of the source
>> code.
>>
>
> Well, it's of course impossible to inform the user about future additions,
> so that's poorly phrased on my part. It's about the compiler informing the
> end user about *new* additions, part of the *current* state of the API,
> that have cropped up since the user last revised the code when the API was
> in a *previous* state (or, indistinguishably, members of which a user is
> unaware regardless of the temporal sequence of when such members were
> added). In what other circumstances do we insist that the compiler perform
> this service?
>
>
> Enums. That's literally how they work today. You are arguing in favor of
> actively removing compiler-aided correctness.
>
> There's also protocol requirements
>

No, that's now how enums work today, and it's not how protocol requirements
work today. Enums today are all semantically exhaustive; if a case is added
in a later version of a library, it's semantically a *different* enum type
that happens to share the same name. Not considering all the cases of an
exhaustive enum is an _error_, not a _warning_, because there is no basis
on which to proceed. This will not change with the proposal. Likewise,
adding a protocol requirement without a default implementation is
source-breaking. The result is a compiler _error_.

The question is, what non-source breaking API additions today cause the
compiler to inform the end user of such additions? The answer is: none
whatsoever. Not new methods or properties on a type, not even new protocol
requirements that have a default implementation.


and, arguably, deprecated methods with a proper message ("use foo instead").
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Review] SE 0192 - Non-Exhaustive Enums

2018-01-02 Thread Xiaodi Wu via swift-evolution
On Tue, Jan 2, 2018 at 1:46 PM, Matthew Johnson 
wrote:

>
>
> Sent from my iPad
>
> On Jan 2, 2018, at 12:48 PM, Xiaodi Wu  wrote:
>
> On Tue, Jan 2, 2018 at 9:38 AM, Matthew Johnson via swift-evolution <
> swift-evolution@swift.org> wrote:
>
>>
>>
>> Sent from my iPad
>>
>> On Jan 1, 2018, at 11:47 PM, Chris Lattner  wrote:
>>
>> On Dec 31, 2017, at 12:14 PM, Matthew Johnson via swift-evolution <
>> swift-evolution@swift.org> wrote:
>>
>> I agree that we need a solution to the problem described.  I also agree
>> that non-exhaustive is most in keeping with the overall design of Swift at
>> module boundaries.  However, I believe this proposal should be modified
>> before being accepted
>>
>>
>> Thanks for writing this up - you’ve explained a common concern in an
>> interesting way:
>>
>> This is likely to be a relatively rare need mostly encountered by 3rd
>> party libraries but it will happen.  When it does happen it would be really
>> unfortunate to be forced to use a `default` clause rather than something
>> like a `future` clause which will produce an error when compiled against an
>> SDK where the enum includes cases that are not covered.  I can imagine
>> cases where this catch-all case would need to do something *other than *abort
>> the program so I do not like the `switch!` suggestion that has been
>> discussed.  The programmer should still be responsible for determining the
>> behavior of unknown cases.
>>
>> ..
>>
>> While library authors have a legitimate need to reserve the right to
>> introduce new cases for some enums this need can be met without taking away
>> a useful tool for generating static compiler errors when code does not
>> align with intent (in this case, the intent being to cover all known
>> cases).  Switch statements working with these kinds of enums should be
>> required to cover unknown cases but should be able to do so while still
>> being statically checked with regards to known cases.
>>
>>
>> I think that this could be the crux of some major confusion, the root of
>> which is the difference between source packages and binary packages that
>> are updated outside your control (e.g. the OS, or a dynamic library that is
>> updated independently of your app like a 3rd party plugin).  Consider:
>>
>> 1) When dealing with independently updated binary packages, your code
>> *has* to implement some behavior for unexpected cases if the enum is
>> non-exhaustive.  It isn’t acceptable to not handle that case, and it isn’t
>> acceptable to abort because then your app will start crashing when a new OS
>> comes out. You have to build some sort of fallback into your app.
>>
>> 2) When dealing with a source package that contributes to your app (e.g.
>> through SwiftPM), *YOU* control when you update that package, and therefore
>> it is entirely reasonable to exhaustively handle enums even if that package
>> owner didn’t “intend” for them to be exhaustive.  When *you* chose to
>> update the package, you get the “unhandled case” error, and you have
>> maximal “knowability” about the package’s behavior.
>>
>>
>> It seems that your concern stems from the fact that the feature as
>> proposed is aligned around module boundaries, and therefore overly punishes
>> source packages like #2.  I hope you agree that in case #1, that the
>> feature as proposed is the right and only thing we can do: you really do
>> have to handle unknown future cases somehow.
>>
>> If I’m getting this right, then maybe there is a variant of the proposal
>> that ties the error/warning behavior to whether or not a module is a source
>> module vs a binary module.  The problem with that right now is that we have
>> no infrastructure in the language to know this…
>>
>>
>> Hi Chris, thanks for your reply.
>>
>> The concern you describe isn’t exactly what I was describing but it is
>> related.  John McCall recently posted a sketch of a solution to the concern
>> you describe which looked great to me.  I don’t have time to look up the
>> link this morning but I think it was in this review thread.
>>
>> The actual concern I am describing is where a 3rd party library (or app)
>> wants to switch over a non-exhaustive enum provided by a module that is a
>> binary (not source) dependency.  The author of the 3rd party library may
>> have a legitimate reason to switch over an enum despite the author of the
>> binary module reserving the right to add additional cases.
>>
>> When this circumstance arises they will do it using the tools provided by
>> the language.  Regardless of the final language solution they obviously
>> need to cover unknown cases - their library could be shipping on a device
>> which receives an update to the binary dependency that contains a new
>> case.  I agree with you that a language-defined crash is not appropriate.
>> The author of the switch must take responsibility for the behavior of
>> unknown cases.
>>
>> I am arguing that these 

Re: [swift-evolution] [Review] SE 0192 - Non-Exhaustive Enums

2018-01-02 Thread Xiaodi Wu via swift-evolution
On Tue, Jan 2, 2018 at 1:27 PM, Goffredo Marocchi <pana...@gmail.com> wrote:

> Hello all,
>
> On 2 Jan 2018, at 18:36, Xiaodi Wu via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> On Tue, Jan 2, 2018 at 12:11 PM, Jason Merchant via swift-evolution <
> swift-evolution@swift.org> wrote:
>
>> I think this whole thing has been unnecessarily convoluted. As a result,
>> the majority of the replies are rabbit holes.
>>
>> In my opinion, the true root of the concept in question is as follows:
>>
>> *A list of something is desired:*
>> 1 - Pancake
>> 2 - Waffle
>> 3 - Juice
>>
>> *Developer wishes to be able to:*
>> *A)* Add new things to the list of choices in the future as they come up
>> with new ideas
>> *B)* Sometimes select one of the choices to be chosen as the normal
>> choice if no choice is made by the user
>>
>> A and B are *separate desires*. In some circumstances a developer may
>> want to add a new choice and make it the normal choice when there was no
>> normal choice was clarified before.
>>
>
> I don't think this is an accurate summary of the problem being tackled
> here. Rather, we are how to enable the vendor of a nonexhaustive enum to
> add new cases without breaking binaries compiled against previous versions.
> There is little here to do with what a "default" should be. Indeed, it is
> an explicit design decision of Swift not to support types having an
> implicit default value.
>
>
> There is no way a library developer of libraries bundled in the app can
> break the app by adding new cases. They may cause compiler issues when the
> app author tries to update the library, but it will not break existing apps.
>
> The concern for updating enums is mostly an Apple / OS related concern for
> libraries/dynamic frameworks the app does not ship with, but links to at
> runtime and we should have an exception for that. We should not use the
> same solution for both and lose exhaustiveness checks when we do not need
> to. It would be wrong.
>

Right, this proposal is about enabling ABI stability and is about libraries
that don't ship with the app.

However, I disagree strongly with your point above. There should not be
dialects of Swift depending on how you link a framework. The point made
above is salient that there are, semantically, certain enums that are
exhaustive (for example, Optional, which can only have two cases), and
others that are nonexhaustive (for example, a list of foods, which will
never be complete).

Those dynamic frameworks should be the one that have to opt-in (even better
> if it is done automatically for them) in non-exhaustive extra resilient
> behaviour, not libraries you ship in the app.
>
> The app developer should be informed and have to address the new cases or
> the removal of old cases.
>
>
>
>> 
>>
>> *Part 2:*
>>
>> After this simple desire is clear, there should be two discussions:
>> *A)* In a text only coding language, what would we like the syntax to
>> look like? (Without regard to past-bias. What should it really be, forget
>> what mistaken design choices were made in Swift in the past)
>> *B)* How do we approach making this happen behind the scenes?
>>
>> *Bonus:* Given that some of us have changed our approach to programming
>> significantly beyond text based coding, and into more dynamic mediums of
>> programming in other niches, and even here and there in Xcode - I would
>> recommend considering how the IDE would show a modern version of this
>> concept. I feel too often that Swift design syntax has a *lack of
>> awareness between the distinctions of what the IDE should do, as opposed to
>> what the syntax of the language should be*, and what should be handled
>> behind the scenes by automated tooling.
>>
>> _
>>
>> *My opinion*, in answering the above questions is in preference to a
>> simple easy to read and write syntax, something like the following:
>>
>> choices Breakfast {
>> Pancake, *Waffle*, Juice
>> }
>>
>> If a "default" choice is desired, it is obvious to me that I would select
>> the choice from the IDE, and it would be visually indicated that it was the
>> default.
>>
>> When changes occur, whether new choices are added, old ones are removed
>> or changed, or a default is added, changed, or removed - a behind the
>> scenes automated tool analyzes the changes and presents migration options
>> through the IDE.
>>
>> _
>>
>> Sincerely,
>> Jason
>>
>>
>>>
>>
>> ___
>> 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] [swift-evolution-announce] [REVIEW] SE-0193 - Cross-module inlining and specialization

2018-01-02 Thread Xiaodi Wu via swift-evolution
On Fri, Dec 22, 2017 at 11:12 PM, Slava Pestov  wrote:

>
>
> On Dec 22, 2017, at 7:09 PM, Xiaodi Wu  wrote:
>
> On Fri, Dec 22, 2017 at 6:12 PM, Chris Lattner 
> wrote:
>
>>
>> On Dec 22, 2017, at 1:03 PM, Xiaodi Wu  wrote:
>>
>> In short, respectfully request that you at least add this approach to the
>>> "alternatives considered” section.
>>>
>>>
>>> So, does anyone have any strong objections to Chris’s proposal?
>>>
>>> From an implementation standpoint, reworking the parser to parse
>>> @available(inlinable) and @available(fixedContents) or whatever would be
>>> straightforward. I would still like to punt the version range part of this
>>> to a future proposal, though.
>>>
>>>
>> I wish I had more time to compose a fully thought-out reply, but that's
>> not going to happen in a little while because of outside constraints, so
>> I'll spill a few thoughts here:
>>
>>
>> No rush, no worries, enjoy the holiday!
>>
>> I'm not a great fan of the @available(inlinable) notation.
>>
>> For one, I have a hard time reasoning how Swift would behave when
>> inlinability is tied to OS version. In this example, if the *app* (as
>> opposed to the library) is compiled (as opposed to run) on iOS 16+, then
>> the *library method* would potentially be emitted into the app, but if
>> compiled on iOS 15 it wouldn't? Huh?
>>
>>
>> No: availability information kicks in based on what you are *deploying*
>> to, not what you’re compiling on.
>>
>> I expect that this stuff will be extremely rarely used in practice, but
>> here’s an example:
>>
>> iOS15 declares this public:
>>
>> public void foo() {
>>bar()
>> }
>>
>> iOS16 wants to promote foo to inlinable, but knows that the inlined body
>> doesn’t work with iOS15, because iOS15 needs the call to bar to happen (for
>> whatever reason)
>>
>> @available(inlinable: iOS16)
>> public void foo() {
>>
>> // nothing needed on iOS16 or later.
>>
>> }
>>
>
> Deployment platform makes more sense, but I still can't envision a real
> use case. What sorts of `bar()` would hypothetically be necessary for iOS
> 15 but not 16? Why would a third-party library need to increase its
> inlining availability for an app based on deployment platform?
>
>
> A better example would be if bar() was itself only available in iOS 16:
>
> @available(iOS 15)
> @available(inlinable: iOS 16)
> public func foo() {
>   bar()
> }
>
> @available(iOS 16)
> public func bar() { … }
>
> Suppose your app calls foo() and deploys to iOS 15. Then you cannot inline
> foo(), because bar() does not exist on iOS 15. (Presumably, foo() had a
> different implementation on iOS 15). But if you’re deploying to iOS 16, all
> is well, and you can inline foo(), which results in your app directly
> calling bar().
>
> I'm quite sure that the reason you inverted your "abiPublic" example is
> because of the same issue. Intuitively, you would want to mark something as
> "available" in version N and then maybe some special kind of "available" in
> version N+1 (which @available(inlinable) would be). But
> @available(linkerSymbol), as you spell it, suffers from a similar problem
> to that of @available(unavailable): it's _not_ a special kind of API
> availability, but rather indicates that something is less-than-available.
> That is, you would use it to indicate that something is available as ABI
> but not as API. In that sense, it extends the "mess" we have with
> @available(unavailable).
>
>
> I don’t think it’s quite the same thing as @available(unavailable). An
> @available(abiPublic) symbol would still be declared to have internal
> visibility, so in this case the @available attribute makes it strictly more
> visible than it would be without. We’re not going to spell it as
> ‘@available(abiPublic) public’, which indeed would be confusing because the
> symbol is not actually public at the source level.
>

In Chris's example, it's an annotation of a public API that was once
internal in a previous version:

  @available(apiPublic: iOS 14)
  @available(iOS 15)
  @available(inlinable: iOS 16)
  public func foo() { ... }

This is a sensible use, but it shows how we get to exactly the "indeed
confusing" situation you write about above: here, @available(apiPublic)
elevates the API above internal but below public *even when it annotates a
public API*.
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Review] SE 0192 - Non-Exhaustive Enums

2018-01-02 Thread Xiaodi Wu via swift-evolution
On Tue, Jan 2, 2018 at 9:38 AM, Matthew Johnson via swift-evolution <
swift-evolution@swift.org> wrote:

>
>
> Sent from my iPad
>
> On Jan 1, 2018, at 11:47 PM, Chris Lattner  wrote:
>
> On Dec 31, 2017, at 12:14 PM, Matthew Johnson via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> I agree that we need a solution to the problem described.  I also agree
> that non-exhaustive is most in keeping with the overall design of Swift at
> module boundaries.  However, I believe this proposal should be modified
> before being accepted
>
>
> Thanks for writing this up - you’ve explained a common concern in an
> interesting way:
>
> This is likely to be a relatively rare need mostly encountered by 3rd
> party libraries but it will happen.  When it does happen it would be really
> unfortunate to be forced to use a `default` clause rather than something
> like a `future` clause which will produce an error when compiled against an
> SDK where the enum includes cases that are not covered.  I can imagine
> cases where this catch-all case would need to do something *other than *abort
> the program so I do not like the `switch!` suggestion that has been
> discussed.  The programmer should still be responsible for determining the
> behavior of unknown cases.
>
> ..
>
> While library authors have a legitimate need to reserve the right to
> introduce new cases for some enums this need can be met without taking away
> a useful tool for generating static compiler errors when code does not
> align with intent (in this case, the intent being to cover all known
> cases).  Switch statements working with these kinds of enums should be
> required to cover unknown cases but should be able to do so while still
> being statically checked with regards to known cases.
>
>
> I think that this could be the crux of some major confusion, the root of
> which is the difference between source packages and binary packages that
> are updated outside your control (e.g. the OS, or a dynamic library that is
> updated independently of your app like a 3rd party plugin).  Consider:
>
> 1) When dealing with independently updated binary packages, your code
> *has* to implement some behavior for unexpected cases if the enum is
> non-exhaustive.  It isn’t acceptable to not handle that case, and it isn’t
> acceptable to abort because then your app will start crashing when a new OS
> comes out. You have to build some sort of fallback into your app.
>
> 2) When dealing with a source package that contributes to your app (e.g.
> through SwiftPM), *YOU* control when you update that package, and therefore
> it is entirely reasonable to exhaustively handle enums even if that package
> owner didn’t “intend” for them to be exhaustive.  When *you* chose to
> update the package, you get the “unhandled case” error, and you have
> maximal “knowability” about the package’s behavior.
>
>
> It seems that your concern stems from the fact that the feature as
> proposed is aligned around module boundaries, and therefore overly punishes
> source packages like #2.  I hope you agree that in case #1, that the
> feature as proposed is the right and only thing we can do: you really do
> have to handle unknown future cases somehow.
>
> If I’m getting this right, then maybe there is a variant of the proposal
> that ties the error/warning behavior to whether or not a module is a source
> module vs a binary module.  The problem with that right now is that we have
> no infrastructure in the language to know this…
>
>
> Hi Chris, thanks for your reply.
>
> The concern you describe isn’t exactly what I was describing but it is
> related.  John McCall recently posted a sketch of a solution to the concern
> you describe which looked great to me.  I don’t have time to look up the
> link this morning but I think it was in this review thread.
>
> The actual concern I am describing is where a 3rd party library (or app)
> wants to switch over a non-exhaustive enum provided by a module that is a
> binary (not source) dependency.  The author of the 3rd party library may
> have a legitimate reason to switch over an enum despite the author of the
> binary module reserving the right to add additional cases.
>
> When this circumstance arises they will do it using the tools provided by
> the language.  Regardless of the final language solution they obviously
> need to cover unknown cases - their library could be shipping on a device
> which receives an update to the binary dependency that contains a new
> case.  I agree with you that a language-defined crash is not appropriate.
> The author of the switch must take responsibility for the behavior of
> unknown cases.
>
> I am arguing that these “pseudo-exhaustive” switch statements *will*
> exist in the wild.  The crucial point of contention is whether or not the
> language provides assistance to the author of the 3rd party library in
> updating their library when the enum provided by the binary dependency
> changes.  Is 

Re: [swift-evolution] [Review] SE 0192 - Non-Exhaustive Enums

2018-01-02 Thread Xiaodi Wu via swift-evolution
On Tue, Jan 2, 2018 at 12:11 PM, Jason Merchant via swift-evolution <
swift-evolution@swift.org> wrote:

> I think this whole thing has been unnecessarily convoluted. As a result,
> the majority of the replies are rabbit holes.
>
> In my opinion, the true root of the concept in question is as follows:
>
> *A list of something is desired:*
> 1 - Pancake
> 2 - Waffle
> 3 - Juice
>
> *Developer wishes to be able to:*
> *A)* Add new things to the list of choices in the future as they come up
> with new ideas
> *B)* Sometimes select one of the choices to be chosen as the normal
> choice if no choice is made by the user
>
> A and B are *separate desires*. In some circumstances a developer may
> want to add a new choice and make it the normal choice when there was no
> normal choice was clarified before.
>

I don't think this is an accurate summary of the problem being tackled
here. Rather, we are how to enable the vendor of a nonexhaustive enum to
add new cases without breaking binaries compiled against previous versions.
There is little here to do with what a "default" should be. Indeed, it is
an explicit design decision of Swift not to support types having an
implicit default value.


> 
>
> *Part 2:*
>
> After this simple desire is clear, there should be two discussions:
> *A)* In a text only coding language, what would we like the syntax to
> look like? (Without regard to past-bias. What should it really be, forget
> what mistaken design choices were made in Swift in the past)
> *B)* How do we approach making this happen behind the scenes?
>
> *Bonus:* Given that some of us have changed our approach to programming
> significantly beyond text based coding, and into more dynamic mediums of
> programming in other niches, and even here and there in Xcode - I would
> recommend considering how the IDE would show a modern version of this
> concept. I feel too often that Swift design syntax has a *lack of
> awareness between the distinctions of what the IDE should do, as opposed to
> what the syntax of the language should be*, and what should be handled
> behind the scenes by automated tooling.
>
> _
>
> *My opinion*, in answering the above questions is in preference to a
> simple easy to read and write syntax, something like the following:
>
> choices Breakfast {
> Pancake, *Waffle*, Juice
> }
>
> If a "default" choice is desired, it is obvious to me that I would select
> the choice from the IDE, and it would be visually indicated that it was the
> default.
>
> When changes occur, whether new choices are added, old ones are removed or
> changed, or a default is added, changed, or removed - a behind the scenes
> automated tool analyzes the changes and presents migration options through
> the IDE.
>
> _
>
> Sincerely,
> Jason
>
>
>>
>
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


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

2018-01-02 Thread Xiaodi Wu via swift-evolution
On Tue, Jan 2, 2018 at 10:19 AM, Dave DeLong via swift-evolution <
swift-evolution@swift.org> wrote:

> Just skimmed through the updated proposal and am weighing in with my naïve
> opinions:
>
>
>- I’m still highly skeptical of a static “T.random” API. I’ve yet to
>see a convincing example where it’d be useful to pick a value from the
>range of all possible values. The only truly useful one I’ve seen is “pick
>a random bool”, which could easily be done via “[true, false].random()"
>
>- I much prefer the GameplayKit API[0], which breaks the idea of
>randomness up in to 2 separate concepts:
>   - A “Source” → Where the random numbers come from
>   - A “Distribution” → Initialized with a source, it makes sure the
>   produced numbers exhibit a specific distribution over multiple 
> samplings.
>   Ie, a uniform distribution vs a Gaussian distribution, or something 
> like “I
>   want to pick a card from a deck but bias choices towards Spades or 
> Aces”.
>   I’m also reminded of the anecdote of how iTunes had to modify their
>   “playlist shuffle” algorithm to be less random[1], because the true
>   randomness would do weird things that made it seem not random. Spotify 
> had
>   the same problem and solution[2].
>   - Breaking things up like this would also make it easier to test
>   randomness (by using a replay-able source) but that still follow the
>   parameters of your app (that it has a bell-curve distribution of
>   probabilities, for example)
>
>   - I’d still really really really like to see how this could be done
>as two separate things:
>   - A minimal implementation in the Standard Library (like, defining
>   the base Source and Distribution protocols, with a single default
>   implementation of each)
>   - A proposal for a more complete “non-standard library” where the
>   larger array of functionality would be contained. For example, IMO I 
> don’t
>   think the shuffling stuff needs to be in the standard library. This is 
> also
>   where all the cryptographically secure stuff (that your typical app
>   developer does not need) would live.
>
>   - The “random” element of a collection/range should be “func
>random() → Element?”, not “var random: Element?”. Property values shouldn't
>change between accesses. Ditto the static “Randomizable.random” property.
>
>- What do you think about actively discouraging people from using the
>modulo operator to create a range? It could be done by having the RNGs
>return a “RandomValue” type, then defining a mod operator that takes a
>RandomValue and a T (?), and then giving it a deprecation warning +
>fixit. Not sure if that’d be worth the type overhead, but I’m very much in
>favor of encouraging people towards better practices.
>
>- I’m +1 on crashing if we can’t produce a random number.
>
>- What do you think about the philosophical difference of
>Type.random(using:) vs Type.init(randomSource:)?
>
>
> Dave
>
> [0]: https://developer.apple.com/documentation/gameplaykit/gkrandom
> [1]: https://www.youtube.com/watch?v=lg188Ebas9E=youtu.be=719
> [2]: https://labs.spotify.com/2014/02/28/how-to-shuffle-songs/
>
>

I think these are some excellent points. Earlier, I think, others also
emphasized this idea of exploring what a really minimal implementation in
the standard library would look like, and I've been thinking about this
overnight.

There is much that is commendable about Alejandro's proposal, but I agree
that there is more than needs to be in the standard library. Here's what I
think the shape of a minimal API would look like, which would
simultaneously enable others to implement their desired functionality as an
end user:

- We need very performant, but otherwise barebones, access to system
randomness so that it can be a building block for everything else. Because
this is so special in that it cannot be seeded or initialized, unlike other
RNGs, we don't need this to be a type, and it doesn't need to conform to a
`RandomNumberGenerator` protocol. It can be as straightforward as one or
both of:

-- A global `func random() -> UInt32`, which is essentially `arc4random` on
macOS/iOS and reads from an appropriate secure source on Linux and other
platforms. One pro of having such a method is that it's a drop-in
replacement for `arc4random()` that's _very_ convenient as a primitive to
build up other random operations; one con is that it encourages modulo
bias, although fortunately mostly only with UInt32.
-- An extension method on `UnsafeMutableRawBufferPointer` named `func
copyRandomBytes()`. This would look a lot like Apple's `SecCopyRandomBytes`
and BSD's `arc4random_buf`.

- Having established the primitive, then we can ask what is the minimum
_useful_ functionality for an end user. I think the answer is a very
judicious subset of the currently proposed functionality:

-- An extension method or 

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

2018-01-02 Thread Xiaodi Wu via swift-evolution
On Tue, Jan 2, 2018 at 2:35 AM, Alejandro Alonso via swift-evolution <
swift-evolution@swift.org> wrote:

> Hello swift evolution once again, I’ve been hard at work considering every
> email and revising the proposal. I’ve made lots of changes and additions to
> the proposal to discuss some problems we’ve had (T.random), and walks
> through detailed design. You can see the proposal here:
> https://github.com/apple/swift-evolution/pull/760 .
>
> A big issue that lots of people pointed out was `T.random %` and to remove
> it completely from the API. To give a gist of why I continue to support
> T.random:
>
> 1. Modulo bias misuse is only a problem to types that conform to
> `BinaryInteger`. Why remove this functionality if only a portion of the
> types have the ability of misuse. `Double.random % 10` is a good example of
> where modulo isn’t implemented here as it produces the error, “'%' is
> unavailable: Use truncatingRemainder instead”.
>
> 2. `Int.random(in: Int.min … Int.max)` doesn’t work. For developers that
> actually rely on this functionality, the work around that was discussed
> earlier simply doesn’t work. `Int.min … Int.max`’s count property exceeds
> that of `Int`’s numerical range. A working work around would be something
> along the lines of `Int(truncatingIfNeeded: Random.default.next(UInt.self))`
> which creates a pain point for those developers. As the goal of this
> proposal to remove pain points regarding random, this change does the
> opposite.
>
> I’m interested to hear if anymore discussion around this, or any other
> issues come up.
>

There is no reason why `(Int.min...Int.max).random` (as I believe the
consensus suggestion was) "doesn't work." Certainly, it doesn't work if you
write only a default implementation on Collection. But `Range where Bound :
FixedWidthInteger & SignedInteger` should have its own implementation of
`random` anyway (for performance reasons, if nothing else) and there is no
impediment to a working implementation.

As to your first point: as evidenced by concrete data given by others
above, the overwhelming majority of uses of `random %` appear to be
erroneous, and of course the great majority of uses of `T.random` will be
on types that conform to `BinaryInteger`. Again, I repeat my concern that
you are naming multiple distinct things "random", which is making it
difficult to carry on this discussion. `BinaryInteger.random` is distinct
in its semantics, and this is precisely the method that is often used and
often misused. There is no reason why other things that you name "random"
shouldn't exist just because `BinaryInteger` shouldn't have a method named
`random`, and it's spurious to say "why remove this functionality if only a
portion of the types have the ability of misuse," when this _functionality_
and its misuse are specific to `BinaryInteger`.


On Sep 8, 2017, 11:52 AM -0500, Alejandro Alonso via swift-evolution <
> swift-evolution@swift.org>, wrote:
>
> Hello swift evolution, I would like to propose a unified approach to
> `random()` in Swift. I have a simple implementation here
> https://gist.github.com/Azoy/5d294148c8b97d20b96ee64f434bb4f5. This
> implementation is a simple wrapper over existing random functions so
> existing code bases will not be affected. Also, this approach introduces a
> new random feature for Linux users that give them access to upper bounds,
> as well as a lower bound for both Glibc and Darwin users. This change would
> be implemented within Foundation.
>
> I believe this simple change could have a very positive impact on new
> developers learning Swift and experienced developers being able to write
> single random declarations.
>
> I’d like to hear about your ideas on this proposal, or any implementation
> changes if need be.
>
> - Alejando
>
>
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] why cant you initialize BinaryFloatingPoint from BinaryInteger?

2018-01-01 Thread Xiaodi Wu via swift-evolution
This would be a good addition to the BinaryFloatingPoint protocol. It's not
difficult to implement; it's not present (afaict) simply because
BinaryFloatingPoint was designed before BinaryInteger existed.


On Mon, Jan 1, 2018 at 3:58 PM, Kelvin Ma via swift-evolution <
swift-evolution@swift.org> wrote:

> title says it all,, this is kind of annoying when writing some generic
> FloatingPoint code where both the integral and floating parameters are
> unfixed.
>
> ___
> 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] [swift-evolution-announce] [REVIEW] SE-0193 - Cross-module inlining and specialization

2017-12-22 Thread Xiaodi Wu via swift-evolution
On Fri, Dec 22, 2017 at 6:12 PM, Chris Lattner  wrote:

>
> On Dec 22, 2017, at 1:03 PM, Xiaodi Wu  wrote:
>
> In short, respectfully request that you at least add this approach to the
>> "alternatives considered” section.
>>
>>
>> So, does anyone have any strong objections to Chris’s proposal?
>>
>> From an implementation standpoint, reworking the parser to parse
>> @available(inlinable) and @available(fixedContents) or whatever would be
>> straightforward. I would still like to punt the version range part of this
>> to a future proposal, though.
>>
>>
> I wish I had more time to compose a fully thought-out reply, but that's
> not going to happen in a little while because of outside constraints, so
> I'll spill a few thoughts here:
>
>
> No rush, no worries, enjoy the holiday!
>
> I'm not a great fan of the @available(inlinable) notation.
>
> For one, I have a hard time reasoning how Swift would behave when
> inlinability is tied to OS version. In this example, if the *app* (as
> opposed to the library) is compiled (as opposed to run) on iOS 16+, then
> the *library method* would potentially be emitted into the app, but if
> compiled on iOS 15 it wouldn't? Huh?
>
>
> No: availability information kicks in based on what you are *deploying*
> to, not what you’re compiling on.
>
> I expect that this stuff will be extremely rarely used in practice, but
> here’s an example:
>
> iOS15 declares this public:
>
> public void foo() {
>bar()
> }
>
> iOS16 wants to promote foo to inlinable, but knows that the inlined body
> doesn’t work with iOS15, because iOS15 needs the call to bar to happen (for
> whatever reason)
>
> @available(inlinable: iOS16)
> public void foo() {
>
> // nothing needed on iOS16 or later.
>
> }
>

Deployment platform makes more sense, but I still can't envision a real use
case. What sorts of `bar()` would hypothetically be necessary for iOS 15
but not 16? Why would a third-party library need to increase its inlining
availability for an app based on deployment platform?

The vastly most common case is that something is defined as inlinable and
> always inlinable, that’s why the @available(inlinable) form is important,
> and why it may make sense to further sugar that default case to @inlinable.
>
>
> Second--and perhaps this is not a common opinion--I've always thought that
> the @available notation was disastrous in terms of readability, especially
> when it comes to @available(unavailable) and the meaning of the asterisk.
> Every time, I have to run and look up whether it means the method is in
> fact available or unavailable for non-listed platforms. Again, with the
> understanding that this is not a fully formed thought, I have to say that I
> feel this is taking a readable and fairly straightforward concept
> (@inlinable) and adding on too many layers of baggage. That it was easy for
> Swift's creator to inadvertently invert the intended annotations in his
> initial example is, to me, a pretty good demonstration that the notation is
> not at all user-friendly.
>
>
> I agree that @available(unavailable) is a mess, this direction doesn’t
> make it worse though.
>
> However, the thing I inverted wasn’t the syntax, it was the “abipublic”
> example.  abipublic is a confusing concept no matter how it is spelled.
>

I understand. I was writing about the "abiPublic" example as well, and I
mentioned @available(unavailable) for precisely that reason:

The mess inherent to @available(unavailable) doesn't stem purely from
inelegance in spelling. Rather, @available(anything) looks as though the
"anything" should be a particular kind of API availability, but
@available(unavailable) is _not_ a kind of API availability but precisely
the opposite: unavailability.

I'm quite sure that the reason you inverted your "abiPublic" example is
because of the same issue. Intuitively, you would want to mark something as
"available" in version N and then maybe some special kind of "available" in
version N+1 (which @available(inlinable) would be). But
@available(linkerSymbol), as you spell it, suffers from a similar problem
to that of @available(unavailable): it's _not_ a special kind of API
availability, but rather indicates that something is less-than-available.
That is, you would use it to indicate that something is available as ABI
but not as API. In that sense, it extends the "mess" we have with
@available(unavailable).
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [swift-evolution-announce] [REVIEW] SE-0193 - Cross-module inlining and specialization

2017-12-22 Thread Xiaodi Wu via swift-evolution
On Fri, Dec 22, 2017 at 2:08 AM, Slava Pestov via swift-evolution <
swift-evolution@swift.org> wrote:

> Hi Chris,
>
> Thanks for reviewing the proposal!
>
> On Dec 20, 2017, at 11:14 PM, Chris Lattner via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> On Dec 20, 2017, at 4:19 PM, Ted Kremenek  wrote:
>
> The review of "SE-0193 - Cross-module inlining and specialization" begins
> now and runs through *January 5, 2018*.
>
> The proposal is available here:
>
> https://github.com/apple/swift-evolution/blob/master/
> proposals/0193-cross-module-inlining-and-specialization.md
>
> When reviewing a proposal, here are some questions to consider:
>
>-
>
>What is your evaluation of the proposal?
>
> I am hugely supportive of the features that these attributes enable, but I
> think that the spelling of this is absolutely wrong, and I’m disappointed
> that the extensive discussion we’ve had for months about this didn’t make
> it into (at least) the alternatives considered section.  Here are my
> concerns:
>
>
> I’m totally aware of your earlier e-mail thread about tying this in with
> availability and I briefly mentioned it in the ‘future directions’ section.
> I don’t have any objections to your approach and I’d be open to changing
> the proposal if there’s some consensus that this is the right way to go.
>
> Do you think exhaustive enums should be spelled as @available(exhaustive)
> (or @available(exhaustive: …)), also?
>
> Furthermore, these two attributes are the tip of the iceberg, and the core
> team has spent a lot of time recently discussing the fact there are
> potentially going to be about a dozen attributes similar to these
> (fixed_contents,  global_var_is_directly_addressible, …)  that will only
> be required for binary frameworks.
>
>
> Hopefully not a dozen! But yes, there will probably be more than just the
> three currently under discussion.
>
> A minor point, but the specific name “abiPublic” is not great in my
> opinion, because “ABI” is a term of art for compiler hackers.  Most users
> have no idea what ABI means, and those who think they do often don’t.  Very
> few people really understand what “stable ABI” means for example.
>
> It would be better to go with something like “apiPublic” or “symbolPublic”
> or “linkableButNotAccessible” or something else long.  This will not be
> commonly used in user code, so being long and descriptive is a good thing.
>
>
> Several other people in the thread also objected to the name abiPublic.
> I’m not attached to it and I would be open to changing it to something
> better. We just don’t have a clear winner yet...
>
> which generalizes properly when we add version ranges:
>
> @available(iOS 14, *)   // this was introduced in iOS 14
> @available(linkerSymbol: iOS 15, *)  // this decl’s symbol became
> “abiPublic" in iOS 15
> @available(inlinable: iOS 16, *)  // this decl became inlinable in iOS 16
> public func foo() {… }
>
>
> Minor nitpick: public implies ABI-public, so you probably meant the other
> way around, where a symbol became ABI public in iOS 14, then public in iOS
> 15. This is certainly something we need to support and my understanding is
> the equivalent already happens all the time in Objective-C land, where SPI
> becomes API.
>
> In short, respectfully request that you at least add this approach to the
> "alternatives considered” section.
>
>
> So, does anyone have any strong objections to Chris’s proposal?
>
> From an implementation standpoint, reworking the parser to parse
> @available(inlinable) and @available(fixedContents) or whatever would be
> straightforward. I would still like to punt the version range part of this
> to a future proposal, though.
>
>
I wish I had more time to compose a fully thought-out reply, but that's not
going to happen in a little while because of outside constraints, so I'll
spill a few thoughts here:

I'm not a great fan of the @available(inlinable) notation.

For one, I have a hard time reasoning how Swift would behave when
inlinability is tied to OS version. In this example, if the *app* (as
opposed to the library) is compiled (as opposed to run) on iOS 16+, then
the *library method* would potentially be emitted into the app, but if
compiled on iOS 15 it wouldn't? Huh?

Second--and perhaps this is not a common opinion--I've always thought that
the @available notation was disastrous in terms of readability, especially
when it comes to @available(unavailable) and the meaning of the asterisk.
Every time, I have to run and look up whether it means the method is in
fact available or unavailable for non-listed platforms. Again, with the
understanding that this is not a fully formed thought, I have to say that I
feel this is taking a readable and fairly straightforward concept
(@inlinable) and adding on too many layers of baggage. That it was easy for
Swift's creator to inadvertently invert the intended annotations in his
initial example is, to me, a pretty good demonstration that 

Re: [swift-evolution] [REVIEW] SE-0193 - Cross-module inlining and specialization

2017-12-20 Thread Xiaodi Wu via swift-evolution
On Wed, Dec 20, 2017 at 18:19 Ted Kremenek via swift-evolution <
swift-evolution@swift.org> wrote:

> The review of "SE-0193 - Cross-module inlining and specialization" begins
> now and runs through *January 5, 2018*.
>
> The proposal is available here:
>
>
> https://github.com/apple/swift-evolution/blob/master/proposals/0193-cross-module-inlining-and-specialization.md
>
> Reviews are an important part of the Swift evolution process. All review
> feedback should be sent to the swift-evolution mailing list at:
>
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
> or, if you would like to keep your feedback private, directly to the
> review manager.
>
> When replying, please try to keep the proposal link at the top of the
> message:
>
> Proposal link:
> https://github.com/apple/swift-evolution/blob/master/proposals/0193-cross-module-inlining-and-specialization.md
> ...
> Reply text
> ...
> Other replies
>
> What goes into a review of a proposal?
>
> The goal of the review process is to improve the proposal under review
> through constructive criticism and, eventually, determine the direction of
> Swift.
>
> When reviewing a proposal, here are some questions to consider:
>
>-
>
>What is your evaluation of the proposal?
>
>
I have been doing the unkosher thing of using these underscored attributes
and would very much like to see these formalized.

My one bikeshedding issue here is the name @abiPublic, which smells too
much like fileprivate in my subjective opinion. A more concrete objection
here is the very much non-ideal juxtaposition of two different access
modifier terms in the "@abiPublic internal" spelling. It would seem to me
that "@abi" would suffice instead. Indeed, the fact that it's an
"interface" implies a certain level of visibility, which in my view is more
precise than coopting the term "public"--that term in turn has an
established meaning in Swift that, by construction, an "@abiPublic
internal" method does not fulfill.


>- Is the problem being addressed significant enough to warrant a
>change to Swift?
>
>
Yes, we need this.


>- Does this proposal fit well with the feel and direction of Swift?
>
>
Yes, with a caveat. It seems a little unfortunate that @inline(never) is
spelled so differently from @inlinable. Probably too late to rename the
former @noninlinable though. It'd be lovely though.


>- If you have used other languages or libraries with a similar
>feature, how do you feel that this proposal compares to those?
>
>
Not really, no.


>- How much effort did you put into your review? A glance, a quick
>reading, or an in-depth study?
>
>
I have used the underscored feature already, and I have read the document.

Thanks,
> Ted Kremenek
> Review Manager
>
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


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

2017-12-20 Thread Xiaodi Wu via swift-evolution
On Wed, Dec 20, 2017 at 13:13 Jens Persson <j...@bitcycle.com> wrote:

> Oh OK, I must have misunderstood this thread:
>
> https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20171204/042034.html
> (
> "The strong opinion of the core team is that such an API should *not* be
> designed with an attempt to service people writing crypto code."
> "It is general goodness if generality for crypto use cases somehow falls
> out of the design.  However, the design for general use shouldn’t suffer
> because of that goal."
> )
>
> I assumed that the Random API would save the user from the trouble of
> making a good choice and implementation (fast and good quality) of a
> "standard" general purpose prng (as well as maybe a cryptographically
> secure one).
>

Providing a cryptographically secure PRNG is necessary but not sufficient
for cryptography. However, many ordinary uses of a general purpose PRNG
will assume that future “random” numbers cannot be guessed by observing a
small number of previous ones. Xoroshiro has its uses, but it would not be
the ideal basis for a general purpose PRNG, especially since we have easy
access to true randomness.

Also, the most commonly recommended ways of converting from eg 64 random
> bits to an int range or a floating point range are unnecessarily bad and
> slow, so I figured the webpage was worth a read, in addition to C++
> stdlib's implementation.
>

I agree it will be critical to ensure that random floating-point values are
truly uniform. All implementors would do well to study the state of the art.


> /Jens
>
>
> On Wed, Dec 20, 2017 at 4:55 PM, Xiaodi Wu <xiaodi...@gmail.com> wrote:
>
>> xoroshiro128+ is not a cryptographically secure algorithm and would not
>> be incorporated into the Random API, though it is trivial to implement your
>> own; the proposal outlines sources of randomness that are cryptographically
>> secure.
>>
>>
>>
>> On Wed, Dec 20, 2017 at 09:46 Jens Persson via swift-evolution <
>> swift-evolution@swift.org> wrote:
>>
>>> I'd like to add a pointer to the information here:
>>> http://xoroshiro.di.unimi.it
>>>
>>> since AFAICS, the xoroshiro128+ generator and the method of "Generating
>>> uniform doubles in the unit interval" should probably be implemented in any
>>> modern general purpose Random API.
>>>
>>> Please correct me if there are more up to date (higher quality and
>>> faster) general purpose generators and ways of converting UInt64 bit
>>> patterns to floating point [0, 1).
>>>
>>> /Jens
>>>
>>>
>>>
>>> On Sun, Dec 3, 2017 at 4:50 AM, Dave Abrahams via swift-evolution <
>>> swift-evolution@swift.org> wrote:
>>>
>>>> I don’t have much to say about this other than that I think the
>>>> discussion seems way too narrow, focusing on spelling rather than on
>>>> functionality and composability.  I consider the “generic random number
>>>> library” design to be a mostly-solved problem, in the C++ standard
>>>> library (http://en.cppreference.com/w/cpp/numeric/random).  Whatever
>>>> goes into the Swift standard library does not need to have all those
>>>> features right away, but should support being extended into something
>>>> having the same general shape. IMO the right design strategy is to 
>>>> *implement
>>>> and use* a Swift version of C++’s facilities and only then consider
>>>> proposing [perhaps a subset of] that design for standardization in Swift.
>>>>
>>>> Sent from my iPad
>>>>
>>>> On Dec 2, 2017, at 5:12 PM, Kyle Murray via swift-evolution <
>>>> swift-evolution@swift.org> wrote:
>>>>
>>>>
>>>> On Dec 2, 2017, at 6:02 PM, Xiaodi Wu via swift-evolution <
>>>> swift-evolution@swift.org> wrote:
>>>>
>>>> Instead, we ought to make clear to users both the features and the
>>>> limitations of this API, to encourage use where suitable and to discourage
>>>> use where unsuitable.
>>>>
>>>>
>>>> I like that you're considering the balance here. I've been lightly
>>>> following this thread and want to add my thoughts on keeping crypto and
>>>> pseudorandomness out of the name of at least one random API intended
>>>> for general use.
>>>>
>>>> For someone who doesn't know or care about the subtleties of insecure
>>>> or pseudorandom numbers, I'm not sure that the name insecureRan

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

2017-12-20 Thread Xiaodi Wu via swift-evolution
xoroshiro128+ is not a cryptographically secure algorithm and would not be
incorporated into the Random API, though it is trivial to implement your
own; the proposal outlines sources of randomness that are cryptographically
secure.


On Wed, Dec 20, 2017 at 09:46 Jens Persson via swift-evolution <
swift-evolution@swift.org> wrote:

> I'd like to add a pointer to the information here:
> http://xoroshiro.di.unimi.it
>
> since AFAICS, the xoroshiro128+ generator and the method of "Generating
> uniform doubles in the unit interval" should probably be implemented in any
> modern general purpose Random API.
>
> Please correct me if there are more up to date (higher quality and faster)
> general purpose generators and ways of converting UInt64 bit patterns to
> floating point [0, 1).
>
> /Jens
>
>
>
> On Sun, Dec 3, 2017 at 4:50 AM, Dave Abrahams via swift-evolution <
> swift-evolution@swift.org> wrote:
>
>> I don’t have much to say about this other than that I think the
>> discussion seems way too narrow, focusing on spelling rather than on
>> functionality and composability.  I consider the “generic random number
>> library” design to be a mostly-solved problem, in the C++ standard
>> library (http://en.cppreference.com/w/cpp/numeric/random).  Whatever
>> goes into the Swift standard library does not need to have all those
>> features right away, but should support being extended into something
>> having the same general shape. IMO the right design strategy is to *implement
>> and use* a Swift version of C++’s facilities and only then consider
>> proposing [perhaps a subset of] that design for standardization in Swift.
>>
>> Sent from my iPad
>>
>> On Dec 2, 2017, at 5:12 PM, Kyle Murray via swift-evolution <
>> swift-evolution@swift.org> wrote:
>>
>>
>> On Dec 2, 2017, at 6:02 PM, Xiaodi Wu via swift-evolution <
>> swift-evolution@swift.org> wrote:
>>
>> Instead, we ought to make clear to users both the features and the
>> limitations of this API, to encourage use where suitable and to discourage
>> use where unsuitable.
>>
>>
>> I like that you're considering the balance here. I've been lightly
>> following this thread and want to add my thoughts on keeping crypto and
>> pseudorandomness out of the name of at least one random API intended for
>> general use.
>>
>> For someone who doesn't know or care about the subtleties of insecure or
>> pseudorandom numbers, I'm not sure that the name insecureRandom is
>> effectively much different than badRandom, at least in terms of the
>> information it conveys to non-experts. To Greg's point, that's the opposite
>> of the signal that the API name should suggest because it's what most
>> people should use most of the time. As you say, this API is being designed
>> for general use.
>>
>> There's a cost to adding extra complexity to names, too. I don't think
>> it's far-fetched to suspect that people who find insecureRandom in an
>> autocomplete listing or search will think "Where's the plain random
>> function?"... and then go looking for a community extension that will
>> inevitably provide a trivial alias: func random() { return
>> insecureRandom() }. That's the sort of adoption I'd expect from
>> something for new programmers, like Swift Playgrounds. Someone's
>> introduction to randomness in programming should probably involve no more
>> than a straightforward mapping from the elementary definition, rather than
>> forcing a teaching moment from more advanced math.
>>
>> I think there are better places for caveat information than in the API
>> names themselves; documentation being one clear destination. This is in
>> contrast with Unsafe*Pointer, where the safety element is critical
>> enough to be elevated to be more than caveat-level information. You can go
>> really far and create really cool things before these caveats start to
>> apply. Using randomness as a black box in an intro programming environment
>> seems like a much more common scenario than someone attempting to roll
>> their first crypto by only reading API names and hoping for the best.
>>
>> -Kyle
>>
>> ___
>> swift-evolution mailing list
>> swift-evolution@swift.org
>> https://lists.swift.org/mailman/listinfo/swift-evolution
>>
>>
>> ___
>> swift-evolution mailing list
>> swift-evolution@swift.org
>> https://lists.swift.org/mailman/listinfo/swift-evolution
>>
>>
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [swift-evolution-announce] [Review] SE 0192 - Non-Exhaustive Enums

2017-12-19 Thread Xiaodi Wu via swift-evolution
On Wed, Dec 20, 2017 at 12:42 AM, Howard Lovatt 
wrote:

> Let me give an example. The recent discussion about filterMap aired in the
> discussion stage misgivings about the name; but it went to review with the
> name filterMap. At the review stage more misgivings were raised, the review
> was returned for amendment. An amended name of compactMap was put forward
> and this was accepted yesterday as a result of the 2nd review. I think that
> this shows how the process can work well. If the discussions were shut down
> with “already covered on Swift Evolution”, then the result wouldn’t be as
> good.
>
> If an argument has been put forward on Evolution, is in the alternatives
> section, and people are still raising the point; it is probably safe to
> assume that the argument hasn’t carried the day and should be revisited.
>

The name of `filterMap` was reviewed a second time because, if I recall,
the core team felt that there might be _additional_ ideas not yet surveyed
the first time. By contrast, if an argument has already been discussed and
is even incorporated into the text of the proposal, then I very strongly
disagree that raising the point again is to be encouraged. It's a different
matter if you have additional _evidence_ or alternative _reasoning_ to
support an argument.

On 19 Dec 2017, at 6:44 pm, Xiaodi Wu  wrote:
>
> On Tue, Dec 19, 2017 at 11:15 PM, Howard Lovatt via swift-evolution <
> swift-evolution@swift.org> wrote:
>
>> As an aside: there seems to be increasingly comments about proposals that
>> say:
>>
>>   1. This was discussed at the evaluation stage and rejected.
>>   2. This is how it is implemented in the patch.
>>
>> And other comments along those lines. Neither the pre-proposal
>> discussions nor the proposed implementation are intended to limit the scope
>> of the review. Therefore I don’t think people should raise this as reasons.
>> You should remember that the process is deliberately staged this way and
>> different people may well be commenting (in fact the process rather assumes
>> that people in the formal review will be a wider set of people).
>>
>>
> No, previous discussion don't limit the scope of review per se, but it's
> not helpful to rehash the same arguments again. We want to encourage
> everyone to contribute their most thought-out comments as early in the
> process as possible to give those who propose ideas the fullest chance to
> flesh out any revisions. However, everyone has finite time to contribute,
> and if the same discussions are merely replayed at every stage of review,
> then the process actively discourages thoughtful early participation. After
> all, why bother defending ideas at the pre-proposal stage if I'm going to
> have to spend the time repeating myself in a few months' time anyway?
>
> Of course, if a wider set of people have _new_ comments, those are welcome
> at a later stage. But, there seems to be a sense that if _I_ haven't said
> something already, then _I_ should say it whether or not the same viewpoint
> has already been aired. In my view, such an approach should be actively
> discouraged for the reasons above. Although a strong consensus within the
> community should certainly be accounted for, this list--even at the formal
> review stage--doesn't even come close to approximating the community of
> Swift users at large. Thus, review is not a vote-counting exercise to
> maximize the number of people who chime in, but rather it is meant to
> maximize the number of ideas and perspectives that are aired. If it's
> already been said, it doesn't need to be said again, even if _I_ haven't
> said it myself.
>
>
>> Anyway gripe over.
>>
>> Proposal link: https://github.com/apple/swift-evolution/blob/master/
>> proposals/0192-non-exhaustive-enums.md
>>
>>
>>-
>>
>>What is your evaluation of the proposal?
>>
>>+1/2
>>
>>I only give this a half because whilst it is important I can see
>>three issues:
>>
>>  1. It doesn’t seem very Swift like to have a different rule,
>>default non-exhaustive, for public as opposed to non-public.
>>
>>  2. It doesn’t seem very Swift like to have the default the unsafe
>>case.
>>
>>  3. Other languages have better solutions - see below under other
>>languages
>>-
>>
>>Is the problem being addressed significant enough to warrant a change
>>to Swift?
>>
>>Yes, Swift ABI compatibility going forwards is important
>>-
>>
>>Does this proposal fit well with the feel and direction of Swift?
>>
>>No. As mentioned above different rules for public and a non-safe
>>default don’t see that Swift like.
>>-
>>
>>If you have used other languages or libraries with a similar feature,
>>how do you feel that this proposal compares to those?
>>
>>Both Java and Scala have a better solution. In these languages enums
>>(Scala calls them case classes) can implement protocols and the user of an
>>enum 

Re: [swift-evolution] [swift-evolution-announce] [Review] SE 0192 - Non-Exhaustive Enums

2017-12-19 Thread Xiaodi Wu via swift-evolution
On Tue, Dec 19, 2017 at 11:15 PM, Howard Lovatt via swift-evolution <
swift-evolution@swift.org> wrote:

> As an aside: there seems to be increasingly comments about proposals that
> say:
>
>   1. This was discussed at the evaluation stage and rejected.
>   2. This is how it is implemented in the patch.
>
> And other comments along those lines. Neither the pre-proposal discussions
> nor the proposed implementation are intended to limit the scope of the
> review. Therefore I don’t think people should raise this as reasons. You
> should remember that the process is deliberately staged this way and
> different people may well be commenting (in fact the process rather assumes
> that people in the formal review will be a wider set of people).
>
>
No, previous discussion don't limit the scope of review per se, but it's
not helpful to rehash the same arguments again. We want to encourage
everyone to contribute their most thought-out comments as early in the
process as possible to give those who propose ideas the fullest chance to
flesh out any revisions. However, everyone has finite time to contribute,
and if the same discussions are merely replayed at every stage of review,
then the process actively discourages thoughtful early participation. After
all, why bother defending ideas at the pre-proposal stage if I'm going to
have to spend the time repeating myself in a few months' time anyway?

Of course, if a wider set of people have _new_ comments, those are welcome
at a later stage. But, there seems to be a sense that if _I_ haven't said
something already, then _I_ should say it whether or not the same viewpoint
has already been aired. In my view, such an approach should be actively
discouraged for the reasons above. Although a strong consensus within the
community should certainly be accounted for, this list--even at the formal
review stage--doesn't even come close to approximating the community of
Swift users at large. Thus, review is not a vote-counting exercise to
maximize the number of people who chime in, but rather it is meant to
maximize the number of ideas and perspectives that are aired. If it's
already been said, it doesn't need to be said again, even if _I_ haven't
said it myself.


> Anyway gripe over.
>
> Proposal link: https://github.com/apple/swift-evolution/blob/
> master/proposals/0192-non-exhaustive-enums.md
>
>
>-
>
>What is your evaluation of the proposal?
>
>+1/2
>
>I only give this a half because whilst it is important I can see three
>issues:
>
>  1. It doesn’t seem very Swift like to have a different rule, default
>non-exhaustive, for public as opposed to non-public.
>
>  2. It doesn’t seem very Swift like to have the default the unsafe
>case.
>
>  3. Other languages have better solutions - see below under other
>languages
>-
>
>Is the problem being addressed significant enough to warrant a change
>to Swift?
>
>Yes, Swift ABI compatibility going forwards is important
>-
>
>Does this proposal fit well with the feel and direction of Swift?
>
>No. As mentioned above different rules for public and a non-safe
>default don’t see that Swift like.
>-
>
>If you have used other languages or libraries with a similar feature,
>how do you feel that this proposal compares to those?
>
>Both Java and Scala have a better solution. In these languages enums
>(Scala calls them case classes) can implement protocols and the user of an
>enum rarely writes a switch statement, instead they call protocol methods.
>Enums in these languages are a fixed set of derived classes; i.e. normal OO
>programming rather than functional programming, which works well in the
>case of wanting to expand later the number of enum cases.
>-
>
>How much effort did you put into your review? A glance, a quick
>reading, or an in-depth study?
>Have followed the discussions. Used enums in Swift and other languages
>extensively.
>
>
> -- Howard.
>
> On 19 Dec 2017, at 12:58 pm, Ted Kremenek  wrote:
>
> When replying, please try to keep the proposal link at the top of the
> message:
>
> Proposal link: https://github.com/apple/swift-evolution/blob/master/
> proposals/0192-non-exhaustive-enums.md
> ...
> Reply text
> ...
> Other replies
>
> What goes into a review of a proposal?
>
> The goal of the review process is to improve the proposal under review
> through constructive criticism and, eventually, determine the direction of
> Swift.
>
> When reviewing a proposal, here are some questions to consider:
>
>-
>
>What is your evaluation of the proposal?
>-
>
>Is the problem being addressed significant enough to warrant a change
>to Swift?
>-
>
>Does this proposal fit well with the feel and direction of Swift?
>-
>
>If you have used other languages or libraries with a similar feature,
>how do you feel that this proposal compares to those?
>-
>
>How 

Re: [swift-evolution] [swift-evolution-announce] [Review] SE 0192 - Non-Exhaustive Enums

2017-12-19 Thread Xiaodi Wu via swift-evolution
On Tue, Dec 19, 2017 at 6:31 PM, Kevin Ballard via swift-evolution <
swift-evolution@swift.org> wrote:

>
> On Dec 19, 2017, at 2:58 PM, Ted Kremenek  wrote:
>
> https://github.com/apple/swift-evolution/blob/master/
> proposals/0192-non-exhaustive-enums.md
>
>
>-
>
>What is your evaluation of the proposal?
>
> Overall I like it, but I have some issues.
>
> I’m not completely sold yet on the idea that public enums should be
> non-exhaustive by default, as I believe every single public enum I’ve ever
> written definitely wants to be exhaustive. I’m tempted to say that enums
> exposed by frameworks that need to maintain future-compatibility (such as
> Apple’s frameworks) want non-exhaustive by default, but enums exposed by
> third-party frameworks that follow semantic versioning are likely to want
> exhaustive by default.
>
> In fact, this brings to mind another difference between enums in Apple
> frameworks and enums in third-party Swift frameworks, which is the former
> is exclusively C-compatible enums whereas the latter is going to have a lot
> of enums that carry associated values. I have no data to support this but
> I’m inclined to think that it’s more likely for C-compatible enums to want
> to be non-exhaustive than it is for enums carrying associated values to
> want to be non-exhaustive.
>
> So I guess I’m saying, I want more thought put on the topic of whether
> enums defined in Swift should actually default to non-exhaustive, and I’m
> now leaning towards the idea that they should remain exhaustive (but Obj-C
> enums will still default to non-exhaustive).
>

I think the proposal represents a very good summary of the pros and cons of
each approach. At the pre-proposal stage, all possible solutions (there are
only three: no default, default to exhaustive, or default to nonexhaustive)
were thoroughly explored, and the proposal as revised here represents a
thoughtful synthesis of the conversation and has a good justification for
the default proposed. I highly doubt that any more back-and-forth on this
will surface new arguments not already covered.


> --
>
> I don’t like that modules using @testable imports treat all enums as
> exhaustive. I can see why you want to do that, but being forced to handle
> non-exhaustive enums in unit tests seems like a valuable guard against
> accidentally publishing non-exhaustive enums that should be exhaustive.
>

On the contrary, I think that the proposal's behavior for `@testable` is
fully consistent and the best solution possible. It preserves the behavior
that `@testable` imports are treated as though internal, and it allows for
unit tests to have compile-time errors when unexpected cases are added. Any
time you want to test nonexhaustive behavior, you can import without
`@testable`.

--
>
> I’m really not a fan of using a ‘default’ case in non-exhaustive enums.
> This means that if new cases are added, the compiler can’t help me find my
> switches. I’d really like to have an alternative way of saying “here’s how
> to behave in the event of an unknown enum case” without also making that a
> catch-all for unspecified-but-known cases. You already brought up this
> issue in the alternatives section, where you stated
>
> Ultimately I decided not to include this in the proposal with the
> expectation is that switches over non-exhaustive enums should be uncommon.
>
>
> But since non-exhaustive enums will be the default, I think this _will_
> become quite common, if for no other reason than you’re using a library
> written by someone who forgot to mark enums as @exhaustive that really
> should be.
>
> Regarding the comment that a ‘future’ case is impossible to test, so is a
> ‘default’ case on a switch that is otherwise exhaustive. In the latter you
> can test it by commenting out one of your existing cases. But you can do
> that with ‘future’ too, just by renaming it to ‘default’ first.
>

This, too, I think, has been discussed quite thoroughly, and I think the
proposal synthesizes the discussion and presents the best possible solution.


> In the “Use-side” section it says that a switch without a default case
> will produce a warning in Swift 4 mode. But in Swift 4 mode all enums are
> exhaustive by default and the @exhaustive annotation does nothing. These
> two things can’t both be true or else Swift 4 mode will emit warnings on
> switches over enums that are very clearly supposed to be exhaustive enums.
>

This is curious. I wonder if C enums will be nonexhaustive in both Swift 4
and 5 mode, thereby triggering such warnings.

>
>-
>
>Is the problem being addressed significant enough to warrant a change
>to Swift?
>
> Yes
>
>
>-
>
>Does this proposal fit well with the feel and direction of Swift?
>
> Yes
>
>
>-
>
>How much effort did you put into your review? A glance, a quick
>reading, or an in-depth study?
>
> A quick reading, followed by a few re-readings as I composed this email.
>
> -Kevin Ballard
>
> 

Re: [swift-evolution] [swift-evolution-announce] [Accepted with revisions] SE-0187 “Introduce Sequence.filterMap(_:)”

2017-12-19 Thread Xiaodi Wu via swift-evolution
I disagree. Let’s not reopen what is settled. “Compact” can be a noun just
as “map” and “filter” can; as long as there are no in-place variants, there
can be no ambiguity.
On Tue, Dec 19, 2017 at 17:11 Brent Royal-Gordon via swift-evolution <
swift-evolution@swift.org> wrote:

> On Dec 19, 2017, at 8:56 AM, John McCall  wrote:
>
> Therefore, SE-0187 is *accepted*, with the *revision* that the new name
> be Sequence.compactMap(_:), and with the agreement that we will add
> Sequence.compact() when it is possible to do so.
>
>
> I like `compact` as the basis for the name, but I hope the core team will
> consider whether the eventual nil-removal method should be called
> `compacting()`, and whether therefore this method should be called
> `compactingMap(_:)`. Prior art on the name `compact()` does exist, but I
> don't think it's strong enough to justify deviating from the API Guidelines.
>
> I don't think we need a full review on this tiny issue; five minutes of
> the core team's time should more than suffice.
>
> --
> Brent Royal-Gordon
> Architechies
>
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Optional Argument Chaining

2017-12-11 Thread Xiaodi Wu via swift-evolution
This topic has been discussed at least two and maybe more times in the
past. It’s hard for me to post links at the moment, but it should be
possible to find on Google.

One major challenge to this idea, for which no satisfactory answer has been
achieved after all these years, is the following issue:

f(g()?, h()?, i(), j()?)?

If g() evaluates to nil, is h() called or not? How about i(), which is not
failable? Since any function or property access can have side effects, in
what order are the arguments evaluated, and how does one reason about this
code flow?

To my mind, in the absence of an intuitive answer to the above—which does
not appear to be possible—this idea is not feasible.
On Mon, Dec 11, 2017 at 12:34 Magnus Ahltorp via swift-evolution <
swift-evolution@swift.org> wrote:

>
> > 12 Dec. 2017 02:58 Jared Khan  wrote:
> >
> > 2. It felt natural to me. It’s analogous to the existing optional
> chaining scenarios and composes nicely. I think it’s about as
> understandable as existing chaining, a newbie would have to look it up to
> discover its meaning. What are your thoughts on this particular syntax
> (ignoring 3. momentarily)? Hopefully others in this thread can share their
> views too.
>
> Chaining methods is linear, while nesting fills a similar purpose when we
> use function calls. This of course affects the way existing Swift code is
> written, but that is something we have to live with if we want to use
> familiar syntax patterns. However, I think we have to consider this
> difference in this case, since the syntax becomes more convoluted. Your
> suggestion is definitely not as easy to read as the optional chaining
> syntax, and maybe it can't be.
>
> > As for how common I’d expect it to be, it’s something I’ve run into
> myself a few times. Again, I hope members of this list can give their view
> on if this would be useful to them.
>
> I don't have any real examples, but I certainly think that I have run into
> it, so I'm quite open to solving the problem. For me, it is probably only a
> matter of finding a syntax that is acceptable.
>
> > 3. I’m not entirely sure what the grammar situation is yet but afaik ‘?’
> has never been available as a postfix operator. Perhaps I’m missing your
> point, could you demonstrate where it is allowed?
>
> I did not expect that you would be able to answer that, it was more a
> question directed to people who are more connected to the inner workings of
> the parsing of Swift than I am. It is not allowed, but the error message is
> not the one I expect, something that gives me a hint that it does have some
> meaning early in the parsing.
>
> /Magnus
>
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


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

2017-12-10 Thread Xiaodi Wu via swift-evolution
On Sun, Dec 10, 2017 at 7:59 AM, Brent Royal-Gordon <br...@architechies.com>
wrote:

> On Dec 9, 2017, at 10:32 AM, Xiaodi Wu via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> On Sat, Dec 9, 2017 at 11:20 Steven Brunwasser <sbrunwas...@gmail.com>
> wrote:
>
>> Just wanted to give my 2¢
>>
>> ¢
>> I don’t like empty protocols—they feel like an abuse of the feature.
>>
>
> As has been discussed here before, protocols aren’t about bags of syntax
> but rather about semantics. Empty protocols are explicitly a demonstration
> of this settled principle and are very much consistent with the direction
> of Swift.
>
>
> I also think it should be an attribute.
>
> The last time I said this, I pointed out that this was a protocol which:
>
> 1. Has no formal members,
> 2. But imposes informal requirements enforced by the compiler,
> 3. Permits and uses arbitrary overloads, and
> 4. Cannot be usefully used in a generic context or as a type constraint,
>
> None of which are true of ordinary protocols. Since then, we have added:
>
> 5. Can only be conformed to in the main declaration.
>
> This is looking less like a protocol by the day. The square-peg grooves in
> the round hole are getting deeper and more splintery with every revision.
>

Synthesized conformances cannot be declared in extensions either. If you'd
like, you could consider that this protocol is one for which the compiler
synthesizes an infinite number of members.

I would like to see (4) addressed: a complete implementation should allow
me to call any member on a type T in a generic context where T :
DynamicMemberLookupProtocol, which I kind of assumed that this proposal
would eventually permit.
___
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-09 Thread Xiaodi Wu via swift-evolution
On Sat, Dec 9, 2017 at 11:20 Steven Brunwasser <sbrunwas...@gmail.com>
wrote:

> Just wanted to give my 2¢
>
> ¢
> I don’t like empty protocols—they feel like an abuse of the feature.
>

As has been discussed here before, protocols aren’t about bags of syntax
but rather about semantics. Empty protocols are explicitly a demonstration
of this settled principle and are very much consistent with the direction
of Swift.

I think attributes are the right way to go, since this proposal is about
> enabling syntactic sugar for types which can’t yet be described in the
> language as-is. This prevents retroactive conformance on preexisting types,
> which some have raised as a concern.
>
> ¢
> I think the discussion about whether or not implementations should throw,
> return optional, or be implicitly unwrapped is a larger discussion on its
> own, and should probably be a separate proposal to steer the language
> towards a more well defined convention. That being said, I’m of the opinion
> that they should always return an implicitly unwrapped value. The precedent
> is already in the language, it allows for cleaner syntax while also
> explicitly stating “hey, just so you know, I might not work, so be careful,
> ok?”, and callers can choose to be more cautious by explicitly using the ?
> operator.
>
> That is all,
> - Steve
>
> On Dec 8, 2017, at 16:34, Xiaodi Wu via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> On Fri, Dec 8, 2017 at 18:08 Jon Gilbert via swift-evolution <
> swift-evolution@swift.org> wrote:
>
>> See below.
>>
>> On Dec 6, 2017, at 02:45, Nick Keets via swift-evolution <
>> swift-evolution@swift.org> wrote:
>>
>> Apologies, I may have misunderstood you. What I wanted to say is that I
>> see no problem allowing "dangerous" stuff that may be abused.
>>
>>
>> You see no problem with danger and abuse?
>>
>> I guess we have differing philosophies...
>>
>> https://developer.apple.com/swift/ states:
>>
>> “Swift eliminates entire classes of unsafe code.”
>>
>> Lets keep it that way.
>>
>> I’m all for this proposal if it can be tweaked to where any of the
>> dangerous invocations contain the word, “Unsafe”, or equivalent.
>>
>
> Again, in Swift, “safety” means something very specific. Trapping at
> runtime is safe; in fact, trapping at runtime is *precisely the means by
> which safety is achieved* in the case of integer overflow and array
> indexing. This proposal introduces nothing that is unsafe.
>
> ~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] Proposal: Introduce User-defined "Dynamic Member Lookup" Types

2017-12-08 Thread Xiaodi Wu via swift-evolution
On Fri, Dec 8, 2017 at 18:08 Jon Gilbert via swift-evolution <
swift-evolution@swift.org> wrote:

> See below.
>
> On Dec 6, 2017, at 02:45, Nick Keets via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> Apologies, I may have misunderstood you. What I wanted to say is that I
> see no problem allowing "dangerous" stuff that may be abused.
>
>
> You see no problem with danger and abuse?
>
> I guess we have differing philosophies...
>
> https://developer.apple.com/swift/ states:
>
> “Swift eliminates entire classes of unsafe code.”
>
> Lets keep it that way.
>
> I’m all for this proposal if it can be tweaked to where any of the
> dangerous invocations contain the word, “Unsafe”, or equivalent.
>

Again, in Swift, “safety” means something very specific. Trapping at
runtime is safe; in fact, trapping at runtime is *precisely the means by
which safety is achieved* in the case of integer overflow and array
indexing. This proposal introduces nothing that is unsafe.

~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] Proposal: Introduce User-defined "Dynamic Member Lookup" Types

2017-12-07 Thread Xiaodi Wu via swift-evolution
On Thu, Dec 7, 2017 at 09:15 Letanyan Arumugam  wrote:

>
>
> On 07 Dec 2017, at 17:02, Xiaodi Wu  wrote:
>
>
> On Thu, Dec 7, 2017 at 00:37 Letanyan Arumugam via swift-evolution <
> swift-evolution@swift.org> wrote:
>
>>
>> This seems marginally tolerable, but excessive.
>>
>> Do we mark every usage of a type that can generate precondition failures
>> or fatal errors for reasons other than “no such method?” No, we don’t.
>>
>> fatalError shouldn’t be used excessively. API surface areas for these
>> types are going to be massive (infinite technically). I assume many people
>> are going to be writing a lot of code would these types and calling many
>> methods and properties which would all essentially have a fatalError. Would
>> you consider it good code if the majority of all your types had methods
>> defined with fatalError calls.
>>
>
> What is the basis for this claim? Probably the majority of standard
> library methods check preconditions and trap on failure. That is how I
> write my code as well.
>
>>
>>
> I’m talking specifically about fatalError not precondition. fatalError is
> something that goes out with production code while precondition is used for
> debugging. I think you would agree a shipped program that has many states
> of being unrecoverable is not a good design?
>

Precondition checks are active in release code. When a program encounters
conditions that have no obvious recovery, trapping immediately is the only
safe option; this is what Swift means by “safety” and the practice is
encouraged.

>
___
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-07 Thread Xiaodi Wu via swift-evolution
On Thu, Dec 7, 2017 at 00:37 Letanyan Arumugam via swift-evolution <
swift-evolution@swift.org> wrote:

>
> This seems marginally tolerable, but excessive.
>
> Do we mark every usage of a type that can generate precondition failures
> or fatal errors for reasons other than “no such method?” No, we don’t.
>
> fatalError shouldn’t be used excessively. API surface areas for these
> types are going to be massive (infinite technically). I assume many people
> are going to be writing a lot of code would these types and calling many
> methods and properties which would all essentially have a fatalError. Would
> you consider it good code if the majority of all your types had methods
> defined with fatalError calls.
>

What is the basis for this claim? Probably the majority of standard library
methods check preconditions and trap on failure. That is how I write my
code as well.

What’s so wrong with adding another layer of protection on top to bypass if
> you want to do this.
>
> Do we use a syntactically privileged marker instead of just using words
> like “unsafe” for types that expose direct access to raw memory? No, we
> don’t.
>
> Okay we use Unsafe. Then should we have something similar for this. A
> UncheckedDynamicMemberLookup [1] and a DynamicMemberLookup [2]? my one
> objection to this would be that I would like to convert a
> UncheckedDynamicMemberLookup to a DynamicMemberLookup.
>
> [1] would work like the current proposal for DynamicMemberLookup
> [2] would only allow returning an optional
>
>
> My main objection to the critical responses is that most of the objections
> are fundamentally cultural, not technical, and are fear-based, not
> evidence-based.
>
>
> The goal of this proposal is to bring people from a culture where
> excessive use of this would be the norm for them. Why would it be so hard
> to imagine that people would adopt bad principles, knowing or unknowing,
> because this is what they’ve always done?
>
> Evidence is going to be hard to get since I don’t know any other language
> like Swift that has done this for the same reasons before. As far as C#
> goes were they trying to get people from a heavily based dynamic community
> or help those already in the community?
>
>
> If a little extra language ceremony helps assuage those fears, I guess I’d
> consider it. I still think static analysis — starting and mostly ending
> with boring old syntax coloring — answers most all the concerns people have
> raised, and this debate is a tempest in a teapot.
>
>
> I'm unsure of this, but as far as I’m aware Swift language proposals
> shouldn’t rely on editor features. But like I said I’m unsure of this and
> if someone could clarify this that would great.
>
>
> ___
> 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] Core Team vs Random number API discussion

2017-12-06 Thread Xiaodi Wu via swift-evolution
So, my read of the decision is that when the core teams says the API should
be designed “without worrying about the needs of crypto experts,” they mean
exactly that we should stop worrying about how easy or hard it is to extend
for those users.

On Wed, Dec 6, 2017 at 18:34 Jacob Williams via swift-evolution <
swift-evolution@swift.org> wrote:

> I agree with this decision, but I would also add the provision that the
> random number API be designed in such a way that those with special crypto
> needs can easily extend the existing random number framework to meet their
> needs. (Specify their own seed, use their own crypto implementation, etc).
>
> I’m sure this is already being considered having read most of the Random
> Unification email chain, but just thought I’d make sure it was specifically
> mentioned. I’d hate to leave a group of coders out in the dark (no matter
> how small that group may be).
>
> > On Dec 6, 2017, at 4:16 PM, Chris Lattner via swift-evolution <
> swift-evolution@swift.org> wrote:
> >
> > Hi All,
> >
> > FYI, the Core Team had a brief discussion about the direction of the
> random number API design being discussed.
> >
> > The strong opinion of the core team is that such an API should *not* be
> designed with an attempt to service people writing crypto code.  Such
> clients will have requirements that are difficult to predict or that are
> hard to provide in general (e.g. “must run in constant time”).  These
> clients are also relatively few, compared the community of people who
> benefit from a good "general use" random number API.
> >
> > As such, the core team strongly encourages the random number API design
> process to focus on building the best possible "general use" API, without
> worrying about the needs of crypto experts.
> >
> > Beyond that, the core team did not discuss what the exact shape of the
> API should look like: it believes the community should continue hashing it
> out.  We just wanted to remove one big constraint from that design process.
> >
> > Thanks,
> >
> > -Chris & Swift Core Team
> >
> >
> > ___
> > swift-evolution mailing list
> > swift-evolution@swift.org
> > https://lists.swift.org/mailman/listinfo/swift-evolution
>
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


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

2017-12-03 Thread Xiaodi Wu via swift-evolution
On Sun, Dec 3, 2017 at 2:16 PM, Matthew Johnson via swift-evolution <
swift-evolution@swift.org> wrote:

>
> On Dec 3, 2017, at 11:36 AM, Chris Lattner  wrote:
>
> On Dec 2, 2017, at 7:11 PM, Matthew Johnson 
> wrote:
>
>
> This does not improve clarity of code, it merely serves to obfuscate
> logic.  It is immediately apparent from the APIs being used, the API style,
> and the static types (in Xcode or through static declarations) that this is
> all Python stuff.
>
>
> It may be immediately apparent when the types involved are obviously
> dynamic, such as in this example where Python.import is explicitly used.
> However, my concern is less about the intended use case of dynamic language
> interop than I am that this feature will be generally available to all
> types in Swift.
>
> This is big change from AnyObject dispatch.  It opens up the dynamism to
> types and contexts that *are not *necessarily obviously using dynamic
> lookup, callable, etc.  Maybe this won’t turn out to be a problem in
> practice but I still think it’s a legitimate concern.
>
>
> Sure, it is a legit concern, but it is also nothing new.  This is the
> standard concern with type inference.
>
>
> The concern for me is orthogonal to type inference.  The name of a type
> supporting dynamic lookup will not necessarily provide any indication that
> the type supports dynamic lookup.
>
>
> While there are weird cases, in practice, values do not get magicked out
> of no-where.  They most commonly are either root values like:
>
> let np = Python.import(“foo”)
> let pyInt = PyVal(42)
>
> or they come for parameters:
>
> func f(x : PyVal) {
>
> The place that is potentially surprising is when the type gets buried
> because you’re working with some API that returns a [String, PyVal]
> dictionary or something:
>
>
> let x = foo()[“someKey”]
>
> and you don’t realize that PyVal’s are involved.  However, if you are
> actively writing the code, you have access to code completion and other
> things that tell you these types, and if it is important for the clarity of
> the code, you write this instead:
>
> let x :PyVal = foo()[“someKey”]
>
> There is nothing specific to this proposal about this issue.
>
>
> See above.  In the case of PyVal specifically the concern is somewhat
> mitigated by the name of the type.  That won’t necessarily always be the
> case.
>

If that's the concern, then it would be pretty straightforward to restrict
dynamic protocols for stdlib internal use only and expose only PyVal. The
trade-off is that all such bridging code would have to be shipped with
Swift itself.


> I’m uncertain what the right answer is.  I’m still not really comfortable
> with opening up dynamic lookup to any user-defined type without some way to
> indicate to readers that dynamic lookup is happening in a piece of code.
> Maybe there is a less localized annotation that would indicate dynamic
> lookup is in effect for a larger chunk of code.
>
>
> You seem to be extremely concerned that people will adopt
> DynamicMemberLookup for types where it doesn’t make sense and abuse the
> feature.  I am having a real problem understanding what your concern is, so
> I’d really love for you to explain some theoretical examples of the bad
> thing that happens: why someone (non-maliciously) adopts the protocol, what
> code gets written, and what harm actually comes from it.
>
> Let me use a made up tale from a parallel universe to illustrate why I
> don’t understand your concern.  Imagine if Swift didn’t already
> interoperate with C, and did not already have IUOs.  Someone who cared
> about C language interoperability would quickly realize that the ergonomics
> of importing everything as strong optionals is a non-starter, jeopardizing
> the usability of C interop, and would propose IUOs as a feature.
>
> We’d then have a long and drawn out conversation about the various options
> on how to model this, the pros and cons of each, and would settle on IUO as
> the least bad design (as an aside, in our universe, when we went through
> the design process that led to IUOs, this is exactly what happened, we even
> considered syntaxing them as interobangs :-).
>
> At that point, there would be a general uproar because IUOs have high
> potential for abuse: Swift is “all about” strong types and safety, which
> IUOs undermine.  Strong optionals are considered a pain to use by some
> people and widely misunderstood (I think they are the biggest challenge in
> learning Swift in practice), and so it is a reasonable feature that people
> could pervasively adopt IUOs, leading to a much worse world all around.
>
>
> This made up parallel universe is exactly analogous to what is happening
> now.  DynamicMemberLookup is no more dangerous and harmful than IUOs are.
> They will be one more tool in the toolbox.  While it is possible that
> someone will abuse it, this will not be widespread.  People who are
> particularly worried will build a 

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

2017-12-03 Thread Xiaodi Wu via swift-evolution
On Sun, Dec 3, 2017 at 2:20 PM, Karl Wagner via swift-evolution <
swift-evolution@swift.org> wrote:

>
> I believe that adding explicit syntax would be counterproductive to your
> goals, and would not make dynamic lookup syntax more clear.  I assume that
> you would also want the same thing for DynamicCallable too, and operator
> overloads, subscripts, and every other operation you perform on these
> values, since they all have the exact same behavior.
>
> If we required some syntax even as minimal as “foo.^bar” and "baz^(42)”,
> that change would turn this (which uses runtime failing or IUO return
> values like AnyObject):
>
> let np = Python.import("numpy")
> let x = np.array([6, 7, 8])
> let y =  np.arange(24).reshape(2, 3, 4)
> let a = np.ones(3, dtype: np.int32)
> let b = np.linspace(0, pi, 3)
> let c = a+b
> let d = np.exp(c)
> print(d)
>
> into:
>
> let np = Python.import("numpy")
> let b = np^.array^([6, 7, 8])
> let y =  np^.arange^(24)^.reshape^(2, 3, 4)
>
> let a = np^.ones^(3, dtype: np^.int32)
> let b = np^.linspace^(0, pi, 3)
> let c = a+^b
> let d = np^.exp^(c)
>
> This does not improve clarity of code, it merely serves to obfuscate
> logic.  It is immediately apparent from the APIs being used, the API style,
> and the static types (in Xcode or through static declarations) that this is
> all Python stuff.  When you start mixing in use of native Swift types like
> dictionaries (something we want to encourage because they are typed!) you
> end up with an inconsistent mismash where people would just try adding
> syntax or applying fixits continuously until the code builds.
>
>
> That’s not Swift. You just wrote a bunch of Python. For example, Swift has
> a native Int32.+ operator which fails on overflow - does your example also
> do that? Anybody’s guess! Does your numpy array conform to Collection? I
> guess not, because it’s an opaque Python value.
>
> That’s exactly the kind of stuff I, as a user of the language, really
> don't want to see mixed together with real Swift. I appreciate the need to
> use functionality from libraries written in Python, but I don’t appreciate
> it being so invisible and pervasive throughout the language. If you have a
> bunch of Python logic, I’d prefer you wrote as much of it as possible in
> Python, with as few bridging points to Swift as you can get away with. I
> remain convinced that this design encourages the opposite - because, as you
> said earlier, it’s “too good”.
>

The use case that Chris is solving here is precisely how to enable the
writing of this type of code in Swift. Put another way, how do I interface
with libraries written in Python without writing my own code in Python?
"That's exactly the kind of stuff I really don't want to see mixed together
with real Swift" and "I'd prefer you wrote as much of it as possible in
Python" is not an answer; it's rejecting the legitimacy of the use case in
the first place.

As for the point about Swift already including non-marked,
> potentially-crashing operations (like the + operator, or Array
> subscripting): nobody likes that behaviour!
>

I, for one, very much like that behavior. Swift has many non-marked,
potentially-crashing operations because that is both performant and safe.
There is a common misconception that crashing is unsafe, with corresponding
misconceptions such as avoiding "!". This is simply incorrect.


> Whenever I come to a new Swift codebase, I almost universally find that
> people have written their own “safe” Array accessor which integrates
> bounds-checking and returns an Optional. The issue has come up here many,
> many times for inclusion in the standard library. I certainly would not use
> it as justification for adding more of those kinds of unmarked,
> potentially-unsafe operations. Also, enough Swift developers know about the
> Array subscript behaviour that the square brackets almost become a marker,
> like “!”, of a potentially-failing operation. The same is not true of the
> dot operator, in general.
>
> I also don’t agree with the comparisons to Objective-C/AnyObject dispatch.
> It’s true that it’s unsafe to an extent, but it’s also orders of magnitude
> safer than this sort of dispatch. Clang is integrated in to the compiler,
> and can at least perform some rudimentary checking of method
> signatures/selectors. This sort of dispatch provides absolutely no
> protections whatsoever — is “arange” really a function? Is it not really a
> typo for “arrange”? That’s something I need to Google. With regular Swift I
> can assume that if the compiler allows it, there is a function called
> “arange” somewhere, and all I need to worry about is whether the erased
> AnyObject is of the correct type to respond to that message. And as I said
> earlier, AnyObject is incredibly rare in practice anyway. So no, I don’t
> agree that we should just keep lowering the safeguards; it’s like
> demolishing your house because of one draughty door.
>
> What I *could* support, would be some kind of 

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

2017-12-02 Thread Xiaodi Wu via swift-evolution
On Sat, Dec 2, 2017 at 19:02 Greg Parker <gpar...@apple.com> wrote:

>
> On Dec 2, 2017, at 1:09 PM, Xiaodi Wu via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> On Sat, Dec 2, 2017 at 6:00 AM, Brent Royal-Gordon <br...@architechies.com
> > wrote:
>
>> On Dec 1, 2017, at 10:37 PM, Xiaodi Wu via swift-evolution <
>> swift-evolution@swift.org> wrote:
>>
>> 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).
>>
>>
>> People will use it for crypto whether we want them to or not.
>>
>
> People are going to do all sorts of unanticipated things, sure. But this
> doesn't mean that we shouldn't consider how we may best encourage users to
> avoid _unintentional_ common pitfalls.
>
> There are options to explore here. Consider, for example--and I'm not
> suggesting that we be this verbose, but it is illustrative of the
> trade-offs which are possible to keep in mind--if certain methods were very
> clear that the result is *pseudorandom* and potentially *insecure*:
> `(0..<9).insecurePseudorandomElement`. Clearly, fewer people would use this
> method for crypto.
>
>
> But what *should* they use instead of our API? The OS-provided CSPRNG is
> almost certainly going to be the most secure thing available in the absence
> of specialized hardware. We should not deliberately scare users away from
> our API if there is nothing better on offer.
>

>
It’s not about OS-provided CSPRNG. It’s about the design and implementation
of _this proposal_ on top of the CSPRNG.

Earlier, we discussed how this API should minimize the number of optional
return values to improve user ergonomics. Instead, the returned value
should be a reasonable best-effort at randomness. This is sensible for a
general-use API, but it is unsuitable for a crypto-oriented API.

David Waite criticizes GameplayKit as lacking in crypto-oriented
functions—the implication being that we ought to provide them here. I
disagree. My point is that our entire design process has been geared
towards a reasonable, best-effort general-use API: It is being designed by
community members who are not specialized in this particular subfield. It
is explicitly being design for common, general use cases in mind. And the
implementation will come with no guarantee as to suitability for crypto,
nor should it have to.

Therefore, I reason, we ought not to extend the design with functions that
are explicitly geared towards crypto using primitive operations that we
haven’t audited for such suitability. Instead, we ought to make clear to
users both the features and the limitations of this API, to encourage use
where suitable and to discourage use where unsuitable.
___
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-02 Thread Xiaodi Wu via swift-evolution
On Sat, Dec 2, 2017 at 2:30 PM, Howard Lovatt via swift-evolution <
swift-evolution@swift.org> wrote:

> Definitely in favour of doing something, I always define the associated
> types since I have had so much trouble with the inference.
>
> Personally I would prefer just 1 and 2 and forget 3. I know this would
> break a lot of code, but I think we should do that because it is the lesser
> of the evils.
>

As Doug wrote, an approach that's essentially that was reviewed and
rejected in SE-0108. We already know that it's not acceptable to a great
proportion of the community.
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


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

2017-12-02 Thread Xiaodi Wu via swift-evolution
On Sat, Dec 2, 2017 at 6:00 AM, Brent Royal-Gordon <br...@architechies.com>
wrote:

> On Dec 1, 2017, at 10:37 PM, Xiaodi Wu via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> 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).
>
>
> People will use it for crypto whether we want them to or not.
>

People are going to do all sorts of unanticipated things, sure. But this
doesn't mean that we shouldn't consider how we may best encourage users to
avoid _unintentional_ common pitfalls.

There are options to explore here. Consider, for example--and I'm not
suggesting that we be this verbose, but it is illustrative of the
trade-offs which are possible to keep in mind--if certain methods were very
clear that the result is *pseudorandom* and potentially *insecure*:
`(0..<9).insecurePseudorandomElement`. Clearly, fewer people would use this
method for crypto.

None of the proposals involve actually writing cryptographic primitives,
> just calling out to well-known functions like `arc4random()` or reading
> from special devices like `/dev/urandom`. I would hope that Apple's
> security team can spare the time to review the security-critical parts and
> sign off on them, and I'd be perfectly happy to see this proposal be
> approved but the final merge into the language be deferred until they've
> taken a look at it.
>
___
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 Xiaodi Wu via swift-evolution
On Thu, Nov 30, 2017 at 6:55 PM, Nate Cook <natec...@apple.com> wrote:

>
> On Nov 30, 2017, at 6:20 PM, Xiaodi Wu <xiaodi...@gmail.com> wrote:
>
> On Thu, Nov 30, 2017 at 5:24 PM, Nate Cook <natec...@apple.com> 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:
>>>
>>>

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: 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] [Review] SE-0191: Eliminate IndexDistance from Collection

2017-11-30 Thread Xiaodi Wu via swift-evolution
On Wed, Nov 29, 2017 at 10:46 AM, Ben Cohen  wrote:

> You can argue the current status is a bug, but…
>
> Welcome to Apple Swift version 4.0.1 (swiftlang-900.0.67 clang-900.0.38).
> Type :help for assistance.
>   1> CountableRange.IndexDistance.self
> $R0: Int.Type = Int
>   2> (Int64.min.. Execution interrupted. Enter code to recover and continue.
>
>
I do believe that, in the source code, this is marked with a "FIXME(ABI)"
comment.

(I dearly wish that we could have a primitive `Int1` available on which to
base a type such as `Int65` in the same manner as we implement
`DoubleWidth`. It would solve this use case beautifully.)

On Nov 29, 2017, at 4:04 AM, Xiaodi Wu  wrote:
>
> So that we are all clear on the implications of this, if IndexDistance
> becomes Int, ranges of integers will stop conforming to Collection, because
> Int.min.. potentially many more.
>
> This would entail nontrivial source breakage.
>
>
> On Mon, Nov 27, 2017 at 22:02 Ben Cohen via swift-evolution <
> swift-evolution@swift.org> wrote:
>
>> My suggestion would be: don’t have your Collection-like type conform to
>> Collection. Give it collection-like methods if you want them, like an
>> indexing and slicing subscript that takes an Int64. It can still conform to
>> Sequence.
>>
>> In practice, these “huge” collections will be mostly used concretely, so
>> their Collection conformance doesn’t buy you much. The reality is that very
>> few generic uses on these types will succeed. You get a few things like
>> .first, .last etc. for free. But very few algorithms are written to handle
>> > Int.max lengths (several in the std lib don’t) – it just isn’t practical.
>> And meanwhile, this is a huge burden on many other use cases.
>>
>> The existence of the memory mapped file case is hypothetical. I canvassed
>> a bit on twitter for some use cases. The only one I got back was where
>> someone was using IndexDistance to stash other information: but this isn’t
>> really a legal use of IndexDistance, since it must be numerically castable
>> to other integer types when needed which would be a lossy operation so at
>> best, it would just be an optimization.
>>
>> On Nov 27, 2017, at 19:29, Nevin Brackett-Rozinsky via swift-evolution <
>> swift-evolution@swift.org> wrote:
>>
>> The proposal mentions one reasonable situation where a larger-than-Int
>> type would be useful, namely a Collection wrapping a memory-mapped file,
>> being used on 32-bit systems.
>>
>> Is there a recommended migration strategy for this scenario?
>>
>> Nevin
>>
>>
>> On Mon, Nov 27, 2017 at 8:34 PM, Douglas Gregor via swift-evolution <
>> swift-evolution@swift.org> wrote:
>>
>>> Hello Swift community,
>>>
>>> The review of SE-0191 "Eliminate IndexDistance from Collection" begins
>>> now and runs through December 3, 2017. The proposal is available here:
>>>
>>> https://github.com/apple/swift-evolution/blob/master/
>>> proposals/0191-eliminate-indexdistance.md
>>>
>>> Reviews are an important part of the Swift evolution process. All
>>> reviews should be sent to the swift-evolution mailing list at
>>>
>>> https://lists.swift.org/mailman/listinfo/swift-evolution
>>>
>>> or, if you would like to keep your feedback private, directly to the
>>> review manager. When replying, please try to keep the proposal link at the
>>> top of the message:
>>>
>>> Proposal link:
>>>
>>> https://github.com/apple/swift-evolution/blob/master/
>>> proposals/0191-eliminate-indexdistance.md
>>>
>>> Reply text
>>>
>>> Other replies
>>>
>>> What
>>> goes into a review?
>>>
>>> The goal of the review process is to improve the proposal under review
>>> through constructive criticism and, eventually, determine the direction of
>>> Swift. When writing your review, here are some questions you might want to
>>> answer in your review:
>>>
>>>- What is your evaluation of the proposal?
>>>- Is the problem being addressed significant enough to warrant a
>>>change to Swift?
>>>- Does this proposal fit well with the feel and direction of Swift?
>>>- If you have used other languages or libraries with a similar
>>>feature, how do you feel that this proposal compares to those?
>>>- How much effort did you put into your review? A glance, a quick
>>>reading, or an in-depth study?
>>>
>>> More information about the Swift evolution process is available at
>>>
>>> https://github.com/apple/swift-evolution/blob/master/process.md
>>>
>>> Thank you,
>>>
>>> -Doug
>>>
>>> Review Manager
>>>
>>> ___
>>> swift-evolution mailing list
>>> swift-evolution@swift.org
>>> https://lists.swift.org/mailman/listinfo/swift-evolution
>>>
>>>
>> ___
>> swift-evolution mailing list
>> swift-evolution@swift.org
>> https://lists.swift.org/mailman/listinfo/swift-evolution
>>
>>
>> 

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

2017-11-30 Thread Xiaodi Wu via swift-evolution
On Thu, Nov 30, 2017 at 5:24 PM, Nate Cook <natec...@apple.com> 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

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

2017-11-30 Thread Xiaodi Wu via swift-evolution
On Thu, Nov 30, 2017 at 2:24 AM, Douglas Gregor via swift-evolution <
swift-evolution@swift.org> wrote:

>
>
> On Nov 26, 2017, at 10:04 PM, Chris Lattner via swift-evolution <
> swift-evolution@swift.org> 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 *think* the
vast majority of bridged use cases can tolerate being `final class` types
instead of `struct` types. I could be wrong though.

Now, as to the possibility of failure: I agree also that eliding the
possibility of lookup failure at the callsite requires further
consideration. Some 

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

2017-11-30 Thread Xiaodi Wu via swift-evolution
> *From:* Xiaodi Wu <xiaodi...@gmail.com>
> *Date:* Nov 24, 2017, 3:05 PM -0600
> *To:* Alejandro Alonso <aalonso...@outlook.com>
> *Cc:* Brent Royal-Gordon <br...@architechies.com>, Steve Canon via
> swift-evolution <swift-evolution@swift.org>
> *Subject:* Re: [swift-evolution] [Proposal] Random Unification
>
> On Fri, Nov 24, 2017 at 2:55 PM, Alejandro Alonso <aalonso...@outlook.com>
> wrote:
>
>> Regarding naming too many things “random”, I’ve talked to many developers
>> on my end and they all don’t find it confusing. This proposal is aimed to
>> make it obvious what the operation is doing when regarding random. I still
>> agree that the proposed solution does just that and in practice feels good
>> to write.
>>
>
> I must disagree quite strongly here. The various facilities you name
> "random" have different semantics, and differences in semantics should be
> reflected in differences in names. It doesn't matter that some people don't
> find it confusing; it is objectively the case that you have named multiple
> distinct facilities with the same name, which leads to confusion. I, for
> one, get confused, and you can see on this list that people are using
> arguments about one property named "random" to discuss another property
> named "random". This is quite an intolerable situation.
>
> I disagree that sample is the correct naming to use here. Getting a sample
>> is a verb in this context which would make it break API guidelines just as
>> well as `pick()`. To sample is to “take a sample or samples of (something)
>> for analysis.” I can agree to use `sampling()` which follows API
>> guidelines. This would result in the following grammar for `[“hi”, “hello”,
>> “hey”].sampling(2)`, “From array, get a sampling of 2"
>>
>
> "Sampling" is fine.
>
>
> On Nov 23, 2017, 12:54 AM -0600, Xiaodi Wu , wrote:
>>
>> On Wed, Nov 22, 2017 at 23:01 Alejandro Alonso <aalonso...@outlook.com>
>> wrote:
>>
>>> Like I’ve said, python has different syntax grammar. We have to read
>>> each call site and form a sentence from it. `random.choice([1, 2, 3])` to
>>> me this reads, “Get a random choice from array”. This makes sense. Slapping
>>> the word choice as an instance property like `[1, 2, 3].choice` reads,
>>> “From array, get choice”. What is choice? This doesn’t make sense at all to
>>> me. To me, the only good solution is `[1, 2, 3].random` which reads, “From
>>> array, get random”. I actually think most users will be able to understand
>>> this at first glance rather than choice (or any or some).
>>>
>>
>> Again, my concern here is that you are proposing to name multiple things
>> "random". If this property should be called "random"--which I'm fine
>> with--then the static method "random(in:)" should be named something else,
>> and the static property "random" should be dropped altogether (as I
>> advocate for reasons we just discussed) or renamed as well. It is simply
>> too confusing that there are so many different "random" methods or
>> properties. Meanwhile, isn't your default RNG also going to be called
>> something like "DefaultRandom"?
>>
>> In regards to the sample() function on collections, I have added this as
>>> I do believe this is something users need. The name I gave it was pick() as
>>> this reads, “From array, pick 2”.
>>>
>>
>> The name "sample" has been used to good effect in other languages, has a
>> well understood meaning in statistics, and is consistent with Swift
>> language guidelines. The operation here is a sampling, and per Swift
>> guidelines the name must be a noun: therefore, 'sample' is fitting. "Pick"
>> does not intrinsically suggest randomness, whereas sample does, and your
>> proposed reading uses it as a verb, whereas Swift guidelines tell us it
>> must be a noun. I would advocate strongly for using well-established
>> terminology and sticking with "sample."
>>
>>
>> On Nov 17, 2017, 8:32 PM -0600, Xiaodi Wu via swift-evolution <
>>> swift-evolution@swift.org>, wrote:
>>>
>>> On Fri, Nov 17, 2017 at 7:11 PM, Brent Royal-Gordon <
>>> br...@architechies.com> wrote:
>>>
>>>> On Nov 17, 2017, at 3:09 PM, Xiaodi Wu via swift-evolution <
>>>> swift-evolution@swift.org> wrote:
>>>>
>>>> But actually, Int.random followed by % is the much bigger issue and a
>>>> very good cauti

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

2017-11-30 Thread Xiaodi Wu via swift-evolution
Right—again, this is yet another difference between two things both named
“random” in this proposal. Almost always, when we say “give me two random
integers,” we want independent random samples from the set of all integers.
But for collections, a very common (and probably more common operation) is
to _sample without replacement_. Conflating the two is how hard-to-detect
errors arise.

On Thu, Nov 30, 2017 at 10:29 Martin Waitz via swift-evolution <
swift-evolution@swift.org> wrote:

> Hi Erica,
>
> > Doesn't `choose` usually take two arguments, the `count` to choose
> (presumably defaulting to 1) and the collection to choose `from`?
>
> This might be useful for collections, when you want to draw several
> elements without drawing the same element twice.
> For ranges of random numbers you usually need independent numbers and just
> call the generator multiple times.
> Both use cases could be provided as overloads (a default argument would
> require that the return value has the same type, which would be unfortunate
> here).
>
> --
> Martin
> ___
> 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] [Review] SE-0191: Eliminate IndexDistance from Collection

2017-11-29 Thread Xiaodi Wu via swift-evolution
Distance must be signed, so it cannot be UInt.
On Wed, Nov 29, 2017 at 11:14 Wallacy  wrote:

> I think is that's why some folks ask for count be UInt (or UInt64 when
> appropriate) some time ago.
>
> I dont know how solve this, but appear to be less painful than current
> IndexDistance.
>
> Em qua, 29 de nov de 2017 às 14:46, Ben Cohen via swift-evolution <
> swift-evolution@swift.org> escreveu:
>
>> You can argue the current status is a bug, but…
>>
>> Welcome to Apple Swift version 4.0.1 (swiftlang-900.0.67 clang-900.0.38).
>> Type :help for assistance.
>>   1> CountableRange.IndexDistance.self
>> $R0: Int.Type = Int
>>   2> (Int64.min..> Execution interrupted. Enter code to recover and continue.
>>
>> On Nov 29, 2017, at 4:04 AM, Xiaodi Wu  wrote:
>>
>> So that we are all clear on the implications of this, if IndexDistance
>> becomes Int, ranges of integers will stop conforming to Collection, because
>> Int.min..> potentially many more.
>>
>> This would entail nontrivial source breakage.
>>
>>
>> On Mon, Nov 27, 2017 at 22:02 Ben Cohen via swift-evolution <
>> swift-evolution@swift.org> wrote:
>>
>>> My suggestion would be: don’t have your Collection-like type conform to
>>> Collection. Give it collection-like methods if you want them, like an
>>> indexing and slicing subscript that takes an Int64. It can still conform to
>>> Sequence.
>>>
>>> In practice, these “huge” collections will be mostly used concretely, so
>>> their Collection conformance doesn’t buy you much. The reality is that very
>>> few generic uses on these types will succeed. You get a few things like
>>> .first, .last etc. for free. But very few algorithms are written to handle
>>> > Int.max lengths (several in the std lib don’t) – it just isn’t practical.
>>> And meanwhile, this is a huge burden on many other use cases.
>>>
>>> The existence of the memory mapped file case is hypothetical. I
>>> canvassed a bit on twitter for some use cases. The only one I got back was
>>> where someone was using IndexDistance to stash other information: but this
>>> isn’t really a legal use of IndexDistance, since it must be numerically
>>> castable to other integer types when needed which would be a lossy
>>> operation so at best, it would just be an optimization.
>>>
>>> On Nov 27, 2017, at 19:29, Nevin Brackett-Rozinsky via swift-evolution <
>>> swift-evolution@swift.org> wrote:
>>>
>>> The proposal mentions one reasonable situation where a larger-than-Int
>>> type would be useful, namely a Collection wrapping a memory-mapped file,
>>> being used on 32-bit systems.
>>>
>>> Is there a recommended migration strategy for this scenario?
>>>
>>> Nevin
>>>
>>>
>>> On Mon, Nov 27, 2017 at 8:34 PM, Douglas Gregor via swift-evolution <
>>> swift-evolution@swift.org> wrote:
>>>
 Hello Swift community,

 The review of SE-0191 "Eliminate IndexDistance from Collection" begins
 now and runs through December 3, 2017. The proposal is available here:


 https://github.com/apple/swift-evolution/blob/master/proposals/0191-eliminate-indexdistance.md

 Reviews are an important part of the Swift evolution process. All
 reviews should be sent to the swift-evolution mailing list at

 https://lists.swift.org/mailman/listinfo/swift-evolution

 or, if you would like to keep your feedback private, directly to the
 review manager. When replying, please try to keep the proposal link at the
 top of the message:

 Proposal link:


 https://github.com/apple/swift-evolution/blob/master/proposals/0191-eliminate-indexdistance.md

 Reply text

 Other replies

 What
 goes into a review?

 The goal of the review process is to improve the proposal under review
 through constructive criticism and, eventually, determine the direction of
 Swift. When writing your review, here are some questions you might want to
 answer in your review:

- What is your evaluation of the proposal?
- Is the problem being addressed significant enough to warrant a
change to Swift?
- Does this proposal fit well with the feel and direction of Swift?
- If you have used other languages or libraries with a similar
feature, how do you feel that this proposal compares to those?
- How much effort did you put into your review? A glance, a quick
reading, or an in-depth study?

 More information about the Swift evolution process is available at

 https://github.com/apple/swift-evolution/blob/master/process.md

 Thank you,

 -Doug

 Review Manager

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


>>> 

Re: [swift-evolution] [Review] SE-0191: Eliminate IndexDistance from Collection

2017-11-29 Thread Xiaodi Wu via swift-evolution
So that we are all clear on the implications of this, if IndexDistance
becomes Int, ranges of integers will stop conforming to Collection, because
Int.min.. wrote:

> My suggestion would be: don’t have your Collection-like type conform to
> Collection. Give it collection-like methods if you want them, like an
> indexing and slicing subscript that takes an Int64. It can still conform to
> Sequence.
>
> In practice, these “huge” collections will be mostly used concretely, so
> their Collection conformance doesn’t buy you much. The reality is that very
> few generic uses on these types will succeed. You get a few things like
> .first, .last etc. for free. But very few algorithms are written to handle
> > Int.max lengths (several in the std lib don’t) – it just isn’t practical.
> And meanwhile, this is a huge burden on many other use cases.
>
> The existence of the memory mapped file case is hypothetical. I canvassed
> a bit on twitter for some use cases. The only one I got back was where
> someone was using IndexDistance to stash other information: but this isn’t
> really a legal use of IndexDistance, since it must be numerically castable
> to other integer types when needed which would be a lossy operation so at
> best, it would just be an optimization.
>
> On Nov 27, 2017, at 19:29, Nevin Brackett-Rozinsky via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> The proposal mentions one reasonable situation where a larger-than-Int
> type would be useful, namely a Collection wrapping a memory-mapped file,
> being used on 32-bit systems.
>
> Is there a recommended migration strategy for this scenario?
>
> Nevin
>
>
> On Mon, Nov 27, 2017 at 8:34 PM, Douglas Gregor via swift-evolution <
> swift-evolution@swift.org> wrote:
>
>> Hello Swift community,
>>
>> The review of SE-0191 "Eliminate IndexDistance from Collection" begins
>> now and runs through December 3, 2017. The proposal is available here:
>>
>>
>> https://github.com/apple/swift-evolution/blob/master/proposals/0191-eliminate-indexdistance.md
>>
>> Reviews are an important part of the Swift evolution process. All reviews
>> should be sent to the swift-evolution mailing list at
>>
>> https://lists.swift.org/mailman/listinfo/swift-evolution
>>
>> or, if you would like to keep your feedback private, directly to the
>> review manager. When replying, please try to keep the proposal link at the
>> top of the message:
>>
>> Proposal link:
>>
>>
>> https://github.com/apple/swift-evolution/blob/master/proposals/0191-eliminate-indexdistance.md
>>
>> Reply text
>>
>> Other replies
>>
>> What
>> goes into a review?
>>
>> The goal of the review process is to improve the proposal under review
>> through constructive criticism and, eventually, determine the direction of
>> Swift. When writing your review, here are some questions you might want to
>> answer in your review:
>>
>>- What is your evaluation of the proposal?
>>- Is the problem being addressed significant enough to warrant a
>>change to Swift?
>>- Does this proposal fit well with the feel and direction of Swift?
>>- If you have used other languages or libraries with a similar
>>feature, how do you feel that this proposal compares to those?
>>- How much effort did you put into your review? A glance, a quick
>>reading, or an in-depth study?
>>
>> More information about the Swift evolution process is available at
>>
>> https://github.com/apple/swift-evolution/blob/master/process.md
>>
>> Thank you,
>>
>> -Doug
>>
>> Review Manager
>>
>> ___
>> swift-evolution mailing list
>> swift-evolution@swift.org
>> https://lists.swift.org/mailman/listinfo/swift-evolution
>>
>>
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Synthesizing Equatable, Hashable, and Comparable for tuple types

2017-11-28 Thread Xiaodi Wu via swift-evolution
On Tue, Nov 28, 2017 at 00:32 Kelvin Ma  wrote:

> On Mon, Nov 27, 2017 at 9:43 PM, Xiaodi Wu  wrote:
>
>> On Mon, Nov 27, 2017 at 5:56 PM, Kelvin Ma  wrote:
>>
>>>
>>>
>>> On Mon, Nov 27, 2017 at 4:21 PM, Xiaodi Wu  wrote:
>>>
 On Mon, Nov 27, 2017 at 15:46 Taylor Swift 
 wrote:

> they use packed buffers of floats, which for type safety are better
> rebound to a structured type. right now (Float, Float, Float) works 
> because
> the tuple is laid out contiguously and the GPU can’t tell the difference
> but it’s not guaranteed. also you’re ignoring all the CPU stages that 
> occur
> before anything even gets sent to the GPU.
>

 Precisely, there is no guarantee of performance if you call these APIs
 with an array of Swift tuples.

>>>
>>> which is exactly why i support a dedicated language-level vector type
>>> which guarantees contiguous, fixed storage, and which the compiler knows
>>> about so it can vectorize operations on them.
>>>
>>
>> That's an entirely separate discussion.
>>
>>
>>> tuples right now try to fill too many roles and that makes life
>>> difficult for both the compiler and the programmer. however, until then, we
>>> need some kind of common, fixed layout currency type for vector data, and
>>> by implementation-detail, *tuples are our best option* since for some
>>> reason everyone is so opposed to the simple solution of baking vec2,
>>> vec3, … vec5 into the language and the generic integer Vector
>>> solution everyone wants likely isn’t going to materialize for the
>>> foreseeable future.
>>>
>>
>> Disagree. If you want a particular memory layout, define your type in C.
>> Swift's interop story is very good, and your type will have a fixed layout
>> forever.
>>
>
> “*write it in c and import it*” is *not* a solution,, it is a workaround.
>

Yes, that’s what we’re talking about here: workarounds to lack of a fixed
layout type. I’m saying C is the “best option” workaround, not tuples.

plus since it lives across the module boundary, it’s effectively opaque to
> compiler optimizations.
>
What sorts of optimizations are you referring to? Recall that we are
talking about taking a value and unsafe bitcasting for the purposes of
calling other C APIs.
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Pitch #2] Introduce User-defined "Dynamic Member Lookup" Types

2017-11-27 Thread Xiaodi Wu via swift-evolution
Better yet, since we previously started to require “@objc dynamic” instead
of “dynamic” with the notion that perhaps there would be some future
non-ObjC dynamism, we *could* have it spelt “dynamic member(_:)”.

But this is all just spelling now; I think the overall design is compelling
in its elegance and power.
On Mon, Nov 27, 2017 at 20:22 Brent Royal-Gordon via swift-evolution <
swift-evolution@swift.org> wrote:

> On Nov 25, 2017, at 3:16 PM, Chris Lattner via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> Just to talk to myself a bit here, but I’ve come to realize that the right
> design really is to have a simple empty marker protocol like this:
>
>
> If you're reaching this point. why have a marker protocol at all? Why not
> treat `subscript(dynamicMember:)` specially on any type that has it, or
> have an `@dynamicMember subscript(_:)` attribute, or introduce an entire
> new `dynamicMember(_:)` declaration?
>
> --
> Brent Royal-Gordon
> Architechies
>
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Synthesizing Equatable, Hashable, and Comparable for tuple types

2017-11-25 Thread Xiaodi Wu via swift-evolution
On Sat, Nov 25, 2017 at 5:21 PM, Mike Kluev  wrote:

> On 25 November 2017 at 23:07, Xiaodi Wu  wrote:
>
>> Not sure what you’re asking. Equatable is a protocol.
>>
>
> that's the point. i mean, if user writes this:
>
> extension (Equatable, Equatable) : Equatable
>
> what *else* could he mean other than this:
>
> extension  (T, R) : Equatable
>

No, it would mean extending the concrete type `(Equatable, Equatable)`
(which has other roadblocks to becoming possible because Equatable has Self
requirements).


> and if it is indeed the only reasonable meaning we can think of - i'd say
> the first notation is nicer.
>
>
>> For a protocol P, (P, P) is a concrete type with two elements each of
>> existential type P.
>>
>
> this part i do not understand. protocol is not an existential type. or is
> it?
>

Ah. You seem to be unfamiliar with protocol existentials. Protocols
(currently, only those without Self or associated type requirements, for
various implementation reasons) are themselves types. For example, you can
write:

```
protocol P { }
extension Int : P { }
let x: P = 42
```

In this example, x is of type `P`, not of type `Int`. Let's clarify the
difference:

```
extension Array where Element == P {
  func hi() {
print("Hello")
  }
}

extension Array where Element : P {
  func hi() {
print("World!")
  }
}

let y: [P] = [x]
let z: [Int] = [x as Int]

y.hi() // Prints "Hello"
z.hi() // Prints "World!"
```

Moreover, if we do not write the first `extension Array`, then `y.hi()`
doesn't compile. This helps to illustrate that P does not conform to itself.


For a type T : P, a tuple of type (T, T) is not a tuple of type (P, P). If
>> we can extend tuples, you can write a generic algorithm that works with any
>> type (T, T) where T : P, and/or you can write an algorithm that works with
>> concrete type (P, P). Note that there is no overlap between these two
>> because existential type P does not conform to protocol P.
>>
>>
> Mike
>
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Pre-pitch] Conditional default arguments

2017-11-25 Thread Xiaodi Wu via swift-evolution
On Sat, Nov 25, 2017 at 4:44 PM, Tony Allevato <tony.allev...@gmail.com>
wrote:

> On Sat, Nov 25, 2017 at 2:35 PM Xiaodi Wu <xiaodi...@gmail.com> wrote:
>
>> On Sat, Nov 25, 2017 at 4:25 PM, Tony Allevato <tony.allev...@gmail.com>
>> wrote:
>>
>>> On Sat, Nov 25, 2017 at 1:16 PM Xiaodi Wu <xiaodi...@gmail.com> wrote:
>>>
>>>> On Sat, Nov 25, 2017 at 15:06 Matthew Johnson <matt...@anandabits.com>
>>>> wrote:
>>>>
>>>>> On Nov 25, 2017, at 1:28 PM, Tony Allevato via swift-evolution <
>>>>> swift-evolution@swift.org> wrote:
>>>>>
>>>>> On Fri, Nov 24, 2017 at 7:18 PM Xiaodi Wu via swift-evolution <
>>>>> swift-evolution@swift.org> wrote:
>>>>>
>>>>>
>>>>> It's kludgy, but we could have something like:
>>>>>>
>>>>>> ```
>>>>>> @defaultArgument(configuration = (), where R.Configuration == Void)
>>>>>> @defaultArgument(actionHandler = { _ in }, where R.Action == Never)
>>>>>> func makeResource(with configuration: R.Configuration, actionHandler:
>>>>>> @escaping (R.Action) -> Void) -> R { ... }
>>>>>> ```
>>>>>>
>>>>>> I don't like that we'd be setting a default argument on something
>>>>>> lexically before even encountering it in the declaration, but it's
>>>>>> serviceable.
>>>>>>
>>>>>
>>>>>
>>>>> What if we could take advantage of the fact that you can have
>>>>> non-constant expressions in default arguments? Overload resolution could
>>>>> already do most of the job—what we need on top of that is a way for the
>>>>> author to say that “if no overload matches, then it’s not an error—just
>>>>> don’t have a default argument in that case”. Something like SFINAE in C++,
>>>>> but more explicit.
>>>>>
>>>>> I’m imagining something like this:
>>>>>
>>>>> func defaultConfiguration() -> Void {
>>>>>   return ()
>>>>> }
>>>>> func defaultActionHandler() -> (Never) -> Void {
>>>>>   return { _ in }
>>>>> }
>>>>> struct ResourceDescription {
>>>>>   func makeResource(
>>>>> with configuration: R.Configuration *=?* defaultConfiguration(),
>>>>> actionHandler: @escaping (R.Action) -> Void *=?* 
>>>>> defaultActionHandler()
>>>>>   ) -> R {
>>>>> // create a resource using the provided configuration
>>>>> // connect the action handler
>>>>> // return the resource
>>>>>   }
>>>>> }
>>>>>
>>>>> The main difference here is the strawman =? syntax, which would
>>>>> indicate that “the default argument exists if there is a way the RHS can 
>>>>> be
>>>>> satisfied for some instances of the generic arguments; otherwise, there is
>>>>> no default”, instead of today’s behavior where it would be an error. There
>>>>> could be multiple overloads of defaultConfiguration and
>>>>> defaultActionHandler (even ones that are themselves generic) and it
>>>>> would do the right thing when there are matches and when there aren’t.
>>>>>
>>>>> I like this approach because it mostly takes advantage of existing
>>>>> language features and is fairly lightweight in terms of how it’s expressed
>>>>> in code compared to regular default arguments—we’d just need to design the
>>>>> new operator and type-checker logic around it.
>>>>>
>>>>> This is an interesting approach.  One advantage to something in this
>>>>> direction is that it could support defining different defaults for the 
>>>>> same
>>>>> argument under different constraints by overloading the default argument
>>>>> factories on their return type.
>>>>>
>>>>> One concern I have is that it doesn’t allows us to clearly define
>>>>> under which constraints a default argument is available.  I suspect this
>>>>> might be problematic especially for public interfaces where source
>>>>> compatibility is a concern.
>>>>>
>>>>
>>>> It's certainly an interesting idea but it would suggest that

Re: [swift-evolution] Synthesizing Equatable, Hashable, and Comparable for tuple types

2017-11-25 Thread Xiaodi Wu via swift-evolution
On Sat, Nov 25, 2017 at 16:44 Mike Kluev  wrote:

> On 25 November 2017 at 22:38, Xiaodi Wu  wrote:
>
>> On Sat, Nov 25, 2017 at 4:30 PM, Mike Kluev  wrote:
>>
>>>
 i haven't encounter this notation before so it looks strange and
>>> requires some effort to decipher. if it was e.g. in this form:
>>>
>>> extension (Equatable...) : Equatable
>>>
>>> then it would be immediately obvious what it means, IMHO
>>>
>>
>> That reads to me like you are extending a tuple of type `(Equatable...)`.
>> This is not the same as extending a tuple of type `(E...) where ...E :
>> Equatable`.
>>
>
> and if Equatable is not a type but a protocol then the practical
> difference is what ?
>

Not sure what you’re asking. Equatable is a protocol.

For a protocol P, (P, P) is a concrete type with two elements each of
existential type P. For a type T : P, a tuple of type (T, T) is not a tuple
of type (P, P). If we can extend tuples, you can write a generic algorithm
that works with any type (T, T) where T : P, and/or you can write an
algorithm that works with concrete type (P, P). Note that there is no
overlap between these two because existential type P does not conform to
protocol P.
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Synthesizing Equatable, Hashable, and Comparable for tuple types

2017-11-25 Thread Xiaodi Wu via swift-evolution
On Sat, Nov 25, 2017 at 4:30 PM, Mike Kluev  wrote:

> On 25 November 2017 at 16:04, Xiaodi Wu  wrote:
>
>>
>> The workaround substantially bloats the standard library, and the result
>> is nothing close to the same because your type is still not Equatable. This
>> means that it cannot benefit from any generic algorithms. For example, an
>> array of such tuples cannot be Equatable in turn.
>>
>>>
>>
> i see. then the current workaround is not deep enough.
>
>
>> speaking of ugliness, the ellipsis on the left of names is quite ugly:
>>>
>>>  extension<...Elements : Equatable> (Elements...) : Equatable
>>>
>>
>> Seems perfectly fine to me.
>>
>
> i haven't encounter this notation before so it looks strange and requires
> some effort to decipher. if it was e.g. in this form:
>
> extension (Equatable...) : Equatable
>
> then it would be immediately obvious what it means, IMHO
>

That reads to me like you are extending a tuple of type `(Equatable...)`.
This is not the same as extending a tuple of type `(E...) where ...E :
Equatable`.
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Pre-pitch] Conditional default arguments

2017-11-25 Thread Xiaodi Wu via swift-evolution
On Sat, Nov 25, 2017 at 4:25 PM, Tony Allevato <tony.allev...@gmail.com>
wrote:

> On Sat, Nov 25, 2017 at 1:16 PM Xiaodi Wu <xiaodi...@gmail.com> wrote:
>
>> On Sat, Nov 25, 2017 at 15:06 Matthew Johnson <matt...@anandabits.com>
>> wrote:
>>
>>> On Nov 25, 2017, at 1:28 PM, Tony Allevato via swift-evolution <
>>> swift-evolution@swift.org> wrote:
>>>
>>> On Fri, Nov 24, 2017 at 7:18 PM Xiaodi Wu via swift-evolution <
>>> swift-evolution@swift.org> wrote:
>>>
>>>
>>> It's kludgy, but we could have something like:
>>>>
>>>> ```
>>>> @defaultArgument(configuration = (), where R.Configuration == Void)
>>>> @defaultArgument(actionHandler = { _ in }, where R.Action == Never)
>>>> func makeResource(with configuration: R.Configuration, actionHandler:
>>>> @escaping (R.Action) -> Void) -> R { ... }
>>>> ```
>>>>
>>>> I don't like that we'd be setting a default argument on something
>>>> lexically before even encountering it in the declaration, but it's
>>>> serviceable.
>>>>
>>>
>>>
>>> What if we could take advantage of the fact that you can have
>>> non-constant expressions in default arguments? Overload resolution could
>>> already do most of the job—what we need on top of that is a way for the
>>> author to say that “if no overload matches, then it’s not an error—just
>>> don’t have a default argument in that case”. Something like SFINAE in C++,
>>> but more explicit.
>>>
>>> I’m imagining something like this:
>>>
>>> func defaultConfiguration() -> Void {
>>>   return ()
>>> }
>>> func defaultActionHandler() -> (Never) -> Void {
>>>   return { _ in }
>>> }
>>> struct ResourceDescription {
>>>   func makeResource(
>>> with configuration: R.Configuration *=?* defaultConfiguration(),
>>> actionHandler: @escaping (R.Action) -> Void *=?* defaultActionHandler()
>>>   ) -> R {
>>> // create a resource using the provided configuration
>>> // connect the action handler
>>> // return the resource
>>>   }
>>> }
>>>
>>> The main difference here is the strawman =? syntax, which would
>>> indicate that “the default argument exists if there is a way the RHS can be
>>> satisfied for some instances of the generic arguments; otherwise, there is
>>> no default”, instead of today’s behavior where it would be an error. There
>>> could be multiple overloads of defaultConfiguration and
>>> defaultActionHandler (even ones that are themselves generic) and it
>>> would do the right thing when there are matches and when there aren’t.
>>>
>>> I like this approach because it mostly takes advantage of existing
>>> language features and is fairly lightweight in terms of how it’s expressed
>>> in code compared to regular default arguments—we’d just need to design the
>>> new operator and type-checker logic around it.
>>>
>>> This is an interesting approach.  One advantage to something in this
>>> direction is that it could support defining different defaults for the same
>>> argument under different constraints by overloading the default argument
>>> factories on their return type.
>>>
>>> One concern I have is that it doesn’t allows us to clearly define under
>>> which constraints a default argument is available.  I suspect this might be
>>> problematic especially for public interfaces where source compatibility is
>>> a concern.
>>>
>>
>> It's certainly an interesting idea but it would suggest that the
>> constraints under which a default argument is available can change at
>> runtime. I'm concerned, like you, that this is difficult to reason about.
>> It is still unclear to me how widespread the underlying issue is that
>> requires conditional default arguments, but the conversation thus far has
>> been about compile-time constraints and Tony's design seems to envision
>> much more than that.
>>
>
> This runtime/reasoning problem *already exists* today with default
> arguments, because you can write something like this:
>
> struct Foo {
>   static var defaultExponent = 2.0
>
>   func raise(_ x: Double, to exponent: Double = defaultExponent) {
> print(pow(x, exponent))
>   }
> }
> Foo().raise(4)  // "16.0"Foo.defaultExponent = 3.0Foo().raise(4)  // "64.0"
>
> S

Re: [swift-evolution] [Pre-pitch] Conditional default arguments

2017-11-25 Thread Xiaodi Wu via swift-evolution
On Sat, Nov 25, 2017 at 15:06 Matthew Johnson <matt...@anandabits.com>
wrote:

> On Nov 25, 2017, at 1:28 PM, Tony Allevato via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> On Fri, Nov 24, 2017 at 7:18 PM Xiaodi Wu via swift-evolution <
> swift-evolution@swift.org> wrote:
>
>
> It's kludgy, but we could have something like:
>>
>> ```
>> @defaultArgument(configuration = (), where R.Configuration == Void)
>> @defaultArgument(actionHandler = { _ in }, where R.Action == Never)
>> func makeResource(with configuration: R.Configuration, actionHandler:
>> @escaping (R.Action) -> Void) -> R { ... }
>> ```
>>
>> I don't like that we'd be setting a default argument on something
>> lexically before even encountering it in the declaration, but it's
>> serviceable.
>>
>
>
> What if we could take advantage of the fact that you can have non-constant
> expressions in default arguments? Overload resolution could already do most
> of the job—what we need on top of that is a way for the author to say that
> “if no overload matches, then it’s not an error—just don’t have a default
> argument in that case”. Something like SFINAE in C++, but more explicit.
>
> I’m imagining something like this:
>
> func defaultConfiguration() -> Void {
>   return ()
> }
> func defaultActionHandler() -> (Never) -> Void {
>   return { _ in }
> }
> struct ResourceDescription {
>   func makeResource(
> with configuration: R.Configuration *=?* defaultConfiguration(),
> actionHandler: @escaping (R.Action) -> Void *=?* defaultActionHandler()
>   ) -> R {
> // create a resource using the provided configuration
> // connect the action handler
> // return the resource
>   }
> }
>
> The main difference here is the strawman =? syntax, which would indicate
> that “the default argument exists if there is a way the RHS can be
> satisfied for some instances of the generic arguments; otherwise, there is
> no default”, instead of today’s behavior where it would be an error. There
> could be multiple overloads of defaultConfiguration and
> defaultActionHandler (even ones that are themselves generic) and it would
> do the right thing when there are matches and when there aren’t.
>
> I like this approach because it mostly takes advantage of existing
> language features and is fairly lightweight in terms of how it’s expressed
> in code compared to regular default arguments—we’d just need to design the
> new operator and type-checker logic around it.
>
> This is an interesting approach.  One advantage to something in this
> direction is that it could support defining different defaults for the same
> argument under different constraints by overloading the default argument
> factories on their return type.
>
> One concern I have is that it doesn’t allows us to clearly define under
> which constraints a default argument is available.  I suspect this might be
> problematic especially for public interfaces where source compatibility is
> a concern.
>

It's certainly an interesting idea but it would suggest that the
constraints under which a default argument is available can change at
runtime. I'm concerned, like you, that this is difficult to reason about.
It is still unclear to me how widespread the underlying issue is that
requires conditional default arguments, but the conversation thus far has
been about compile-time constraints and Tony's design seems to envision
much more than that.

I think I prefer Xiaodi’s suggestion for that reason.  His approach could
> also support multiple defaults for the same parameter as long as the
> constraints are not allowed to overlap (overlapping constraints would
> result in ambiguity similar to ambiguous overload resolution) or an
> explicit argument is required if they do.
>
>
>
>
>
>>
>> On Fri, Nov 24, 2017 at 8:36 PM, T.J. Usiyan via swift-evolution <
>> swift-evolution@swift.org> wrote:
>>
>>> I am all for this. are many types where there is an obvious 'zero' or
>>> 'default' value and the ability to express "use that when possible" without
>>> an overload is welcome.
>>>
>>>
>>> The best thing that I can think of right now, in terms of syntax, is
>>> actually using @overload
>>>
>>> ```
>>> struct ResourceDescription {
>>>
>>>   func makeResource(with configuration: R.Configuration, actionHandler:
>>> @escaping (R.Action) -> Void) -> R
>>>  @overload(R.Configuration == Void) func makeResource(actionHandler:
>>> @escaping (R.Action) -> Void) -> R
>>> @overload(R.Action == Never)  func makeReso

Re: [swift-evolution] Synthesizing Equatable, Hashable, and Comparable for tuple types

2017-11-25 Thread Xiaodi Wu via swift-evolution
On Sat, Nov 25, 2017 at 06:35 Mike Kluev  wrote:

> On 25 November 2017 at 03:12, Xiaodi Wu  wrote:
>
>> On Fri, Nov 24, 2017 at 9:08 PM, Mike Kluev via swift-evolution <
>> swift-evolution@swift.org> wrote:
>>
>>> On 24 November 2017 at 23:47, Douglas Gregor  wrote:
>>>

 e.g., making all tuples of Equatable elements Equatable


>>> that's already the case.. (all tuples of equatable elements are
>>> equatable). no?
>>>
>>
>> No, tuples do not conform to any protocols. There are hardcoded
>> implementations of `==` up to some arity in the stdlib to partially
>> mitigate the lack of protocol conformance.
>>
>>
> to me as a user the end result is the same...
> probably we need a better convincing example of what users may want that
> doesn't have a workaround now.
>

The workaround substantially bloats the standard library, and the result is
nothing close to the same because your type is still not Equatable. This
means that it cannot benefit from any generic algorithms. For example, an
array of such tuples cannot be Equatable in turn.

>
speaking of ugliness, the ellipsis on the left of names is quite ugly:
>
>  extension<...Elements : Equatable> (Elements...) : Equatable
>

Seems perfectly fine to me.
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Pitch] Raw mode string literals

2017-11-24 Thread Xiaodi Wu via swift-evolution
On Sat, Nov 25, 2017 at 12:08 AM, Chris Lattner  wrote:

>
>
> On Nov 24, 2017, at 7:52 PM, Xiaodi Wu  wrote:
>
> etc.  Even if we don’t have a “default regex” for types, it would still be
>> awesome to be able to write:
>>
>>
>> if case /(let name: [a-zA-Z]+) (let count: Int: [0-9]+)/ =
>> getSomeString() {
>>print(name, count)
>> }
>>
>> and have that transparently invoke and check the Int?(string) failable
>> initializer.
>>
>
> Yes, these are very interesting options to explore, and you're right that
> if we want to go down this road, then we'd need to imbue regex literals
> with certain "smarts" as opposed to having lenient regex literal parsing
> that entirely defers validation to a concrete regex type conforming to
> ExpressibleByRegularExpressionLiteral.
>
> I don't think it's an all-or-nothing proposition, though, as to whether
> the literal or the conforming type performs the validation. Personally, I
> think one of the strengths of Swift's literals is that they are
> intrinsically untyped and that multiple concrete types are expressible by
> them.
>
>
> Right, but the string literal syntaxes we have (single and multiline) do
> not allow different grammars (e.g. escape sequences) depending on what type
> they are inferred to.  Wouldn’t it be odd if a string literal accepted
> “\x12\u1212\U1212” when it converts to a "const char *” but accepted
> “\u{12345}” when passed to a bridged Dart API?
>

...And here we come full circle. The original proposal is precisely to have
a different type of string literal that accepts/rejects different escape
sequences. In my initial reply, I wrote that (should raw strings be
sufficiently motivated that some sort of solution is clearly desirable) one
avenue to explore is redesigning literals to allow conforming types to
access the "raw" literal, free of all but the most minimal processing, so
that the type can choose the grammar rather than the literal. In so doing,
we avoid having to hardcode new "flavors" of string literal.

It is precisely in observing these repeated requests for now flavors of
string literals, as well as existing shortcomings of integer and float
literals for supporting BigInt and Decimal types, that leads me to think
that we should exactly allow what you describe as "odd."
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


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

2017-11-24 Thread Xiaodi Wu via swift-evolution
1, 2, 3].random` which reads, “From
>>>> array, get random”. I actually think most users will be able to understand
>>>> this at first glance rather than choice (or any or some).
>>>>
>>>
>>> Again, my concern here is that you are proposing to name multiple things
>>> "random". If this property should be called "random"--which I'm fine
>>> with--then the static method "random(in:)" should be named something else,
>>> and the static property "random" should be dropped altogether (as I
>>> advocate for reasons we just discussed) or renamed as well. It is simply
>>> too confusing that there are so many different "random" methods or
>>> properties. Meanwhile, isn't your default RNG also going to be called
>>> something like "DefaultRandom"?
>>>
>>> In regards to the sample() function on collections, I have added this as
>>>> I do believe this is something users need. The name I gave it was pick() as
>>>> this reads, “From array, pick 2”.
>>>>
>>>
>>> The name "sample" has been used to good effect in other languages, has a
>>> well understood meaning in statistics, and is consistent with Swift
>>> language guidelines. The operation here is a sampling, and per Swift
>>> guidelines the name must be a noun: therefore, 'sample' is fitting. "Pick"
>>> does not intrinsically suggest randomness, whereas sample does, and your
>>> proposed reading uses it as a verb, whereas Swift guidelines tell us it
>>> must be a noun. I would advocate strongly for using well-established
>>> terminology and sticking with "sample."
>>>
>>>
>>> On Nov 17, 2017, 8:32 PM -0600, Xiaodi Wu via swift-evolution <
>>>> swift-evolution@swift.org>, wrote:
>>>>
>>>> On Fri, Nov 17, 2017 at 7:11 PM, Brent Royal-Gordon <
>>>> br...@architechies.com> wrote:
>>>>
>>>>> On Nov 17, 2017, at 3:09 PM, Xiaodi Wu via swift-evolution <
>>>>> swift-evolution@swift.org> wrote:
>>>>>
>>>>> But actually, Int.random followed by % is the much bigger issue and a
>>>>> very good cautionary tale for why T.random is not a good idea. Swift 
>>>>> should
>>>>> help users do the correct thing, and getting a random value across the 
>>>>> full
>>>>> domain and computing an integer modulus is never the correct thing to do
>>>>> because of modulo bias, yet it's a very common error to make. We are much
>>>>> better off eliminating this API and encouraging use of the correct API,
>>>>> thereby reducing the likelihood of users making this category of error.
>>>>>
>>>>>
>>>>> Amen.
>>>>>
>>>>> If (and I agree with this) the range-based notation is less intuitive
>>>>> (0..<10.random is certainly less discoverable than Int.random), then we
>>>>> ought to offer an API in the form of `Int.random(in:)` but not
>>>>> `Int.random`. This does not preclude a `Collection.random` API as 
>>>>> Alejandro
>>>>> proposes, of course, and that has independent value as Gwendal says.
>>>>>
>>>>>
>>>>> If we're not happy with the range syntax, maybe we should put
>>>>> `random(in:)`-style methods on the RNG protocol as extension methods
>>>>> instead. Then there's a nice, uniform style:
>>>>>
>>>>> let diceRoll = rng.random(in: 1...6)
>>>>> let card = rng.random(in: deck)
>>>>> let isHeads = rng.random(in: [true, false])
>>>>> let probability = rng.random(in: 0.0...1.0) // Special FloatingPoint
>>>>> overload
>>>>>
>>>>> The only issue is that this makes the default RNG's name really
>>>>> important. Something like:
>>>>>
>>>>> DefaultRandom.shared.random(in: 1...6)
>>>>>
>>>>> Will be a bit of a pain for users.
>>>>>
>>>>
>>>> I did in fact implement this style of RNG in NumericAnnex, but I'm not
>>>> satisfied with the design myself. Not only is it a bit of an ergonomic
>>>> thorn, there's also another drawback that actually has weighty 
>>>> implications:
>>>>
>>>> Users aren't conditioned to reuse RNG instances. Perhaps, it is because
>>>> it can &qu

Re: [swift-evolution] [Pitch] Raw mode string literals

2017-11-24 Thread Xiaodi Wu via swift-evolution
On Fri, Nov 24, 2017 at 6:25 PM, Chris Lattner  wrote:

>
>
> On Nov 24, 2017, at 4:15 PM, Chris Lattner  wrote:
>
>
> than the same type having a collection of named matches using the usual
> Perl syntax?
>
>   if case /(?[a-zA-Z]+) (?[a-zA-Z]+)/ =
> getSomeString() {
> print(Regex.captured["firstName"], Regex.captured["lastName"])
>   }
>
>
> Personally, I really don’t like this.  It turns a structured problem into
> one that violates DRY and loses the structure inherent in the solution.
> Also, while theoretically the dictionary could be optimized away, in
> practice that would be difficult to do without heroics.
>
>
> One other minor and obscure point: if the compiler is aware of the regex
> grammar it can properly type the matches, I can imagine the following cases:
>
> if case /(let name: [a-zA-Z]+) (let count: Int)/ = getSomeString() {
>print(name, count)
> }
>
>
> -> name has type String, count has type Int (and matches [0-9]+)
>
>
> if case /(let name: [a-zA-Z]+)? (let count: Int)/ = getSomeString() {
>print(name, count)
> }
>
> -> name has type String?
>
> if case /(let name: [a-zA-Z]+)* (let count: Int)/ = getSomeString() {
>print(name, count)
> }
>
> -> name has type [String]
>
> etc.  Even if we don’t have a “default regex” for types, it would still be
> awesome to be able to write:
>
>
> if case /(let name: [a-zA-Z]+) (let count: Int: [0-9]+)/ = getSomeString()
> {
>print(name, count)
> }
>
> and have that transparently invoke and check the Int?(string) failable
> initializer.
>

Yes, these are very interesting options to explore, and you're right that
if we want to go down this road, then we'd need to imbue regex literals
with certain "smarts" as opposed to having lenient regex literal parsing
that entirely defers validation to a concrete regex type conforming to
ExpressibleByRegularExpressionLiteral.

I don't think it's an all-or-nothing proposition, though, as to whether the
literal or the conforming type performs the validation. Personally, I think
one of the strengths of Swift's literals is that they are intrinsically
untyped and that multiple concrete types are expressible by them. Whether
or not we think one or another regex syntax is best doesn't necessarily
mean we need to preclude other regex engines from interacting with a regex
literal. Rather, just like string interpolation literals allow the compiler
to parse some "stuff" inside the quotation marks, we can have some syntax
that allows for regex patterns to have segments parsed by the compiler for
binding without locking down regex syntax entirely. For instance, just as
the compiler parses `\(...)` inside string literals, suppose it parses
`(let...)` and `(var...)` inside regex literals.
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


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

2017-11-24 Thread Xiaodi Wu via swift-evolution
sion. I, for
> one, get confused, and you can see on this list that people are using
> arguments about one property named "random" to discuss another property
> named "random". This is quite an intolerable situation.
>
> I disagree that sample is the correct naming to use here. Getting a sample
>> is a verb in this context which would make it break API guidelines just as
>> well as `pick()`. To sample is to “take a sample or samples of (something)
>> for analysis.” I can agree to use `sampling()` which follows API
>> guidelines. This would result in the following grammar for `[“hi”, “hello”,
>> “hey”].sampling(2)`, “From array, get a sampling of 2"
>>
>
> "Sampling" is fine.
>
>
> On Nov 23, 2017, 12:54 AM -0600, Xiaodi Wu , wrote:
>>
>> On Wed, Nov 22, 2017 at 23:01 Alejandro Alonso <aalonso...@outlook.com>
>> wrote:
>>
>>> Like I’ve said, python has different syntax grammar. We have to read
>>> each call site and form a sentence from it. `random.choice([1, 2, 3])` to
>>> me this reads, “Get a random choice from array”. This makes sense. Slapping
>>> the word choice as an instance property like `[1, 2, 3].choice` reads,
>>> “From array, get choice”. What is choice? This doesn’t make sense at all to
>>> me. To me, the only good solution is `[1, 2, 3].random` which reads, “From
>>> array, get random”. I actually think most users will be able to understand
>>> this at first glance rather than choice (or any or some).
>>>
>>
>> Again, my concern here is that you are proposing to name multiple things
>> "random". If this property should be called "random"--which I'm fine
>> with--then the static method "random(in:)" should be named something else,
>> and the static property "random" should be dropped altogether (as I
>> advocate for reasons we just discussed) or renamed as well. It is simply
>> too confusing that there are so many different "random" methods or
>> properties. Meanwhile, isn't your default RNG also going to be called
>> something like "DefaultRandom"?
>>
>> In regards to the sample() function on collections, I have added this as
>>> I do believe this is something users need. The name I gave it was pick() as
>>> this reads, “From array, pick 2”.
>>>
>>
>> The name "sample" has been used to good effect in other languages, has a
>> well understood meaning in statistics, and is consistent with Swift
>> language guidelines. The operation here is a sampling, and per Swift
>> guidelines the name must be a noun: therefore, 'sample' is fitting. "Pick"
>> does not intrinsically suggest randomness, whereas sample does, and your
>> proposed reading uses it as a verb, whereas Swift guidelines tell us it
>> must be a noun. I would advocate strongly for using well-established
>> terminology and sticking with "sample."
>>
>>
>> On Nov 17, 2017, 8:32 PM -0600, Xiaodi Wu via swift-evolution <
>>> swift-evolution@swift.org>, wrote:
>>>
>>> On Fri, Nov 17, 2017 at 7:11 PM, Brent Royal-Gordon <
>>> br...@architechies.com> wrote:
>>>
>>>> On Nov 17, 2017, at 3:09 PM, Xiaodi Wu via swift-evolution <
>>>> swift-evolution@swift.org> wrote:
>>>>
>>>> But actually, Int.random followed by % is the much bigger issue and a
>>>> very good cautionary tale for why T.random is not a good idea. Swift should
>>>> help users do the correct thing, and getting a random value across the full
>>>> domain and computing an integer modulus is never the correct thing to do
>>>> because of modulo bias, yet it's a very common error to make. We are much
>>>> better off eliminating this API and encouraging use of the correct API,
>>>> thereby reducing the likelihood of users making this category of error.
>>>>
>>>>
>>>> Amen.
>>>>
>>>> If (and I agree with this) the range-based notation is less intuitive
>>>> (0..<10.random is certainly less discoverable than Int.random), then we
>>>> ought to offer an API in the form of `Int.random(in:)` but not
>>>> `Int.random`. This does not preclude a `Collection.random` API as Alejandro
>>>> proposes, of course, and that has independent value as Gwendal says.
>>>>
>>>>
>>>> If we're not happy with the range syntax, maybe we should put
>>>> `random(in:)`-style methods on the RNG protocol as extension methods
>>>

Re: [swift-evolution] [Pre-pitch] Conditional default arguments

2017-11-24 Thread Xiaodi Wu via swift-evolution
It's kludgy, but we could have something like:

```
@defaultArgument(configuration = (), where R.Configuration == Void)
@defaultArgument(actionHandler = { _ in }, where R.Action == Never)
func makeResource(with configuration: R.Configuration, actionHandler:
@escaping (R.Action) -> Void) -> R { ... }
```

I don't like that we'd be setting a default argument on something lexically
before even encountering it in the declaration, but it's serviceable.


On Fri, Nov 24, 2017 at 8:36 PM, T.J. Usiyan via swift-evolution <
swift-evolution@swift.org> wrote:

> I am all for this. are many types where there is an obvious 'zero' or
> 'default' value and the ability to express "use that when possible" without
> an overload is welcome.
>
>
> The best thing that I can think of right now, in terms of syntax, is
> actually using @overload
>
> ```
> struct ResourceDescription {
>
>   func makeResource(with configuration: R.Configuration, actionHandler:
> @escaping (R.Action) -> Void) -> R
>  @overload(R.Configuration == Void) func makeResource(actionHandler:
> @escaping (R.Action) -> Void) -> R
> @overload(R.Action == Never)  func makeResource(with configuration:
> R.Configuration) -> R
> {
> // create a resource using the provided configuration
> // connect the action handler
> // return the resource
>   }
> }
> ```
>
>
> This isn't great though…
>
> On Fri, Nov 24, 2017 at 6:11 PM, Matthew Johnson via swift-evolution <
> swift-evolution@swift.org> wrote:
>
>> As mentioned in my prior message, I currently have a PR open to update
>> the generics manifesto (https://github.com/apple/swift/pull/13012).  I
>> removed one topic from that update at Doug Gregor’s request that it be
>> discussed on the list first.
>>
>> The idea is to add the ability to make default arguments conditional
>> (i.e. depend on generic constraints).  It is currently possible to emulate
>> conditional default arguments using an overload set.  This is verbose,
>> especially when several arguments are involved.  Here is an example use
>> case using the overload method to emulate this feature:
>>
>> ```swift
>> protocol Resource {
>>   associatedtype Configuration
>>   associatedtype Action
>> }
>> struct ResourceDescription {
>>   func makeResource(with configuration: R.Configuration, actionHandler:
>> @escaping (R.Action) -> Void) -> R {
>> // create a resource using the provided configuration
>> // connect the action handler
>> // return the resource
>>   }
>> }
>>
>> extension ResourceDescription where R.Configuration == Void {
>>   func makeResource(actionHandler: @escaping (R.Action) -> Void) -> R {
>> return makeResource(with: (), actionHandler: actionHandler)
>>   }
>> }
>>
>> extension ResourceDescription where R.Action == Never {
>>   func makeResource(with configuration: R.Configuration) -> R {
>> return makeResource(with: configuration, actionHandler: { _ in })
>>   }
>> }
>>
>> extension ResourceDescription where R.Configuration == Void, R.Action ==
>> Never {
>>   func makeResource() -> R {
>> return makeResource(with: (), actionHandler: { _ in })
>>   }
>> }
>>
>> ```
>>
>> Adding language support for defining these more directly would eliminate
>> a lot of boilerplate and reduce the need for overloads.  Doug mentioned
>> that it may also help simplify associated type inference (
>> https://github.com/apple/swift/pull/13012#discussion_r152124535).
>>
>> The reason that I call this a pre-pitch and one reason Doug requested it
>> be discussed on list is that I haven’t thought of a good way to express
>> this syntactically.  I am interested in hearing general feedback on the
>> idea.  I am also looking for syntax suggestions.
>>
>> Matthew
>>
>> ___
>> swift-evolution mailing list
>> swift-evolution@swift.org
>> https://lists.swift.org/mailman/listinfo/swift-evolution
>>
>>
>
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Synthesizing Equatable, Hashable, and Comparable for tuple types

2017-11-24 Thread Xiaodi Wu via swift-evolution
On Fri, Nov 24, 2017 at 9:08 PM, Mike Kluev via swift-evolution <
swift-evolution@swift.org> wrote:

> On 24 November 2017 at 23:47, Douglas Gregor  wrote:
>
>>
>> e.g., making all tuples of Equatable elements Equatable
>>
>>
> that's already the case.. (all tuples of equatable elements are
> equatable). no?
>

No, tuples do not conform to any protocols. There are hardcoded
implementations of `==` up to some arity in the stdlib to partially
mitigate the lack of protocol conformance.
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


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

2017-11-24 Thread Xiaodi Wu via swift-evolution
On Fri, Nov 24, 2017 at 2:55 PM, Alejandro Alonso <aalonso...@outlook.com>
wrote:

> Regarding naming too many things “random”, I’ve talked to many developers
> on my end and they all don’t find it confusing. This proposal is aimed to
> make it obvious what the operation is doing when regarding random. I still
> agree that the proposed solution does just that and in practice feels good
> to write.
>

I must disagree quite strongly here. The various facilities you name
"random" have different semantics, and differences in semantics should be
reflected in differences in names. It doesn't matter that some people don't
find it confusing; it is objectively the case that you have named multiple
distinct facilities with the same name, which leads to confusion. I, for
one, get confused, and you can see on this list that people are using
arguments about one property named "random" to discuss another property
named "random". This is quite an intolerable situation.

I disagree that sample is the correct naming to use here. Getting a sample
> is a verb in this context which would make it break API guidelines just as
> well as `pick()`. To sample is to “take a sample or samples of (something)
> for analysis.” I can agree to use `sampling()` which follows API
> guidelines. This would result in the following grammar for `[“hi”, “hello”,
> “hey”].sampling(2)`, “From array, get a sampling of 2"
>

"Sampling" is fine.


On Nov 23, 2017, 12:54 AM -0600, Xiaodi Wu , wrote:
>
> On Wed, Nov 22, 2017 at 23:01 Alejandro Alonso <aalonso...@outlook.com>
> wrote:
>
>> Like I’ve said, python has different syntax grammar. We have to read each
>> call site and form a sentence from it. `random.choice([1, 2, 3])` to me
>> this reads, “Get a random choice from array”. This makes sense. Slapping
>> the word choice as an instance property like `[1, 2, 3].choice` reads,
>> “From array, get choice”. What is choice? This doesn’t make sense at all to
>> me. To me, the only good solution is `[1, 2, 3].random` which reads, “From
>> array, get random”. I actually think most users will be able to understand
>> this at first glance rather than choice (or any or some).
>>
>
> Again, my concern here is that you are proposing to name multiple things
> "random". If this property should be called "random"--which I'm fine
> with--then the static method "random(in:)" should be named something else,
> and the static property "random" should be dropped altogether (as I
> advocate for reasons we just discussed) or renamed as well. It is simply
> too confusing that there are so many different "random" methods or
> properties. Meanwhile, isn't your default RNG also going to be called
> something like "DefaultRandom"?
>
> In regards to the sample() function on collections, I have added this as I
>> do believe this is something users need. The name I gave it was pick() as
>> this reads, “From array, pick 2”.
>>
>
> The name "sample" has been used to good effect in other languages, has a
> well understood meaning in statistics, and is consistent with Swift
> language guidelines. The operation here is a sampling, and per Swift
> guidelines the name must be a noun: therefore, 'sample' is fitting. "Pick"
> does not intrinsically suggest randomness, whereas sample does, and your
> proposed reading uses it as a verb, whereas Swift guidelines tell us it
> must be a noun. I would advocate strongly for using well-established
> terminology and sticking with "sample."
>
>
> On Nov 17, 2017, 8:32 PM -0600, Xiaodi Wu via swift-evolution <
>> swift-evolution@swift.org>, wrote:
>>
>> On Fri, Nov 17, 2017 at 7:11 PM, Brent Royal-Gordon <
>> br...@architechies.com> wrote:
>>
>>> On Nov 17, 2017, at 3:09 PM, Xiaodi Wu via swift-evolution <
>>> swift-evolution@swift.org> wrote:
>>>
>>> But actually, Int.random followed by % is the much bigger issue and a
>>> very good cautionary tale for why T.random is not a good idea. Swift should
>>> help users do the correct thing, and getting a random value across the full
>>> domain and computing an integer modulus is never the correct thing to do
>>> because of modulo bias, yet it's a very common error to make. We are much
>>> better off eliminating this API and encouraging use of the correct API,
>>> thereby reducing the likelihood of users making this category of error.
>>>
>>>
>>> Amen.
>>>
>>> If (and I agree with this) the range-based notation is less intuitive
>>> (0..<10.random is certainly less discoverable

Re: [swift-evolution] [Pitch] Raw mode string literals

2017-11-24 Thread Xiaodi Wu via swift-evolution
On Thu, Nov 23, 2017 at 5:33 PM, Chris Lattner <clatt...@nondot.org> wrote:

> On Nov 23, 2017, at 10:35 AM, Xiaodi Wu via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> This proposed addition addresses a known pain point, to be sure, but I
> think it has many implications for the future direction of the language and
> I'd like to explore them here.
>
>
> Thanks for writing this up Xiaodi,
>
> We should certainly move any discussion about regex literals into its own
> thread, but to make it clear that I'm not simply suggesting that we
> implement something in Swift 10 instead of addressing a known pain point
> now, here's a sketch of how Swift 5 could make meaningful progress:
>
> - Teach the lexer about basic /pattern/flag syntax.
> - Add an `ExpressibleByRegularExpressionLiteral`, where the initializer
> would be something like `init(regularExpressionLiteralPattern: String,
> flags: RegularExpressionFlags)` where RegularExpressionFlags would be an
> OptionSet type.
> - Add conformance to `ExpressibleByRegularExpressionLiteral` to
> `NSRegularExpression`.
> - Have no default `RegularExpressionLiteralType` for now so that, in the
> future, we can discuss and design a Swift standard library regular
> expression type, which is justifiable because we've baked in language
> support for the literal. This can be postponed.
>
>
> This approach could make sense, but it makes a couple of assumptions that
> I’m not certain are the right way to go (to be clear, I’m not certain that
> they’re wrong either!).
>
> Things I’d like to carefully consider:
>
> 1) We could make the compiler parse and validate regex literals at compile
> time:
>
> a) this allows the compiler to emit diagnostics (with fixits!) on
> malformed literals.
>
> b) When the compiler knows the grammar of the regex, it can precompile the
> regex into a DFA table or static executable code, rather than runtime
> compiling into a bytecode.
>
> c) however, the compiler can’t parse the literal unless it knows the
> dialect it corresponds to.  While we could parameterize this somehow (e.g.
> as a requirement in ExpressibleByRegularExpressionLiteral), if we weren’t
> bound by backwards compatibility, we would just keep things simple and say
> “there is one and only one grammar”.  I’d argue that having exactly one
> grammar supported by the // syntax is also *better* for users, rather than
> saying “it depends on what library you’re passing the regex into”.
>

I think we've circled back to a topic that we've discussed here before. I
do agree that having more of this validation at compile time would improve
the experience. However, I can see a few drawbacks to the _compiler_ doing
the validation:

- In the absence of a `constexpr`-like facility, supporting runtime
expressions would mean we'd be writing the same code twice, once in C++ for
compile-time validation of literal expressions and another time in Swift
for runtime expressions.

- As seen in these discussions about string literals where users want to
copy and paste text and have it "just work," supporting only one dialect in
regex literals will inevitably lead users to ask for other types of regex
literals for each individual flavor of regex they encounter.

Just like ExpressibleByDictionaryLiteral doesn't deduplicate keys, leaving
that to Dictionary, I think regex literals are better off not validating
literal expressions (or, maybe, doing only the barest sanity check),
leaving the rest to concrete regex types. As you point out with validation
of integer overflows during constant folding, we could get enough
compile-time validation even without teaching the compiler itself how to
validate the literal.

2) I’d like to explore the idea of making // syntax be *patterns* instead
> of simply literals.  As a pattern, it should be possible to bind submatches
> directly into variable declarations, eliminating the need to count parens
> in matches or other gross things.  Here is strawman syntax with a dumb
> example:
>
> if case /([a-zA-Z]+: let firstName) ([a-zA-Z]+: let lastName)/ =
> getSomeString() {
>print(firstName, lastName)
> }
>
>
This is an interesting idea. But is it significantly more usable than the
same type having a collection of named matches using the usual Perl syntax?

  if case /(?[a-zA-Z]+) (?[a-zA-Z]+)/ =
getSomeString() {
print(Regex.captured["firstName"], Regex.captured["lastName"])
  }

3) I see regex string matching as the dual to string interpolation.  We
> already provide the ability for types to specify a default way to print
> themselves, and it would be great to have default regex’s associated with
> many types, so you can just say “match an Int here” instead of having to
> match [0-9]+ and then do a failable

Re: [swift-evolution] Synthesizing Equatable, Hashable, and Comparable for tuple types

2017-11-24 Thread Xiaodi Wu via swift-evolution
On Thu, Nov 23, 2017 at 6:27 PM, Kelvin Ma  wrote:

>
>
> On Thu, Nov 23, 2017 at 7:08 PM, Xiaodi Wu  wrote:
>
>>
>> On Thu, Nov 23, 2017 at 16:45 Kelvin Ma via swift-evolution <
>> swift-evolution@swift.org> wrote:
>>
>>>
>>>
>>> On Thu, Nov 23, 2017 at 12:32 PM, Tino Heth <2...@gmx.de> wrote:
>>>

 a good idea on paper, a disastrous one in practice. What happens if
 every geometry library declares their own Point type?

 That would be ugly („disastrous“ imho is a little bit to strong — C++
 had/has similar issues, and other languages as well)
 But if there would be a simple Point struct in a library that is
 popular (could be achieved by shipping it alongside the stdlib), this
 problem would be solved (there has been a pitch lately, but I guess it
 faded away silently).

>>>
>>> it’s ugly in C++ and disastrous in Swift because C++ has fixed layout
>>> guarantees and everyone agrees that z comes after y comes after x, so you
>>> can unsafe-bitcast the foreign C++ points into your own points “for free”.
>>> you can’t do the same thing in Swift
>>>
>>
>> Why do you need to have this ability to unsafe bitcast? Is
>> interconversion between point types such a common operation that it's a
>> performance bottleneck?
>>
>
> idk if it’s a performance bottleneck because i use tuples in my geometry
> stack and i keep the bottom 2 levels in the same module but it cannot be
> good. a lot of the geometry code I write sits atop 2 or 3 other layers of
> geometry code beneath it, and it interops with geometry APIs in other
> libraries. for example it might be organized like
>
> [ Client geometry code ] ←→ [ Library geometry code ] (example:
> Voronoi.voronoi(_:), Noise.perlin(_:_:))
>[ Procedurally generated geometry ] (example:
> makeSphere(resolution:))
>[Matrices and projections ] (example:
> Geometry.clockwise(_:_:center:normal:))
>[   Math  ] (example: Math.cross(_:_:))
>
> converting at every boundary seems like something to avoid. not to mention
> the sheer amount of boilerplate all those conversions produce.
>

FWIW, tuples are only guaranteed to have a C-compatible layout when exposed
to C; that is, Swift doesn't guarantee that there will not be optimizations
in the future that change tuple layout such that a call into C will cause
your tuples to do interop gymnastics.
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Synthesizing Equatable, Hashable, and Comparable for tuple types

2017-11-23 Thread Xiaodi Wu via swift-evolution
On Thu, Nov 23, 2017 at 16:45 Kelvin Ma via swift-evolution <
swift-evolution@swift.org> wrote:

>
>
> On Thu, Nov 23, 2017 at 12:32 PM, Tino Heth <2...@gmx.de> wrote:
>
>>
>> a good idea on paper, a disastrous one in practice. What happens if every
>> geometry library declares their own Point type?
>>
>> That would be ugly („disastrous“ imho is a little bit to strong — C++
>> had/has similar issues, and other languages as well)
>> But if there would be a simple Point struct in a library that is popular
>> (could be achieved by shipping it alongside the stdlib), this problem would
>> be solved (there has been a pitch lately, but I guess it faded away
>> silently).
>>
>
> it’s ugly in C++ and disastrous in Swift because C++ has fixed layout
> guarantees and everyone agrees that z comes after y comes after x, so you
> can unsafe-bitcast the foreign C++ points into your own points “for free”.
> you can’t do the same thing in Swift
>

Why do you need to have this ability to unsafe bitcast? Is interconversion
between point types such a common operation that it's a performance
bottleneck?
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Pitch] Raw mode string literals

2017-11-23 Thread Xiaodi Wu via swift-evolution
On Thu, Nov 23, 2017 at 2:47 PM, Tony Allevato <tony.allev...@gmail.com>
wrote:

>
>
> On Thu, Nov 23, 2017 at 12:21 PM Xiaodi Wu via swift-evolution <
> swift-evolution@swift.org> wrote:
>
>> On Thu, Nov 23, 2017 at 2:14 PM, John Holdsworth via swift-evolution <
>> swift-evolution@swift.org> wrote:
>>
>>> I’m beginning to wish I hadn’t tied this proposal so strongly to regular
>>> expressions!
>>> It is indeed the wrong motivation. Even as a ten year veteran of Perl
>>> development
>>> I’m not sure we want to bake it into the language quite so tightly
>>> (isn’t a part of
>>> Foundation?) What would /regex/ represent - an instance of
>>> NSRegularExpression?
>>> Would the flags be pattern options or matching options? This is a whole
>>> other debate.
>>>
>>> For me the focus of raw strings was a sort of super-literal literal
>>> which has many
>>> applications. The r”literal” syntax has a precedent in Python and there
>>> seemed
>>> to be a syntactic gap that could be occupied but perhaps there are other
>>> alternatives
>>> we could discuss. It would be a shame to see ‘quoted strings’ be used
>>> for this however.
>>> I still live in hope one day it will be used for single character
>>> UNICODE values.
>>>
>>> Since what passes for a single character changes by Unicode
>> revision--such as whenever they get around to enumerating the permitted
>> modifying attributes of the poop emoji--it is quite impossible (and Swift's
>> `Character` doesn't attempt to) to enforce single-characterness at compile
>> time. We should put any such notions to rest up front.
>>
>
> Unless I'm misunderstanding you here, I don't think that's true: writing
> something like `let c: Character = "ab"` is definitely a compile-time
> error: https://gist.github.com/allevato/ae267e27939d6233d66a87b48fc0
>

Hmm, yes, it still attempts to make a best effort, it seems. I had thought
that this compile-time check was removed altogether, as it cannot be done
in the general case.


> To the original point though, I don't think Swift needs to use single
> quotes for single characters (or single scalars). Type inference already
> infers Characters from single-character String literals in contexts where a
> Character is expected, and the only time you need to be explicit is if
> you're trying to resolve an overload or initialize a variable by itself.
> Using single quotes to avoid writing "as Character" would feel like a waste.
>
>> Agree.

> On 23 Nov 2017, at 19:10, Brent Royal-Gordon <br...@architechies.com>
>>> wrote:
>>>
>>> On Nov 23, 2017, at 11:15 AM, Chris Lattner via swift-evolution <
>>> swift-evolution@swift.org> wrote:
>>>
>>> Until we figure out that path forward for regex’s, I think they aren’t
>>> the right motivation for this proposal.
>>>
>>>
>>> 1. Even in our shining pattern matching future—a future which I, for
>>> one, am eager to hasten—we will still need to interoperate with
>>> NSRegularExpression and other Perl 5-compatible regex engines.
>>>
>>> 2. Code generation.
>>>
>>> 3. Windows-style paths.
>>>
>>> 4. Doesn’t LaTeX use backslashes?
>>>
>>> 5. Etc.
>>>
>>> I think the Motivation section undersells this proposal. Regexes are a
>>> strong short-run use case, but in the long run, we’ll need this for other
>>> things. In both cases, though, raw literals will be a useful addition to
>>> the language, improving the clarity of Swift code much like multiline
>>> literals already have.
>>>
>>> --
>>> Brent Royal-Gordon
>>> Sent from my iPhone
>>>
>>>
>>>
>>> ___
>>> 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] [Pitch] Raw mode string literals

2017-11-23 Thread Xiaodi Wu via swift-evolution
On Thu, Nov 23, 2017 at 2:14 PM, John Holdsworth via swift-evolution <
swift-evolution@swift.org> wrote:

> I’m beginning to wish I hadn’t tied this proposal so strongly to regular
> expressions!
> It is indeed the wrong motivation. Even as a ten year veteran of Perl
> development
> I’m not sure we want to bake it into the language quite so tightly (isn’t
> a part of
> Foundation?) What would /regex/ represent - an instance of
> NSRegularExpression?
> Would the flags be pattern options or matching options? This is a whole
> other debate.
>
> For me the focus of raw strings was a sort of super-literal literal which
> has many
> applications. The r”literal” syntax has a precedent in Python and there
> seemed
> to be a syntactic gap that could be occupied but perhaps there are other
> alternatives
> we could discuss. It would be a shame to see ‘quoted strings’ be used for
> this however.
> I still live in hope one day it will be used for single character UNICODE
> values.
>
> Since what passes for a single character changes by Unicode revision--such
as whenever they get around to enumerating the permitted modifying
attributes of the poop emoji--it is quite impossible (and Swift's
`Character` doesn't attempt to) to enforce single-characterness at compile
time. We should put any such notions to rest up front.

> On 23 Nov 2017, at 19:10, Brent Royal-Gordon 
> wrote:
>
> On Nov 23, 2017, at 11:15 AM, Chris Lattner via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> Until we figure out that path forward for regex’s, I think they aren’t the
> right motivation for this proposal.
>
>
> 1. Even in our shining pattern matching future—a future which I, for one,
> am eager to hasten—we will still need to interoperate with
> NSRegularExpression and other Perl 5-compatible regex engines.
>
> 2. Code generation.
>
> 3. Windows-style paths.
>
> 4. Doesn’t LaTeX use backslashes?
>
> 5. Etc.
>
> I think the Motivation section undersells this proposal. Regexes are a
> strong short-run use case, but in the long run, we’ll need this for other
> things. In both cases, though, raw literals will be a useful addition to
> the language, improving the clarity of Swift code much like multiline
> literals already have.
>
> --
> Brent Royal-Gordon
> Sent from my iPhone
>
>
>
> ___
> 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] [Pitch] Raw mode string literals

2017-11-23 Thread Xiaodi Wu via swift-evolution
On Thu, Nov 23, 2017 at 1:12 PM, Brent Royal-Gordon via swift-evolution <
swift-evolution@swift.org> wrote:

> On Nov 23, 2017, at 11:15 AM, Chris Lattner via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> Until we figure out that path forward for regex’s, I think they aren’t the
> right motivation for this proposal.
>
>
> 1. Even in our shining pattern matching future—a future which I, for one,
> am eager to hasten—we will still need to interoperate with
> NSRegularExpression and other Perl 5-compatible regex engines.
>

Can you explain why such interoperability would need _raw string literals_
as opposed to regex literals?


> 2. Code generation.
>

Can you elaborate on this?


> 3. Windows-style paths.
>

Sure, Windows-style paths use the backslash. But it's not a useful exercise
to enumerate all places where backslashes are used, but rather where
they're often used in _literals_. How often are you hardcoding
Windows-style paths? Wouldn't an ergonomic API accept the forward slash
also? Even many Microsoft-vended Windows utilities do so.


> 4. Doesn’t LaTeX use backslashes?
>

Again, not often you're hardcoding LaTeX literals. Let's not turn this into
an exercise in listing all places where you've seen a backslash used.


> 5. Etc.
>
> I think the Motivation section undersells this proposal. Regexes are a
> strong short-run use case, but in the long run, we’ll need this for other
> things. In both cases, though, raw literals will be a useful addition to
> the language, improving the clarity of Swift code much like multiline
> literals already have.
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Pitch] Raw mode string literals

2017-11-23 Thread Xiaodi Wu via swift-evolution
This proposed addition addresses a known pain point, to be sure, but I
think it has many implications for the future direction of the language and
I'd like to explore them here.

The tl;dr version is that I'm not sure this is the right direction in which
to head to address the issue of regex ergonomics, and that the issue also
implicates other weaknesses in terms of literals for which I think the
solution exacerbates rather than solves the underlying problem. [Chris's
email just came through and cut to the meat of it, but I'll keep writing
this email and complete my thoughts.]

We've been talking on this list for quite some time about supporting `/this
syntax/` for a regex literal. Whether this can be accomplished or not
within the Swift 5 timeframe (and I think a reasonable barebones
implementation could be), the question here is whether your proposed
addition serves any useful purpose in a future version of Swift in which we
do have such a literal. After all, your motivation (and a very valid one)
is that regex literals are too difficult to type. I very strongly believe
that the solution here is what we've been talking about all along: actual
regex literals.

We should certainly move any discussion about regex literals into its own
thread, but to make it clear that I'm not simply suggesting that we
implement something in Swift 10 instead of addressing a known pain point
now, here's a sketch of how Swift 5 could make meaningful progress:

- Teach the lexer about basic /pattern/flag syntax.
- Add an `ExpressibleByRegularExpressionLiteral`, where the initializer
would be something like `init(regularExpressionLiteralPattern: String,
flags: RegularExpressionFlags)` where RegularExpressionFlags would be an
OptionSet type.
- Add conformance to `ExpressibleByRegularExpressionLiteral` to
`NSRegularExpression`.
- Have no default `RegularExpressionLiteralType` for now so that, in the
future, we can discuss and design a Swift standard library regular
expression type, which is justifiable because we've baked in language
support for the literal. This can be postponed.

Now, suppose we can motivate "raw" strings with some other use case. The
proposed syntax remains problematic and I'd like to discuss that for a
little bit.

I believe it was Chris who originally explained some time ago that it was a
deliberate design decision not to have little dangling bits on literals
such as "1.0f", opting instead for more readable spellings such as "1.0 as
Float". This `r` prefix is clearly undoing that deliberate design decision
and inconsistent with the direction of Swift. There are other options here,
should a use case arise that successfully motivate "raw" strings. For
example, one might be to use the long-reserved single-quoted 'string
literal' for this purpose, if this is judged to be a significant enough
feature that can justify it.

But there's another matter here that I'd like to touch on. Namely, for all
literal types, the `ExpressiblyBy*` protocols expose a processed version of
the literal. This leads to various issues that require hacky workarounds at
best. For instance, BigInt types can't initialize arbitrarily large values
with integer literals, because the literal has to be representable as a
built-in fixed-width integer; Decimal initializes its floating-point
literal values through a Double intermediary, which can lead to undesirable
results; and so on. What these issues have in common with your use case
here is the inability of `ExpressibleBy*` types to receive the underlying
"raw" literal as it is input. If we could come up with a holistic solution
here, we might be able to dispense with having any distinct syntax for
"raw" strings *and* solve all of these issues at once.


On Thu, Nov 23, 2017 at 11:43 AM, John Holdsworth via swift-evolution <
swift-evolution@swift.org> wrote:

> Hello S/E,
>
> I’d like to put forward a perhaps rather banal change to the Swift lexer
> primarily intended to make entering regular expression patterns easier.
>
> https://github.com/DoubleSpeak/swift-evolution/blob/master/proposals/-
> raw-string-escaping.md
>
> With a raw literal a string prefixed by “r” the \ character would have no
> special role at all and be processed like any other character i.e.
>
> r"\n\(var)\n" == "\\n\\(var)\\n"
>
> r"\?\y\=" == "\\?\\y\\="
>
> r"c:\windows\system32" == "c:\\windows\\system32"
>
> r"""
> Line One\
> Line Two\
> """ == "Line One\\\nLineTwo\\"
>
> I had considered another version of the proposal where known escapes
> were still processed but it proved too difficult to reason exactly what was
> contained in the string.
>
> There is a example toolchain available for testing:
>
> http://johnholdsworth.com/swift-LOCAL-2017-11-23-a-osx.tar.gz
>
> Can we shepard this minor additive change into Swift 4.1?
>
> John
>
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> 

  1   2   3   4   5   6   7   8   9   10   >