[swift-evolution] Epic: Typesafe calculations
Thorsten Seitz
tseitz42 at icloud.com
Wed Jan 20 14:12:55 CST 2016
> Am 20.01.2016 um 18:16 schrieb Dave Abrahams via swift-evolution <swift-evolution at swift.org>:
>
>
> on Wed Jan 13 2016, Thorsten Seitz via swift-evolution <swift-evolution-m3FHrko0VLzYtjvyW6yDsg-AT-public.gmane.org> wrote:
>
>>> Am 13.01.2016 um 00:06 schrieb Dave Abrahams
>>> <dabrahams at apple.com>:
>>>
>>>> On Jan 7, 2016, at 10:46 AM, Thorsten Seitz
>>>> <tseitz42 at icloud.com> wrote:
>>
>>>>
>>>> Really great to hear that you are planning for Swift to be able to
>>>> do these kinds of things!
>>>>
>>>> I tried to see how far I could get (working from memory of a
>>>> Haskell library; Boost.Units seems quite similar at first glance),
>>>> but failed of course because of the missing parameterized recursive
>>>> typealiases:
>>>
>>> Sadly, the lack of the ability to define a pretty shorthand for
>>> quantities is not what stands in the way, fundamentally.
>>
>> I'm afraid I don't get your meaning here. Would you mind to explain a bit more?
>> Thanks!
>
> Typealiases are just about creating new names for existing types. The
> inability to even form the correct type when an an acceleration is
> multiplied by a time is the more fundamental issue. You need to add
> corresponding powers of the fundamental dimensions.
Ah, thanks for explaining what you meant!
Actually that’s what the generic recursive typealiases Add and Sub I defined in my example are for: they effectively provide addition and subtraction for Peano numbers implemented in the type system (that’s the way it works in Haskell).
typealias Add<Zero, P: Peano> = P
typealias Add<P: Peano, Zero> = P
typealias Add<Succ<P1>, Succ<P2>> = Add<Succ<Succ<P1>>,P2>
typealias Add<Succ<P1>, Pred<P2>> = Add<P1,P2>
typealias Add<Pred<P1>, Succ<P2>> = Add<P1,P2>
typealias Add<Pred<P1>, Pred<P2>> = Add<P1,Pred<Pred<P2>>>
public func *
<L1,T1,M1,L2,T2,M2,L,T,M where
L == Add<L1,L2>, T == Add<T1,T2>, M == Add<M1,M2>>
(lhs: Quantity<L1,T1,M1>, rhs: Quantity<L2,T2,M2>) -> Quantity<L,T,M>
{
return Quantity<L,T,M>(lhs.value * rhs.value)
}
Having integers as generic parameters with the possibility of adding them is much nicer, though, as the Peano numbers are no longer needed and everything is much easier to understand. The adaption of my example to that feature was in my other mail, e.g.
public func *
<L1,T1,M1,L2,T2,M2,L,T,M where L == L1+L2, T == T1+T2, M == M1+M2>
(lhs: Quantity<L1,T1,M1>, rhs: Quantity<L2,T2,M2>) -> Quantity<L,T,M>
{
return Quantity<L,T,M>(lhs.value * rhs.value)
}
-Thorsten
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160120/518a8ceb/attachment.html>
More information about the swift-evolution
mailing list