[swift-evolution] Support for newtype feature/typesafe calculations

James Campbell james at supmenow.com
Thu Jan 7 09:02:49 CST 2016


If it helps I would be happy to start a library for this, which could be
later added to the standard library :)

On Thu, Jan 7, 2016 at 3:01 PM, James Campbell <james at supmenow.com> wrote:

> Interesting could you upload :) would be good to consolidate all the
> approaches we have right now so we can come up with the best one:
>
> So far we have:
>
> - Box/Unit Type Protocol (My Solution)
> - Math Group Protocol (Tino Heth)
> - Computed typealias (John Randolph)
>
> On Thu, Jan 7, 2016 at 2:55 PM, John Randolph via swift-evolution <
> swift-evolution at swift.org> wrote:
>
>>
>>
>> On Jan 7, 2016, at 4:06 AM, James Campbell via swift-evolution <
>> swift-evolution at swift.org> wrote:
>>
>> So this is how this feature could be achieved right now with minimal
>> changes to the language.
>>
>> - We expose some kind of protocol that allows you to Box up types, we
>> could call this `Box` or something else like `Unit`. (I have a working
>> implementation in the current language with a bit of boilerplate). This
>> protocol handles the default implementation of converting from literals and
>> to floats etc.
>> - For each type-safe unit for a calculation - you define a protocol
>> extending this `Box` type which defines the associated type of the value
>> that unit holds. For example for Degree and Radian I declared a `AngleType`
>> which set the associated type to be a double.
>> - For each unit type, you declare a struct that inherits from that
>> protocol you defined. So I have two structs `Degree` and `Radian` which
>> implement the `AngleType` protocol.
>> - You implement the functions for figuring out if your units are equal
>> and all other operators they may need i.e `Degree(360) - 30`.
>>
>>
>> I took a different approach to this, which was to just typealias Angle to
>> Double,  keep all Angle values as radians (since the stdlib trig functions
>> take radians), and add some computed setters and getters to let me access
>> an Angle in radians, degrees, or grads.
>>
>> I would like to see Angle, along with several other basic geometric
>> concepts, promoted to the Swift standard library.
>>
>> -jcr
>>
>>
>> _______________________________________________
>> swift-evolution mailing list
>> swift-evolution at swift.org
>> https://lists.swift.org/mailman/listinfo/swift-evolution
>>
>>
>
>
> --
>  Wizard
> james at supmenow.com
> +44 7523 279 698
>



-- 
 Wizard
james at supmenow.com
+44 7523 279 698
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160107/cf71a93b/attachment-0001.html>


More information about the swift-evolution mailing list