3 ms·
In some languages, you could define a new division operator that returns an Optional/Option/Maybe result, and then use a nil-coalescing operator to choose what
by mayoff 8y ago
In some languages, you could define a new division operator that returns an Optional/Option/Maybe result, and then use a nil-coalescing operator to choose what you want in case of division-by-zero. In Swift:
infix operator /? : MultiplicationPrecedence
extension FloatingPoint {
static func /? (lhs: Self, rhs: Self) -> Self? {
return rhs == 0 ? nil : lhs / rhs
}
}
extension BinaryInteger {
static func /? (lhs: Self, rhs: Self) -> Self? {
return rhs == 0 ? nil : lhs / rhs
}
}
10 /? 2 ?? 0 // -> 5
10 /? 0 ?? 0 // -> 0
10 /? 0 ?? 10 // -> 10
- spooneybarger 8y agoYou can't define your own in Pony but, /?, *?, +? and -? are coming to Pony. We call them "safe math operators" and will error on integer overflow, underflow, and division by zero.