[swift-evolution] [Proposal draft] Enhanced floating-point protocols

Greg Parker gparker at apple.com
Tue Apr 19 01:08:47 CDT 2016


> On Apr 14, 2016, at 4:55 PM, Stephen Canon via swift-evolution <swift-evolution at swift.org> wrote:
> 
>   /// `true` iff the signbit of `self` is set.  Implements the IEEE 754
>   /// `signbit` operation.
>   ///
>   /// Note that this is not the same as `self < 0`.  In particular, this
>   /// property is true for `-0` and some NaNs, both of which compare not
>   /// less than zero.
>   //  TODO: strictly speaking a bit and a bool are slightly different
>   //  concepts.  Is another name more appropriate for this property?
>   //  `isNegative` is incorrect because of -0 and NaN.  `isSignMinus` might
>   //  be acceptable, but isn't great.  `signBit` is the IEEE 754 name.
>   var signBit: Bool { get }
> 
>   init(signBit: Bool, exponent: Int, significand: Self)
These do feel a bit awkward. Perhaps something over-engineered to handle the typical cases more readably?

  public protocol FloatingPoint: SignedArithmetic, Comparable {
    enum Sign { 
      case Plus
      case Minus
      init(bit: Bool) { return bit ? .Minus : .Plus }
      var bit: Bool { get { return self == Minus } }
    }
  
    var sign: Sign { get }
    var signBit: Bool { get }
  
    init(sign: Sign, exponent: Int, significand: Self)
    init(signBit: Bool, exponent: Int, significand: Self)
  
    …
  }

…and perhaps each sign/signBit pair would provides one as a default implementation that calls the other.

Then we can often write something more readable than signBit: 

  let x = Float(sign: .Plus, exponent: 2, signficand: 2)
  if x.sign == .Plus { … }

Alternatively or additionally, perhaps signBit ought to be an Int because the people writing code using signBit would probably prefer to use literal 1 and 0 instead of true and false. (Hasn't the distinction between Bit and Bool come up before?)


-- 
Greg Parker     gparker at apple.com     Runtime Wrangler


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160418/88a325d8/attachment.html>


More information about the swift-evolution mailing list