Sources/OrgCore/Compute/CalcSymbolic.swift

fb3b538d8bb007da66099e27e5c2e4310e51dd08
orgstar/Sources/OrgCore/Compute/CalcSymbolic.swift

664 lines · 32145 bytes

  1import Foundation
  2
  3/// Calc's arithmetic on formulas it can't reduce to a number: variables, `inf`, `uinf`, and
  4/// quotients by zero. This ports `math-add`, `math-mul`, `math-div`, `math-pow` and `math-neg`
  5/// with their `-symb-fancy` helpers from calc.el and calc-arith.el, as `calc-eval` runs them
  6/// with `calc-simplify-mode` nil, and Calc's flat formula printer from calccomp.el. Anything
  7/// those functions would decide from declarations, units, matrices or intervals throws
  8/// `Calc.Unsupported`.
  9extension Calc {
 10    /// A formula, as Calc's Lisp form: a number, a variable, or an operator or function with
 11    /// its arguments (`+ - * / ^ neg`, or a function name).
 12    public indirect enum Term: Equatable, Sendable {
 13        case number(Value)
 14        case variable(String)
 15        case op(String, [Term])
 16    }
 17
 18    /// `math-reject-arg`: the operation stays unevaluated.
 19    struct Rejected: Error {}
 20
 21    /// `calc-symbolic-mode`.
 22    @TaskLocal static var symbolicMode = false
 23
 24    /// `calc-prefer-frac`, for the division the arithmetic does.
 25    @TaskLocal static var fractions = false
 26
 27    /// Variables Calc gives a value or a declaration, which would change the arithmetic.
 28    static let reserved: Set<String> = ["CommuteRules", "Decls", "DistribRules", "EvalRules", "FactorRules", "FitRules",
 29                                        "Holidays", "IntegAfterRules", "InvertRules", "JumpRules", "MergeRules", "Modes",
 30                                        "NegateRules"]
 31
 32    /// The special constants and infinities, whose sign or type Calc knows.
 33    static let constants: Set<String> = ["pi", "e", "phi", "gamma", "i", "inf", "uinf", "nan"]
 34
 35    static func term(_ v: Value) throws -> Term {
 36        switch v {
 37        case .symbolic(let t): return t
 38        case .nan: return .variable("nan")
 39        case .int, .float, .frac: return .number(v)
 40        case .vector, .date: throw Unsupported("symbolic arithmetic")
 41        }
 42    }
 43
 44    static func value(_ t: Term) -> Value {
 45        switch t {
 46        case .number(let v): return v
 47        case .variable("nan"): return .nan
 48        default: return .symbolic(t)
 49        }
 50    }
 51
 52    enum Symbolic {
 53        static let inf = Term.variable("inf")
 54        static let uinf = Term.variable("uinf")
 55        static let nan = Term.variable("nan")
 56
 57        // MARK: Predicates
 58
 59        static func number(_ t: Term) -> Value? {
 60            if case .number(let v) = t { return v }
 61            return nil
 62        }
 63
 64        static func head(_ t: Term) -> String? {
 65            if case .op(let f, _) = t { return f }
 66            return nil
 67        }
 68
 69        /// `(nth n a)`, from 1.
 70        static func arg(_ t: Term, _ n: Int) -> Term {
 71            guard case .op(_, let args) = t, n - 1 < args.count else { return .number(.int(0)) }
 72            return args[n - 1]
 73        }
 74
 75        static func objectp(_ t: Term) -> Bool { number(t) != nil }
 76        static func zerop(_ t: Term) -> Bool { number(t).map(isZero) ?? false }
 77        static func floatp(_ t: Term) -> Bool {
 78            if case .number(.float) = t { return true }
 79            return false
 80        }
 81        static func ratp(_ t: Term) -> Bool { number(t).map { rational($0) != nil } ?? false }
 82        static func integerp(_ t: Term) -> Bool {
 83            if case .number(.int) = t { return true }
 84            return false
 85        }
 86
 87        /// `math-negp`.
 88        static func negp(_ t: Term) -> Bool {
 89            if let v = number(t) { return (try? sign(v)) == -1 }
 90            return t == .op("neg", [inf])
 91        }
 92
 93        /// `math-posp`.
 94        static func posp(_ t: Term) -> Bool {
 95            if let v = number(t) { return (try? sign(v)) == 1 }
 96            return t == inf
 97        }
 98
 99        /// `Math-equal-int`.
100        static func equalInt(_ t: Term, _ n: Int) -> Bool {
101            t == .number(.int(n)) || t == .number(.float(n, 0))
102        }
103
104        /// `math-looks-negp`; `loose` false is the `Math-looks-negp` macro, which doesn't
105        /// look inside a difference.
106        static func looksNeg(_ t: Term, loose: Bool = true) -> Bool {
107            if negp(t) { return true }
108            switch head(t) {
109            case "neg": return true
110            case "*", "/": return looksNeg(arg(t, 1)) || looksNeg(arg(t, 2))
111            case "-": return loose && looksNeg(arg(t, 1))
112            default: return false
113            }
114        }
115
116        /// `math-infinitep`: the infinity a product, quotient or negation is made of.
117        static func infinitep(_ t: Term) -> Term? {
118            var a = t
119            while let f = head(a), ["*", "/", "neg"].contains(f) {
120                a = f != "*" || infinitep(arg(a, 1)) != nil ? arg(a, 1) : arg(a, 2)
121            }
122            return [inf, uinf, nan].contains(a) ? a : nil
123        }
124
125        static func containsConstant(_ t: Term) -> Bool {
126            switch t {
127            case .number: false
128            case .variable(let name): constants.contains(name)
129            case .op(_, let args): args.contains(where: containsConstant)
130            }
131        }
132
133        /// `math-possible-signs`: the bits 1 negative, 2 zero, 4 positive and 8 not real,
134        /// relative to `origin`. Nothing is declared, so a variable may be anything.
135        static func signs(_ a: Term, _ origin: Term? = nil) throws -> Int {
136            func negSigns(_ s: Int) -> Int {
137                s >= 8 ? 8 + negSigns(s - 8) : (s & 1 != 0 ? 4 : 0) | (s & 2) | (s & 4 != 0 ? 1 : 0)
138            }
139            if objectp(a) {
140                let x = try origin.map { try sub(a, $0) } ?? a
141                return posp(x) ? 4 : negp(x) ? 1 : 2
142            }
143            let (a1, a2) = (arg(a, 1), arg(a, 2))
144            let f = head(a)
145            if f == "+" || f == "-" {
146                if objectp(a1) {
147                    if f == "-" { return negSigns(try signs(a2, try origin.map { try add($0, a1) } ?? a1)) }
148                    return try signs(a2, try origin.map { try sub($0, a1) } ?? (try neg(a1)))
149                }
150                if objectp(a2) {
151                    let org = f == "-" ? a2 : try neg(a2)
152                    return try signs(a1, try origin.map { try add($0, org) } ?? org)
153                }
154                let s1 = try signs(a1, origin)
155                var s2 = try signs(a2)
156                if f == "-" { s2 = negSigns(s2) }
157                if s1 == s2 { return s1 }
158                if s1 == 2 { return s2 }
159                if s2 == 2 { return s1 }
160                if s1 >= 8 || s2 >= 8 { return 15 }
161                if (s1, s2) == (4, 6) || (s1, s2) == (6, 4) { return 4 }
162                if (s1, s2) == (1, 3) || (s1, s2) == (3, 1) { return 1 }
163                return 7
164            }
165            if f == "neg" { return negSigns(try signs(a1, try origin.map(neg))) }
166            let origin = origin.flatMap { zerop($0) ? nil : $0 }
167            let zero = Term.number(.int(0))
168            if f == "*" || (f == "/" && origin != nil), objectp(a1) {
169                let s = f == "*"
170                    ? (zerop(a1) ? try signs(zero, origin) : try signs(a2, try div(origin ?? zero, a1)))
171                    : negSigns(try signs(a2, try div(a1, origin!)))
172                return negp(a1) ? negSigns(s) : s
173            }
174            if f == "*" || f == "/", objectp(a2) {
175                let s = try signs(a1, f == "*" ? try mul(origin ?? zero, a2) : try div(origin ?? zero, a2))
176                return negp(a2) ? negSigns(s) : s
177            }
178            let sign: Int
179            switch a {
180            case .op("*", _), .op("/", _):
181                let (s1, s2) = (try signs(a1), try signs(a2))
182                if s1 >= 8 || s2 >= 8 || (f == "/" && [2, 3, 6, 7].contains(s2)) {
183                    sign = 15
184                } else {
185                    sign = (s1 & 4 != 0 ? s2 : 0) | (s1 & 2) | (s1 & 1 != 0 ? negSigns(s2) : 0)
186                }
187            case .op("^", _):
188                let (s1, s2) = (try signs(a1), try signs(a2))
189                if s1 >= 8 || s2 >= 8 {
190                    sign = 15
191                } else if s1 == 4 {
192                    sign = 4
193                } else if s1 == 2 {
194                    sign = s2 == 4 ? 2 : 15
195                } else if s2 == 2 {
196                    sign = [1, 5].contains(s1) ? 2 : 15
197                } else if case .number(.int(let n)) = a2 {
198                    sign = n % 2 == 0 ? ([3, 6, 7].contains(s1) ? 6 : 4) : s1
199                } else if s1 == 6 {
200                    sign = s2 == 4 ? 6 : 15
201                } else {
202                    sign = 7
203                }
204            case .variable(let name):
205                switch name {
206                case "pi", "e":
207                    guard origin == nil else { throw Unsupported("symbolic arithmetic") }
208                    return 4
209                case "inf": return 4
210                case "uinf": return 13
211                case "i": return 8
212                default: return 15
213                }
214            default: throw Unsupported("function \(f ?? "")")
215            }
216            guard let origin else { return sign }
217            if posp(origin) { return (sign & 8) + ([1, 2, 3, 8, 9, 10, 11].contains(sign) ? 1 : 7) }
218            return (sign & 8) + ([2, 4, 6, 8, 10, 12, 14].contains(sign) ? 4 : 7)
219        }
220
221        static func knownNonneg(_ t: Term) throws -> Bool { [2, 4, 6].contains(try signs(t)) }
222
223        /// `math-known-num-integerp` and `math-known-integerp`: only numbers are known to be
224        /// integers, as nothing is declared.
225        static func knownNumInteger(_ t: Term) throws -> Bool {
226            if let v = number(t) { return isWhole(v) }
227            guard !containsConstant(t) else { throw Unsupported("symbolic arithmetic") }
228            return false
229        }
230
231        // MARK: Arithmetic
232
233        /// `math-normalize`: the operations applied again from the leaves, floats rounded
234        /// to the precision.
235        static func normalize(_ t: Term) throws -> Term {
236            switch t {
237            case .number(.float(let m, let e)): return .number(try makeFloat(Int128(m), e))
238            case .number, .variable: return t
239            case .op(let f, let args):
240                let args = try args.map(normalize)
241                do { return try apply(f, args) } catch is Rejected { return .op(f, args) }
242            }
243        }
244
245        static func apply(_ f: String, _ args: [Term]) throws -> Term {
246            switch (f, args.count) {
247            case ("+", 2): return try add(args[0], args[1])
248            case ("-", 2): return try sub(args[0], args[1])
249            case ("*", 2): return try mul(args[0], args[1])
250            case ("/", 2): return try div(args[0], args[1])
251            case ("^", 2): return try pow(args[0], args[1])
252            case ("neg", 1): return try neg(args[0])
253            default: throw Unsupported("function \(f)")
254            }
255        }
256
257        static func numeric(_ a: Term, _ b: Term, _ op: (Value, Value) throws -> Value) throws -> Term? {
258            guard let x = number(a), let y = number(b) else { return nil }
259            return try term(try op(x, y))
260        }
261
262        /// `math-float` of a rational number.
263        static func float(_ t: Term) throws -> Term {
264            guard let v = number(t) else { return t }
265            return .number(try Calc.float(v))
266        }
267
268        /// `math-neg`.
269        static func neg(_ a: Term) throws -> Term {
270            if let v = number(a) { return .number(try negate(v)) }
271            func okayNeg(_ t: Term) -> Bool { looksNeg(t) || head(t) == "-" }
272            let (a1, a2) = (arg(a, 1), arg(a, 2))
273            switch head(a) {
274            case "+": return try sub(try neg(a1), a2)
275            case "-": return try sub(a2, a1)
276            case "*", "/":
277                let f = head(a)!
278                if okayNeg(a1) { return .op(f, [try neg(a1), a2]) }
279                if okayNeg(a2) { return .op(f, [a1, try neg(a2)]) }
280                if objectp(a1) || (head(a1) == "*" && objectp(arg(a1, 1))) { return .op(f, [try neg(a1), a2]) }
281                if f == "/", objectp(a2) || (head(a2) == "*" && objectp(arg(a2, 1))) { return .op(f, [a1, try neg(a2)]) }
282            case "neg": return a1
283            default: if a == uinf || a == nan { return a }
284            }
285            return .op("neg", [a])
286        }
287
288        /// `math-add`.
289        static func add(_ a: Term, _ b: Term) throws -> Term {
290            if let sum = try numeric(a, b, { try Calc.add($0, $1) }) { return sum }
291            if zerop(a) { return b }
292            if zerop(b) { return a }
293            return try addFancy(a, b)
294        }
295
296        /// `math-sub`.
297        static func sub(_ a: Term, _ b: Term) throws -> Term { try add(a, try neg(b)) }
298
299        /// `math-add-symb-fancy`.
300        static func addFancy(_ a: Term, _ b: Term) throws -> Term {
301            switch head(b) {
302            case "+": return try add(try add(a, arg(b, 1)), arg(b, 2))
303            case "-": return try sub(try add(a, arg(b, 1)), arg(b, 2))
304            case "neg" where head(arg(b, 1)) == "+":
305                return try sub(try sub(a, arg(arg(b, 1), 1)), arg(arg(b, 1), 2))
306            default: break
307            }
308            if let result = try combineSums(a, b) { return result }
309            if looksNeg(b, loose: false) { return .op("-", [a, try neg(b)]) }
310            if looksNeg(a, loose: false) { return .op("-", [b, try neg(a)]) }
311            return .op("+", [a, b])
312        }
313
314        /// The `cond` in `math-add-symb-fancy` that handles infinities and like terms.
315        static func combineSums(_ a: Term, _ b: Term) throws -> Term? {
316            if let infA = infinitep(a) {
317                guard let infB = infinitep(b) else { return a }
318                if [uinf, nan].contains(infA) || [uinf, nan].contains(infB) { return nan }
319                let dirA = try infiniteDirection(a, infA)
320                let dirB = try infiniteDirection(b, infB)
321                guard let x = number(dirA), let y = number(dirB) else { return nil }
322                return try compare(x, y) == 0 ? a : nan
323            }
324            if infinitep(b) != nil { return b }
325            if head(a) == "+" {
326                return try combineSum(arg(a, 2), b, negA: false, negB: false, scalarOkay: true).map { try add(arg(a, 1), $0) }
327            }
328            if head(a) == "-" {
329                return try combineSum(arg(a, 2), b, negA: true, negB: false, scalarOkay: true).map { try add(arg(a, 1), $0) }
330            }
331            if objectp(a), objectp(b) { return nil }
332            return try combineSum(a, b, negA: false, negB: false, scalarOkay: false)
333        }
334
335        /// `math-infinite-dir`: the formula with its infinity replaced by 1.
336        static func infiniteDirection(_ a: Term, _ infinity: Term) throws -> Term {
337            func substitute(_ t: Term) -> Term {
338                if t == infinity { return .number(.int(1)) }
339                if case .op(let f, let args) = t { return .op(f, args.map(substitute)) }
340                return t
341            }
342            return try normalize(substitute(a))
343        }
344
345        /// `math-combine-sum`: two terms that are multiples of the same thing, added.
346        static func combineSum(_ a: Term, _ b: Term, negA: Bool, negB: Bool, scalarOkay: Bool) throws -> Term? {
347            if scalarOkay, objectp(a), objectp(b) {
348                return try add(negA ? try neg(a) : a, negB ? try neg(b) : b)
349            }
350            /// The coefficient and the rest; a nil coefficient is Calc's `(frac 1 0)`.
351            func split(_ t: Term) throws -> (Term?, Term) {
352                switch head(t) {
353                case "*" where objectp(arg(t, 1)): return (arg(t, 1), arg(t, 2))
354                case "/" where objectp(arg(t, 2)):
355                    let d = arg(t, 2)
356                    if case .number(.int(let n)) = d { return (n == 0 ? nil : .number(try fraction(1, n)), arg(t, 1)) }
357                    return (try div(.number(.int(1)), d), arg(t, 1))
358                case "neg": return (.number(.int(-1)), arg(t, 1))
359                default: return (.number(.int(1)), t)
360                }
361            }
362            let (multA, restA) = try split(a)
363            let (multB, restB) = try split(b)
364            guard restA == restB else { return nil }
365            // `math-make-frac` of two such coefficients divides by zero.
366            if multA == nil, multB == nil { throw Rejected() }
367            guard var ma = multA, var mb = multB else { throw Unsupported("division by zero") }
368            if negA { ma = try neg(ma) }
369            if negB { mb = try neg(mb) }
370            return try mul(try add(ma, mb), restA)
371        }
372
373        /// `math-mul`.
374        static func mul(_ a: Term, _ b: Term) throws -> Term {
375            if let product = try numeric(a, b, { try multiply($0, $1) }) { return product }
376            if zerop(a) { return try mulZero(a, b) }
377            if zerop(b) { return try mulZero(b, a) }
378            return try mulFancy(a, b)
379        }
380
381        /// `math-mul-zero`, `a` zero and `b` a formula.
382        static func mulZero(_ a: Term, _ b: Term) throws -> Term {
383            if infinitep(b) != nil { return nan }
384            return floatp(a) || floatp(b) ? .number(.float(0, 0)) : .number(.int(0))
385        }
386
387        /// `math-mul-symb-fancy`.
388        static func mulFancy(_ a: Term, _ b: Term) throws -> Term {
389            if equalInt(a, 1) { return b }
390            if equalInt(a, -1) { return try neg(b) }
391            if objectp(b), !objectp(a) { return try mul(b, a) }
392            if head(a) == "neg" { return try neg(try mul(arg(a, 1), b)) }
393            if head(b) == "neg" { return try neg(try mul(a, arg(b, 1))) }
394            if head(a) == "*" { return try mul(arg(a, 1), try mul(arg(a, 2), b)) }
395            let negativePower = { (t: Term) in head(t) == "^" && looksNeg(arg(t, 2), loose: false) }
396            if negativePower(a), !negativePower(b) {
397                return try div(b, try normalize(.op("^", [arg(a, 1), try neg(arg(a, 2))])))
398            }
399            if negativePower(b), !negativePower(a) {
400                return try div(a, try normalize(.op("^", [arg(b, 1), try neg(arg(b, 2))])))
401            }
402            if head(a) == "/" {
403                if let c = try combineProd(arg(a, 2), b, invA: true, invB: false, scalarOkay: true) { return try mul(arg(a, 1), c) }
404                return try div(try mul(arg(a, 1), b), arg(a, 2))
405            }
406            if head(b) == "/" { return try div(try mul(a, arg(b, 1)), arg(b, 2)) }
407            if let f = head(b), f == "+" || f == "-", objectp(a), objectp(arg(b, 1)) || objectp(arg(b, 2)) {
408                let (x, y) = (try mul(a, arg(b, 1)), try mul(a, arg(b, 2)))
409                return f == "+" ? try add(x, y) : try sub(x, y)
410            }
411            if head(b) == "*", objectp(arg(b, 1)), !objectp(a) { return try mul(arg(b, 1), try mul(a, arg(b, 2))) }
412            if looksNeg(b) || (head(b) == "-" && looksNeg(a)) { return try mul(try neg(a), try neg(b)) }
413            if head(b) == "*" {
414                if let c = try combineProd(a, arg(b, 1), invA: false, invB: false, scalarOkay: true) { return try mul(c, arg(b, 2)) }
415            } else if let c = try combineProd(a, b, invA: false, invB: false, scalarOkay: false) {
416                return c
417            }
418            for special in [nan, uinf] {
419                if a == special { return a }
420                if b == special { return b }
421            }
422            if b == inf {
423                switch try signs(a) {
424                case 4: return b
425                case 1: return try neg(b)
426                case 3, 6: throw Unsupported("symbolic arithmetic")
427                default: break
428                }
429            }
430            if a == inf { return try mul(b, a) }
431            return .op("*", [a, b])
432        }
433
434        /// `math-div`.
435        static func div(_ a: Term, _ b: Term) throws -> Term {
436            if zerop(b) {
437                // `math-div-by-zero`.
438                guard let infinity = infinitep(a) else { throw Rejected() }
439                return infinity == nan ? a : uinf
440            }
441            if let quotient = try numeric(a, b, { try divide($0, $1, fractions: fractions) }) { return quotient }
442            // `math-div-zero`.
443            if zerop(a) { return b == nan ? b : a }
444            return try divFancy(a, b)
445        }
446
447        /// `math-div-symb-fancy`.
448        static func divFancy(_ a: Term, _ b: Term) throws -> Term {
449            if equalInt(b, 1) { return a }
450            if equalInt(b, -1) { return try neg(a) }
451            if head(b) == "^", looksNeg(arg(b, 2), loose: false) || equalInt(a, 1) {
452                return try mul(a, try normalize(.op("^", [arg(b, 1), try neg(arg(b, 2))])))
453            }
454            if head(a) == "neg" { return try neg(try div(arg(a, 1), b)) }
455            if head(b) == "neg" { return try neg(try div(a, arg(b, 1))) }
456            if head(a) == "/" { return try div(arg(a, 1), try mul(arg(a, 2), b)) }
457            if head(b) == "/" { return try div(try mul(a, arg(b, 2)), arg(b, 1)) }
458            if case .number(.frac(let n, let d)) = b { return try mul(.number(try fraction(d, n)), a) }
459            if let f = head(a), f == "+" || f == "-", objectp(arg(a, 1)) || objectp(arg(a, 2)), objectp(b) {
460                let (x, y) = (try div(arg(a, 1), b), try div(arg(a, 2), b))
461                return f == "+" ? try add(x, y) : try sub(x, y)
462            }
463            if head(a) == "-" || looksNeg(a), looksNeg(b) { return try div(try neg(a), try neg(b)) }
464            if head(b) == "-", looksNeg(a) { return try div(try neg(a), try neg(b)) }
465            if head(a) == "*" {
466                if head(b) == "*" {
467                    if let c = try combineProd(arg(a, 1), arg(b, 1), invA: false, invB: true, scalarOkay: true) {
468                        return try div(try mul(c, arg(a, 2)), arg(b, 2))
469                    }
470                } else if let c = try combineProd(arg(a, 1), b, invA: false, invB: true, scalarOkay: true) {
471                    return try mul(c, arg(a, 2))
472                }
473            } else if head(b) == "*" {
474                if let c = try combineProd(a, arg(b, 1), invA: false, invB: true, scalarOkay: true) { return try div(c, arg(b, 2)) }
475            } else if let c = try combineProd(a, b, invA: false, invB: true, scalarOkay: false) {
476                return c
477            }
478            if infinitep(a) != nil {
479                if infinitep(b) != nil { return nan }
480                if a == nan || a == uinf { return a }
481                if a == inf {
482                    if posp(b) { return a }
483                    if negp(b) { return try neg(a) }
484                    if objectp(b) { throw Unsupported("symbolic arithmetic") }
485                }
486            }
487            if infinitep(b) != nil {
488                if b == nan { return b }
489                return floatp(a) || floatp(b) ? .number(.float(0, 0)) : .number(.int(0))
490            }
491            return .op("/", [a, b])
492        }
493
494        /// `math-mul-or-div`.
495        static func mulOrDiv(_ a: Term, _ b: Term, invA: Bool, invB: Bool) throws -> Term {
496            if invA { return invB ? try div(try div(.number(.int(1)), a), b) : try div(b, a) }
497            return invB ? try div(a, b) : try mul(a, b)
498        }
499
500        /// `math-combine-prod`: two factors that are powers of the same thing, multiplied.
501        static func combineProd(_ a: Term, _ b: Term, invA: Bool, invB: Bool, scalarOkay: Bool) throws -> Term? {
502            if (invA && zerop(a)) || (invB && zerop(b)) { return nil }
503            if scalarOkay, objectp(a), objectp(b) {
504                let r = try mulOrDiv(a, b, invA: invA, invB: invB)
505                return objectp(r) ? r : nil
506            }
507            if head(a) == "^", invA, looksNeg(arg(a, 2)) { return try mul(try pow(arg(a, 1), try neg(arg(a, 2))), b) }
508            if head(b) == "^", invB, looksNeg(arg(b, 2)) { return try mul(a, try pow(arg(b, 1), try neg(arg(b, 2)))) }
509            func split(_ t: Term) throws -> (Term, Term) {
510                var (base, power) = (t, Term.number(.int(1)))
511                if head(t) == "^", objectp(arg(t, 2)) { (base, power) = (arg(t, 1), arg(t, 2)) }
512                if head(t) == "sqrt" || head(t) == "exp" { throw Unsupported("symbolic arithmetic") }
513                if case .number(.frac(let n, let d)) = base, n < d {
514                    (base, power) = (try div(.number(.int(1)), base), try neg(power))
515                }
516                return (base, power)
517            }
518            var (baseA, powA) = try split(a)
519            var (baseB, powB) = try split(b)
520            if invA { powA = try neg(powA) }
521            if invB { powB = try neg(powB) }
522            func isFrac(_ t: Term) -> Bool {
523                if case .number(.frac) = t { return true }
524                return false
525            }
526            if baseA == baseB {
527                var sum = try add(powA, powB)
528                if !integerp(baseA) || zerop(sum) || isFrac(powA) == isFrac(powB) {
529                    if looksNeg(sum), ratp(baseA), posp(baseA) {
530                        (baseA, sum) = (try div(.number(.int(1)), baseA), try neg(sum))
531                    }
532                    if sum == .number(.frac(1, 2)) || sum == .number(.frac(-1, 2)) { throw Unsupported("symbolic arithmetic") }
533                    return try pow(baseA, sum)
534                }
535            }
536            if powA == powB, case .number(.int(let x)) = baseA, case .number(.int(let y)) = baseB, x >= 0, y >= 0 {
537                if powA == .number(.frac(1, 2)) || powA == .number(.frac(-1, 2)) { throw Unsupported("symbolic arithmetic") }
538                return try pow(try mul(baseA, baseB), powA)
539            }
540            return nil
541        }
542
543        /// `math-pow`.
544        static func pow(_ a: Term, _ b: Term) throws -> Term {
545            if b == nan { return b }
546            if zerop(a) {
547                if let y = number(b) {
548                    if try sign(y) > 0 { return floatp(b) ? try float(a) : a }
549                    return .number(try power(number(a)!, y, fractions: fractions))
550                }
551                // `math-pow-of-zero` with a formula.
552                switch try signs(b) {
553                case 4: return a
554                case 1: return try div(.number(.int(1)), a)
555                default: return infinitep(b) != nil ? nan : .op("^", [a, b])
556                }
557            }
558            if a == .number(.int(1)) || b == .number(.int(1)) { return a }
559            if a == .number(.float(1, 0)) || b == .number(.float(1, 0)) { return a }
560            if zerop(b) {
561                if let x = number(a) { return .number(try power(x, number(b)!, fractions: fractions)) }
562                // `math-pow-zero`.
563                if infinitep(a) != nil { return nan }
564                return floatp(b) ? .number(.float(1, 0)) : .number(.int(1))
565            }
566            if let x = number(a), let y = number(b) { return .number(try power(x, y, fractions: fractions)) }
567            return try powFancy(a, b)
568        }
569
570        /// `math-pow-fancy` with a formula.
571        static func powFancy(_ a: Term, _ b: Term) throws -> Term {
572            let (a1, a2) = (arg(a, 1), arg(a, 2))
573            switch head(a) {
574            case "*" where try knownNumInteger(b) || knownNonneg(a1) || knownNonneg(a2):
575                return try mul(try pow(a1, b), try pow(a2, b))
576            case "/" where try knownNumInteger(b) || knownNonneg(a2):
577                return try div(try pow(a1, b), try pow(a2, b))
578            case "/" where try knownNonneg(a1) && !equalInt(a1, 1):
579                return try mul(try pow(a1, b), try pow(try div(.number(.int(1)), a2), b))
580            case "^" where try knownNumInteger(b) || knownNonneg(a1):
581                return try pow(a1, try mul(a2, b))
582            case "^":
583                // `math-known-evenp` of an exponent with a variable is false.
584                if case .number(let n) = a2, isWhole(n), try trunc(n) % 2 == 0, let y = number(b), let q = quarter(y),
585                   (1...3).contains(q), try signs(a1) < 8 { throw Unsupported("symbolic arithmetic") }
586            default: break
587            }
588            if looksNeg(a), case .number(.int(let n)) = b {
589                let p = try pow(try neg(a), b)
590                return n % 2 == 0 ? p : try neg(p)
591            }
592            if let infinity = infinitep(a) {
593                if infinity == nan { return infinity }
594                if head(a) == "neg" { return try mul(try pow(.number(.int(-1)), b), try pow(a1, b)) }
595                if posp(b) { return a }
596                if negp(b) { return floatp(b) ? .number(.float(0, 0)) : .number(.int(0)) }
597                if objectp(b) || infinitep(b) != nil { return nan }
598                throw Unsupported("symbolic arithmetic")
599            }
600            if infinitep(b) != nil {
601                guard let x = number(a), b == inf else { throw Unsupported("symbolic arithmetic") }
602                // `calcFunc-abssqr` of a real number is its square.
603                let scale = try multiply(x, x)
604                if scale == .int(1) || scale == .float(1, 0) { return nan }
605                if try compare(scale, .int(1)) < 0 { return floatp(a) ? .number(.float(0, 0)) : .number(.int(0)) }
606                if try compare(.int(1), x) < 0 { return b }
607                return uinf
608            }
609            return .op("^", [a, b])
610        }
611
612        // MARK: Display
613
614        /// `math-format-value`: `math-compose-expr` in the flat language.
615        static func format(_ t: Term, _ floatFormat: FloatFormat) throws -> String {
616            let text = try compose(t, 0, floatFormat)
617            // Past its width of 1000, `calc-eval` breaks the line.
618            guard text.count < 1000 else { throw Unsupported("symbolic arithmetic") }
619            return text
620        }
621
622        /// Left and right precedence, from `math-standard-ops` with
623        /// `calc-multiplication-has-precedence`.
624        static let operators: [String: (Int, Int)] = ["+": (180, 181), "-": (180, 181), "*": (196, 195), "/": (190, 191), "^": (201, 200)]
625
626        static func compose(_ t: Term, _ prec: Int, _ floatFormat: FloatFormat, div: Bool = false) throws -> String {
627            switch t {
628            case .number(let v): return try Calc.format(v, floatFormat)
629            case .variable(let name): return name
630            case .op("neg", let args):
631                if prec > 197 { return "(" + (try compose(t, 0, floatFormat)) + ")" }
632                return "-" + (try compose(args[0], 197, floatFormat))
633            case .op(let f, let args):
634                guard let (left, right) = operators[f], args.count == 2 else {
635                    return f + "(" + (try args.map { try compose($0, 0, floatFormat) }).joined(separator: ", ") + ")"
636                }
637                if prec > min(left, right) || (div && f == "*") { return "(" + (try compose(t, 0, floatFormat)) + ")" }
638                var lhs = try compose(args[0], left, floatFormat)
639                let rhs = try compose(args[1], right, floatFormat, div: f == "/")
640                if f == "^", lhs.first == "-" { lhs = "(" + lhs + ")" }
641                if f == "*", let next = rhs.first {
642                    var lastFactor = args[0]
643                    while head(lastFactor) == "*" { lastFactor = arg(lastFactor, 2) }
644                    let isVariable = if case .variable = lastFactor { true } else { false }
645                    if (next.isASCII && (next.isLetter || next.isNumber)) || ".#_([{".contains(next), !(isVariable && next == "(") {
646                        return lhs + " " + rhs
647                    }
648                    return lhs + "*" + rhs
649                }
650                if f == "^" { return lhs + "^" + rhs }
651                if f == "/", let x = number(args[0]), isWhole(x), case .number(.int) = args[1] { return lhs + "/" + rhs }
652                return lhs + " " + f + " " + rhs
653            }
654        }
655    }
656}
657
658extension Calc.Term {
659    /// Whether an operator or function in the formula satisfies `predicate`.
660    func contains(where predicate: (String) -> Bool) -> Bool {
661        guard case .op(let f, let args) = self else { return false }
662        return predicate(f) || args.contains { $0.contains(where: predicate) }
663    }
664}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form