Sources/OrgCore/Compute/CalcSymbolic.swift
1000 lines · 49884 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; `math-sqrt`, `math-abs`, `math-mod`, `calcFunc-exp`, `calcFunc-ln`,
7/// `calcFunc-min`, `calcFunc-max` and the comparisons and logical functions of calc-prog.el on
8/// formulas; and Calc's flat formula printer from calccomp.el. Anything
9/// those functions would decide from declarations, units, matrices or intervals throws
10/// `Calc.Unsupported`.
11extension Calc {
12 /// A formula, as Calc's Lisp form: a number, a variable, or an operator or function with
13 /// its arguments (`+ - * / ^ neg`, or a function name).
14 public indirect enum Term: Equatable, Sendable {
15 case number(Value)
16 case variable(String)
17 case op(String, [Term])
18 }
19
20 /// `math-reject-arg`: the operation stays unevaluated.
21 struct Rejected: Error {}
22
23 /// `calc-symbolic-mode`.
24 @TaskLocal static var symbolicMode = false
25
26 /// `calc-prefer-frac`, for the division the arithmetic does.
27 @TaskLocal static var fractions = false
28
29 /// How deeply `mul` calls itself in one evaluation. Some products rewrite themselves
30 /// without end, where Calc stops at `max-lisp-eval-depth`; past `limit` they are refused.
31 final class Nesting: @unchecked Sendable {
32 static let limit = 64
33 var depth = 0
34 }
35 @TaskLocal static var nesting: Nesting?
36
37 /// Variables Calc gives a value or a declaration, which would change the arithmetic.
38 static let reserved: Set<String> = ["CommuteRules", "Decls", "DistribRules", "EvalRules", "FactorRules", "FitRules",
39 "Holidays", "IntegAfterRules", "InvertRules", "JumpRules", "MergeRules", "Modes",
40 "NegateRules"]
41
42 /// The special constants and infinities, whose sign or type Calc knows.
43 static let constants: Set<String> = ["pi", "e", "phi", "gamma", "i", "inf", "uinf", "nan"]
44
45 static func term(_ v: Value) throws -> Term {
46 switch v {
47 case .symbolic(let t): return t
48 case .nan: return .variable("nan")
49 case .int, .float, .frac: return .number(v)
50 case .vector, .date: throw Unsupported("symbolic arithmetic")
51 }
52 }
53
54 static func value(_ t: Term) -> Value {
55 switch t {
56 case .number(let v): return v
57 case .variable("nan"): return .nan
58 default: return .symbolic(t)
59 }
60 }
61
62 enum Symbolic {
63 static let inf = Term.variable("inf")
64 static let uinf = Term.variable("uinf")
65 static let nan = Term.variable("nan")
66
67 // MARK: Predicates
68
69 static func number(_ t: Term) -> Value? {
70 if case .number(let v) = t { return v }
71 return nil
72 }
73
74 static func head(_ t: Term) -> String? {
75 if case .op(let f, _) = t { return f }
76 return nil
77 }
78
79 /// `(nth n a)`, from 1.
80 static func arg(_ t: Term, _ n: Int) -> Term {
81 guard case .op(_, let args) = t, n - 1 < args.count else { return .number(.int(0)) }
82 return args[n - 1]
83 }
84
85 static func objectp(_ t: Term) -> Bool { number(t) != nil }
86 static func zerop(_ t: Term) -> Bool { number(t).map(isZero) ?? false }
87 static func floatp(_ t: Term) -> Bool {
88 if case .number(.float) = t { return true }
89 return false
90 }
91 static func ratp(_ t: Term) -> Bool { number(t).map { rational($0) != nil } ?? false }
92 static func integerp(_ t: Term) -> Bool {
93 if case .number(.int) = t { return true }
94 return false
95 }
96
97 /// `math-negp`.
98 static func negp(_ t: Term) -> Bool {
99 if let v = number(t) { return (try? sign(v)) == -1 }
100 return t == .op("neg", [inf])
101 }
102
103 /// `math-posp`.
104 static func posp(_ t: Term) -> Bool {
105 if let v = number(t) { return (try? sign(v)) == 1 }
106 return t == inf
107 }
108
109 /// `Math-equal-int`.
110 static func equalInt(_ t: Term, _ n: Int) -> Bool {
111 t == .number(.int(n)) || t == .number(.float(n, 0))
112 }
113
114 /// `math-looks-negp`; `loose` false is the `Math-looks-negp` macro, which doesn't
115 /// look inside a difference.
116 static func looksNeg(_ t: Term, loose: Bool = true) -> Bool {
117 if negp(t) { return true }
118 switch head(t) {
119 case "neg": return true
120 case "*", "/": return looksNeg(arg(t, 1)) || looksNeg(arg(t, 2))
121 case "-": return loose && looksNeg(arg(t, 1))
122 default: return false
123 }
124 }
125
126 /// `math-infinitep`: the infinity a product, quotient or negation is made of.
127 static func infinitep(_ t: Term) -> Term? {
128 var a = t
129 while let f = head(a), ["*", "/", "neg"].contains(f) {
130 a = f != "*" || infinitep(arg(a, 1)) != nil ? arg(a, 1) : arg(a, 2)
131 }
132 return [inf, uinf, nan].contains(a) ? a : nil
133 }
134
135 static func containsConstant(_ t: Term) -> Bool {
136 switch t {
137 case .number: false
138 case .variable(let name): constants.contains(name)
139 case .op(_, let args): args.contains(where: containsConstant)
140 }
141 }
142
143 /// `math-possible-signs`: the bits 1 negative, 2 zero, 4 positive and 8 not real,
144 /// relative to `origin`. Nothing is declared, so a variable may be anything.
145 static func signs(_ a: Term, _ origin: Term? = nil) throws -> Int {
146 func negSigns(_ s: Int) -> Int {
147 s >= 8 ? 8 + negSigns(s - 8) : (s & 1 != 0 ? 4 : 0) | (s & 2) | (s & 4 != 0 ? 1 : 0)
148 }
149 if objectp(a) {
150 let x = try origin.map { try sub(a, $0) } ?? a
151 return posp(x) ? 4 : negp(x) ? 1 : 2
152 }
153 let (a1, a2) = (arg(a, 1), arg(a, 2))
154 let f = head(a)
155 if f == "+" || f == "-" {
156 if objectp(a1) {
157 if f == "-" { return negSigns(try signs(a2, try origin.map { try add($0, a1) } ?? a1)) }
158 return try signs(a2, try origin.map { try sub($0, a1) } ?? (try neg(a1)))
159 }
160 if objectp(a2) {
161 let org = f == "-" ? a2 : try neg(a2)
162 return try signs(a1, try origin.map { try add($0, org) } ?? org)
163 }
164 let s1 = try signs(a1, origin)
165 var s2 = try signs(a2)
166 if f == "-" { s2 = negSigns(s2) }
167 if s1 == s2 { return s1 }
168 if s1 == 2 { return s2 }
169 if s2 == 2 { return s1 }
170 if s1 >= 8 || s2 >= 8 { return 15 }
171 if (s1, s2) == (4, 6) || (s1, s2) == (6, 4) { return 4 }
172 if (s1, s2) == (1, 3) || (s1, s2) == (3, 1) { return 1 }
173 return 7
174 }
175 if f == "neg" { return negSigns(try signs(a1, try origin.map(neg))) }
176 var origin = origin.flatMap { zerop($0) ? nil : $0 }
177 let zero = Term.number(.int(0))
178 if f == "*" || (f == "/" && origin != nil), objectp(a1) {
179 let s = f == "*"
180 ? (zerop(a1) ? try signs(zero, origin) : try signs(a2, try div(origin ?? zero, a1)))
181 : negSigns(try signs(a2, try div(a1, origin!)))
182 return negp(a1) ? negSigns(s) : s
183 }
184 if f == "*" || f == "/", objectp(a2) {
185 let s = try signs(a1, f == "*" ? try mul(origin ?? zero, a2) : try div(origin ?? zero, a2))
186 return negp(a2) ? negSigns(s) : s
187 }
188 let sign: Int
189 switch a {
190 case .op("*", _), .op("/", _):
191 let (s1, s2) = (try signs(a1), try signs(a2))
192 if s1 >= 8 || s2 >= 8 || (f == "/" && [2, 3, 6, 7].contains(s2)) {
193 sign = 15
194 } else {
195 sign = (s1 & 4 != 0 ? s2 : 0) | (s1 & 2) | (s1 & 1 != 0 ? negSigns(s2) : 0)
196 }
197 case .op("^", _):
198 let (s1, s2) = (try signs(a1), try signs(a2))
199 if s1 >= 8 || s2 >= 8 {
200 sign = 15
201 } else if s1 == 4 {
202 sign = 4
203 } else if s1 == 2 {
204 sign = s2 == 4 ? 2 : 15
205 } else if s2 == 2 {
206 sign = [1, 5].contains(s1) ? 2 : 15
207 } else if case .number(.int(let n)) = a2 {
208 sign = n % 2 == 0 ? ([3, 6, 7].contains(s1) ? 6 : 4) : s1
209 } else if s1 == 6 {
210 sign = s2 == 4 ? 6 : 15
211 } else {
212 sign = 7
213 }
214 case .variable(let name):
215 switch name {
216 case "pi", "e":
217 guard origin == nil else { throw Unsupported("symbolic arithmetic") }
218 return 4
219 case "inf": return 4
220 case "uinf": return 13
221 case "i": return 8
222 default: return 15
223 }
224 case .op("%", let args):
225 let s2 = try signs(args[1])
226 sign = s2 >= 8 ? 7 : s2 == 2 ? 2 : [4, 6].contains(s2) ? 6 : [1, 3].contains(s2) ? 3 : 7
227 case .op("abs", let args):
228 let s1 = try signs(args[0])
229 sign = s1 == 2 ? 2 : [1, 4, 5].contains(s1) ? 4 : 6
230 case .op("exp", let args):
231 let s1 = try signs(args[0])
232 if s1 >= 8 {
233 sign = 15
234 } else if origin == nil || negp(origin!) {
235 sign = 4
236 } else {
237 origin = try sub(origin!, .number(.int(1)))
238 if zerop(origin!) { origin = nil }
239 sign = s1
240 }
241 case .op("ln", let args):
242 sign = try knownNonneg(args[0]) ? try signs(args[0], .number(.int(1))) : 15
243 case .op("sqrt", let args):
244 let s1 = try signs(args[0])
245 sign = [2, 4, 6].contains(s1) ? s1 : 15
246 case .op(let f, _) where ["eq", "neq", "lt", "gt", "leq", "geq", "lnot", "max", "min"].contains(f):
247 sign = 7
248 // Nothing is declared about the other functions.
249 case .op(let f, _) where functions.contains(f) || f == "if": return 15
250 default: throw Unsupported("function \(f ?? "")")
251 }
252 guard let origin else { return sign }
253 if posp(origin) { return (sign & 8) + ([1, 2, 3, 8, 9, 10, 11].contains(sign) ? 1 : 7) }
254 return (sign & 8) + ([2, 4, 6, 8, 10, 12, 14].contains(sign) ? 4 : 7)
255 }
256
257 static func knownNonneg(_ t: Term) throws -> Bool { [2, 4, 6].contains(try signs(t)) }
258
259 static func knownReal(_ t: Term) throws -> Bool { try signs(t) < 8 }
260
261 /// `math-known-evenp`.
262 static func knownEven(_ t: Term) throws -> Bool {
263 switch t {
264 case .number(.int(let n)): return n % 2 == 0
265 case .number(.float(let m, let e)) where e >= 0: return e > 0 || m % 2 == 0
266 case .op("*", let args):
267 if try knownEven(args[0]) { return try knownNumInteger(args[1]) }
268 return try knownNumInteger(args[0]) && knownEven(args[1])
269 case .op("+", let args), .op("-", let args):
270 return try (knownEven(args[0]) && knownEven(args[1])) || (knownOdd(args[0]) && knownOdd(args[1]))
271 case .op("neg", let args): return try knownEven(args[0])
272 default: return false
273 }
274 }
275
276 /// `math-known-oddp`.
277 static func knownOdd(_ t: Term) throws -> Bool {
278 switch t {
279 case .number(.int(let n)): return n % 2 != 0
280 case .number(.float(let m, let e)) where e >= 0: return e == 0 && m % 2 != 0
281 case .op("+", let args), .op("-", let args):
282 return try (knownEven(args[0]) && knownOdd(args[1])) || (knownOdd(args[0]) && knownEven(args[1]))
283 case .op("neg", let args): return try knownOdd(args[0])
284 default: return false
285 }
286 }
287
288 /// `math-known-num-integerp`.
289 static func knownNumInteger(_ t: Term) throws -> Bool {
290 if let v = number(t) { return isWhole(v) }
291 guard !containsConstant(t) else { throw Unsupported("symbolic arithmetic") }
292 return try possibleTypes(t, num: true) <= 3
293 }
294
295 /// `math-possible-types`: the bits 1 integer, 2 integer-valued float, 4 fraction and
296 /// 8 float, with `num` merging 1 and 2 and merging 4 and 8. Nothing is declared, so a
297 /// variable may be anything (63). Results above 15 are all 63 here: only whether a
298 /// result is at most 3 is used, and no larger operand can make it so.
299 static func possibleTypes(_ a: Term, num: Bool = false) throws -> Int {
300 func merge(_ t1: Int, _ t2: Int, _ mask: Int) -> Int {
301 if num { return mask * 3 }
302 return (t1 & 5 > 0 && t2 & 5 > 0 ? mask : 0) | ((t1 | t2) & 10 > 0 ? mask * 2 : 0)
303 }
304 switch a {
305 case .number(.int): return num ? 3 : 1
306 case .number(.float(_, let e)) where e >= 0: return num ? 3 : 2
307 case .number(.frac): return num ? 12 : 4
308 case .number(.float): return num ? 12 : 8
309 case .number: throw Unsupported("symbolic arithmetic")
310 case .variable: return 63
311 case .op("neg", let args): return try possibleTypes(args[0])
312 case .op("sqrt", let args):
313 let s1 = try signs(args[0])
314 let t = (s1 & 2 > 0 ? 3 : 0) | (s1 & 1 > 0 ? 16 : 0) | (s1 & 4 > 0 ? 15 : 0) | (s1 & 8 > 0 ? 32 : 0)
315 return t < 16 ? t : 63
316 case .op("abs", let args):
317 let t1 = try possibleTypes(args[0])
318 return t1 >= 16 ? 15 : t1
319 case .op(let f, let args) where args.count == 2 && ["+", "-", "*", "/", "^", "%"].contains(f):
320 // `%` keeps only the real bits, which the merged values above 15 don't give.
321 if f == "%", args.contains(where: { containsHead($0, "sqrt") }) { throw Unsupported("symbolic arithmetic") }
322 var (t1, t2) = (try possibleTypes(args[0], num: num), try possibleTypes(args[1], num: num))
323 if f == "%" { (t1, t2) = (t1 & 15, t2 & 15) }
324 let t12 = t1 | t2
325 if f == "^" {
326 guard t2 <= 3, try knownNonneg(args[1]), t1 < 16 else {
327 return try knownNonneg(args[0]) && signs(args[1]) == 4 ? 15 : 63
328 }
329 let mask = (t1 & 3 > 0 ? 1 : 0) | (t1 & 4) | (t1 & 12 > 0 ? 5 : 0)
330 return merge(t1, t2, mask)
331 }
332 guard t12 < 16 else { return 63 }
333 if f == "/" {
334 if t12 & 10 > 0 { return 10 }
335 return t1 == 4 || t2 == 4 || fractions ? 5 : 15
336 }
337 let mask = t12 <= 3 ? 1
338 : ((t1 <= 3 && t2 & 3 == 0) || (t2 <= 3 && t1 & 3 == 0)) && (f == "+" || f == "-") ? 4 : 5
339 return merge(t1, t2, mask)
340 case .op(let f, _) where functions.contains(f) || f == "if": return 63
341 default: throw Unsupported("function \(head(a) ?? "")")
342 }
343 }
344
345 static func containsHead(_ t: Term, _ f: String) -> Bool {
346 guard case .op(let g, let args) = t else { return false }
347 return g == f || args.contains { containsHead($0, f) }
348 }
349
350 // MARK: Arithmetic
351
352 /// `math-normalize`: the operations applied again from the leaves, floats rounded
353 /// to the precision.
354 static func normalize(_ t: Term) throws -> Term {
355 switch t {
356 case .number(.float(let m, let e)): return .number(try makeFloat(Int128(m), e))
357 case .number, .variable: return t
358 // `math-normalize-logical-op`: the branches stay as written unless the condition
359 // is a number.
360 case .op("if", let args) where args.count == 3:
361 let c = try normalize(args[0])
362 guard let v = number(c) else { return .op("if", [c, args[1], args[2]]) }
363 return try normalize(isZero(v) ? args[2] : args[1])
364 case .op(let f, let args):
365 let args = try args.map(normalize)
366 do { return try apply(f, args) } catch is Rejected { return .op(f, args) }
367 }
368 }
369
370 static func apply(_ f: String, _ args: [Term]) throws -> Term {
371 switch (f, args.count) {
372 case ("+", 2): return try add(args[0], args[1])
373 case ("-", 2): return try sub(args[0], args[1])
374 case ("*", 2): return try mul(args[0], args[1])
375 case ("/", 2): return try div(args[0], args[1])
376 case ("^", 2): return try pow(args[0], args[1])
377 case ("neg", 1): return try neg(args[0])
378 default:
379 guard functions.contains(f) else { throw Unsupported("function \(f)") }
380 return try function(f, args)
381 }
382 }
383
384 static func numeric(_ a: Term, _ b: Term, _ op: (Value, Value) throws -> Value) throws -> Term? {
385 guard let x = number(a), let y = number(b) else { return nil }
386 return try term(try op(x, y))
387 }
388
389 /// `math-float` of a rational number.
390 static func float(_ t: Term) throws -> Term {
391 guard let v = number(t) else { return t }
392 return .number(try Calc.float(v))
393 }
394
395 /// `math-neg`.
396 static func neg(_ a: Term) throws -> Term {
397 if let v = number(a) { return .number(try negate(v)) }
398 func okayNeg(_ t: Term) -> Bool { looksNeg(t) || head(t) == "-" }
399 let (a1, a2) = (arg(a, 1), arg(a, 2))
400 switch head(a) {
401 case "+": return try sub(try neg(a1), a2)
402 case "-": return try sub(a2, a1)
403 case "*", "/":
404 let f = head(a)!
405 if okayNeg(a1) { return .op(f, [try neg(a1), a2]) }
406 if okayNeg(a2) { return .op(f, [a1, try neg(a2)]) }
407 if objectp(a1) || (head(a1) == "*" && objectp(arg(a1, 1))) { return .op(f, [try neg(a1), a2]) }
408 if f == "/", objectp(a2) || (head(a2) == "*" && objectp(arg(a2, 1))) { return .op(f, [a1, try neg(a2)]) }
409 case "neg": return a1
410 default: if a == uinf || a == nan { return a }
411 }
412 return .op("neg", [a])
413 }
414
415 /// `math-add`.
416 static func add(_ a: Term, _ b: Term) throws -> Term {
417 if let sum = try numeric(a, b, { try Calc.add($0, $1) }) { return sum }
418 if zerop(a) { return b }
419 if zerop(b) { return a }
420 return try addFancy(a, b)
421 }
422
423 /// `math-sub`.
424 static func sub(_ a: Term, _ b: Term) throws -> Term { try add(a, try neg(b)) }
425
426 /// `math-add-symb-fancy`.
427 static func addFancy(_ a: Term, _ b: Term) throws -> Term {
428 switch head(b) {
429 case "+": return try add(try add(a, arg(b, 1)), arg(b, 2))
430 case "-": return try sub(try add(a, arg(b, 1)), arg(b, 2))
431 case "neg" where head(arg(b, 1)) == "+":
432 return try sub(try sub(a, arg(arg(b, 1), 1)), arg(arg(b, 1), 2))
433 default: break
434 }
435 if let result = try combineSums(a, b) { return result }
436 if looksNeg(b, loose: false) { return .op("-", [a, try neg(b)]) }
437 if looksNeg(a, loose: false) { return .op("-", [b, try neg(a)]) }
438 return .op("+", [a, b])
439 }
440
441 /// The `cond` in `math-add-symb-fancy` that handles infinities and like terms.
442 static func combineSums(_ a: Term, _ b: Term) throws -> Term? {
443 if let infA = infinitep(a) {
444 guard let infB = infinitep(b) else { return a }
445 if [uinf, nan].contains(infA) || [uinf, nan].contains(infB) { return nan }
446 let dirA = try infiniteDirection(a, infA)
447 let dirB = try infiniteDirection(b, infB)
448 guard let x = number(dirA), let y = number(dirB) else { return nil }
449 return try compare(x, y) == 0 ? a : nan
450 }
451 if infinitep(b) != nil { return b }
452 if head(a) == "+" {
453 return try combineSum(arg(a, 2), b, negA: false, negB: false, scalarOkay: true).map { try add(arg(a, 1), $0) }
454 }
455 if head(a) == "-" {
456 return try combineSum(arg(a, 2), b, negA: true, negB: false, scalarOkay: true).map { try add(arg(a, 1), $0) }
457 }
458 if objectp(a), objectp(b) { return nil }
459 return try combineSum(a, b, negA: false, negB: false, scalarOkay: false)
460 }
461
462 /// `math-infinite-dir`: the formula with its infinity replaced by 1.
463 static func infiniteDirection(_ a: Term, _ infinity: Term) throws -> Term {
464 func substitute(_ t: Term) -> Term {
465 if t == infinity { return .number(.int(1)) }
466 if case .op(let f, let args) = t { return .op(f, args.map(substitute)) }
467 return t
468 }
469 return try normalize(substitute(a))
470 }
471
472 /// `math-combine-sum`: two terms that are multiples of the same thing, added.
473 static func combineSum(_ a: Term, _ b: Term, negA: Bool, negB: Bool, scalarOkay: Bool) throws -> Term? {
474 if scalarOkay, objectp(a), objectp(b) {
475 return try add(negA ? try neg(a) : a, negB ? try neg(b) : b)
476 }
477 /// The coefficient and the rest; a nil coefficient is Calc's `(frac 1 0)`.
478 func split(_ t: Term) throws -> (Term?, Term) {
479 switch head(t) {
480 case "*" where objectp(arg(t, 1)): return (arg(t, 1), arg(t, 2))
481 case "/" where objectp(arg(t, 2)):
482 let d = arg(t, 2)
483 if case .number(.int(let n)) = d { return (n == 0 ? nil : .number(try fraction(1, n)), arg(t, 1)) }
484 return (try div(.number(.int(1)), d), arg(t, 1))
485 case "neg": return (.number(.int(-1)), arg(t, 1))
486 default: return (.number(.int(1)), t)
487 }
488 }
489 let (multA, restA) = try split(a)
490 let (multB, restB) = try split(b)
491 guard restA == restB else { return nil }
492 // `math-make-frac` of two such coefficients divides by zero.
493 if multA == nil, multB == nil { throw Rejected() }
494 guard var ma = multA, var mb = multB else { throw Unsupported("division by zero") }
495 if negA { ma = try neg(ma) }
496 if negB { mb = try neg(mb) }
497 return try mul(try add(ma, mb), restA)
498 }
499
500 /// `math-mul`.
501 static func mul(_ a: Term, _ b: Term) throws -> Term {
502 let nesting = Calc.nesting
503 nesting?.depth += 1
504 defer { nesting?.depth -= 1 }
505 if let nesting, nesting.depth > Nesting.limit { throw Unsupported("symbolic arithmetic") }
506 if let product = try numeric(a, b, { try multiply($0, $1) }) { return product }
507 if zerop(a) { return try mulZero(a, b) }
508 if zerop(b) { return try mulZero(b, a) }
509 return try mulFancy(a, b)
510 }
511
512 /// `math-mul-zero`, `a` zero and `b` a formula.
513 static func mulZero(_ a: Term, _ b: Term) throws -> Term {
514 if infinitep(b) != nil { return nan }
515 return floatp(a) || floatp(b) ? .number(.float(0, 0)) : .number(.int(0))
516 }
517
518 /// `math-mul-symb-fancy`.
519 static func mulFancy(_ a: Term, _ b: Term) throws -> Term {
520 if equalInt(a, 1) { return b }
521 if equalInt(a, -1) { return try neg(b) }
522 if objectp(b), !objectp(a) { return try mul(b, a) }
523 if head(a) == "neg" { return try neg(try mul(arg(a, 1), b)) }
524 if head(b) == "neg" { return try neg(try mul(a, arg(b, 1))) }
525 if head(a) == "*" { return try mul(arg(a, 1), try mul(arg(a, 2), b)) }
526 let negativePower = { (t: Term) in head(t) == "^" && looksNeg(arg(t, 2), loose: false) }
527 if negativePower(a), !negativePower(b) {
528 return try div(b, try normalize(.op("^", [arg(a, 1), try neg(arg(a, 2))])))
529 }
530 if negativePower(b), !negativePower(a) {
531 return try div(a, try normalize(.op("^", [arg(b, 1), try neg(arg(b, 2))])))
532 }
533 if head(a) == "/" {
534 if let c = try combineProd(arg(a, 2), b, invA: true, invB: false, scalarOkay: true) { return try mul(arg(a, 1), c) }
535 return try div(try mul(arg(a, 1), b), arg(a, 2))
536 }
537 if head(b) == "/" { return try div(try mul(a, arg(b, 1)), arg(b, 2)) }
538 if let f = head(b), f == "+" || f == "-", objectp(a), objectp(arg(b, 1)) || objectp(arg(b, 2)) {
539 let (x, y) = (try mul(a, arg(b, 1)), try mul(a, arg(b, 2)))
540 return f == "+" ? try add(x, y) : try sub(x, y)
541 }
542 if head(b) == "*", objectp(arg(b, 1)), !objectp(a) { return try mul(arg(b, 1), try mul(a, arg(b, 2))) }
543 if looksNeg(b) || (head(b) == "-" && looksNeg(a)) { return try mul(try neg(a), try neg(b)) }
544 if head(b) == "*" {
545 if let c = try combineProd(a, arg(b, 1), invA: false, invB: false, scalarOkay: true) { return try mul(c, arg(b, 2)) }
546 } else if let c = try combineProd(a, b, invA: false, invB: false, scalarOkay: false) {
547 return c
548 }
549 for special in [nan, uinf] {
550 if a == special { return a }
551 if b == special { return b }
552 }
553 if b == inf {
554 switch try signs(a) {
555 case 4: return b
556 case 1: return try neg(b)
557 case 3, 6: throw Unsupported("symbolic arithmetic")
558 default: break
559 }
560 }
561 if a == inf { return try mul(b, a) }
562 return .op("*", [a, b])
563 }
564
565 /// `math-div`.
566 static func div(_ a: Term, _ b: Term) throws -> Term {
567 if zerop(b) {
568 // `math-div-by-zero`.
569 guard let infinity = infinitep(a) else { throw Rejected() }
570 return infinity == nan ? a : uinf
571 }
572 if let quotient = try numeric(a, b, { try divide($0, $1, fractions: fractions) }) { return quotient }
573 // `math-div-zero`.
574 if zerop(a) { return b == nan ? b : a }
575 return try divFancy(a, b)
576 }
577
578 /// `math-div-symb-fancy`.
579 static func divFancy(_ a: Term, _ b: Term) throws -> Term {
580 if equalInt(b, 1) { return a }
581 if equalInt(b, -1) { return try neg(a) }
582 if head(b) == "^", looksNeg(arg(b, 2), loose: false) || equalInt(a, 1) {
583 return try mul(a, try normalize(.op("^", [arg(b, 1), try neg(arg(b, 2))])))
584 }
585 if head(a) == "neg" { return try neg(try div(arg(a, 1), b)) }
586 if head(b) == "neg" { return try neg(try div(a, arg(b, 1))) }
587 if head(a) == "/" { return try div(arg(a, 1), try mul(arg(a, 2), b)) }
588 if head(b) == "/" { return try div(try mul(a, arg(b, 2)), arg(b, 1)) }
589 if case .number(.frac(let n, let d)) = b { return try mul(.number(try fraction(d, n)), a) }
590 if let f = head(a), f == "+" || f == "-", objectp(arg(a, 1)) || objectp(arg(a, 2)), objectp(b) {
591 let (x, y) = (try div(arg(a, 1), b), try div(arg(a, 2), b))
592 return f == "+" ? try add(x, y) : try sub(x, y)
593 }
594 if head(a) == "-" || looksNeg(a), looksNeg(b) { return try div(try neg(a), try neg(b)) }
595 if head(b) == "-", looksNeg(a) { return try div(try neg(a), try neg(b)) }
596 if head(a) == "*" {
597 if head(b) == "*" {
598 if let c = try combineProd(arg(a, 1), arg(b, 1), invA: false, invB: true, scalarOkay: true) {
599 return try div(try mul(c, arg(a, 2)), arg(b, 2))
600 }
601 } else if let c = try combineProd(arg(a, 1), b, invA: false, invB: true, scalarOkay: true) {
602 return try mul(c, arg(a, 2))
603 }
604 } else if head(b) == "*" {
605 if let c = try combineProd(a, arg(b, 1), invA: false, invB: true, scalarOkay: true) { return try div(c, arg(b, 2)) }
606 } else if let c = try combineProd(a, b, invA: false, invB: true, scalarOkay: false) {
607 return c
608 }
609 if infinitep(a) != nil {
610 if infinitep(b) != nil { return nan }
611 if a == nan || a == uinf { return a }
612 if a == inf {
613 if posp(b) { return a }
614 if negp(b) { return try neg(a) }
615 if objectp(b) { throw Unsupported("symbolic arithmetic") }
616 }
617 }
618 if infinitep(b) != nil {
619 if b == nan { return b }
620 return floatp(a) || floatp(b) ? .number(.float(0, 0)) : .number(.int(0))
621 }
622 return .op("/", [a, b])
623 }
624
625 /// `math-mul-or-div`.
626 static func mulOrDiv(_ a: Term, _ b: Term, invA: Bool, invB: Bool) throws -> Term {
627 if invA { return invB ? try div(try div(.number(.int(1)), a), b) : try div(b, a) }
628 return invB ? try div(a, b) : try mul(a, b)
629 }
630
631 /// `math-combine-prod`: two factors that are powers of the same thing, multiplied.
632 static func combineProd(_ a: Term, _ b: Term, invA: Bool, invB: Bool, scalarOkay: Bool) throws -> Term? {
633 if (invA && zerop(a)) || (invB && zerop(b)) { return nil }
634 if scalarOkay, objectp(a), objectp(b) {
635 let r = try mulOrDiv(a, b, invA: invA, invB: invB)
636 return objectp(r) ? r : nil
637 }
638 if head(a) == "^", invA, looksNeg(arg(a, 2)) { return try mul(try pow(arg(a, 1), try neg(arg(a, 2))), b) }
639 if head(b) == "^", invB, looksNeg(arg(b, 2)) { return try mul(a, try pow(arg(b, 1), try neg(arg(b, 2)))) }
640 func split(_ t: Term) throws -> (Term, Term) {
641 var (base, power) = (t, Term.number(.int(1)))
642 if head(t) == "^", objectp(arg(t, 2)) { (base, power) = (arg(t, 1), arg(t, 2)) }
643 if head(t) == "sqrt" { (base, power) = (arg(t, 1), .number(.frac(1, 2))) }
644 // Only in symbolic mode does `exp` of a number stay.
645 if head(t) == "exp", objectp(arg(t, 1)) { throw Unsupported("symbolic arithmetic") }
646 if case .number(.frac(let n, let d)) = base, n < d {
647 (base, power) = (try div(.number(.int(1)), base), try neg(power))
648 }
649 return (base, power)
650 }
651 var (baseA, powA) = try split(a)
652 var (baseB, powB) = try split(b)
653 if invA { powA = try neg(powA) }
654 if invB { powB = try neg(powB) }
655 func isFrac(_ t: Term) -> Bool {
656 if case .number(.frac) = t { return true }
657 return false
658 }
659 if baseA == baseB {
660 var sum = try add(powA, powB)
661 if !integerp(baseA) || zerop(sum) || isFrac(powA) == isFrac(powB) {
662 if looksNeg(sum), ratp(baseA), posp(baseA) {
663 (baseA, sum) = (try div(.number(.int(1)), baseA), try neg(sum))
664 }
665 return try root(baseA, sum)
666 }
667 }
668 if powA == powB, case .number(.int(let x)) = baseA, case .number(.int(let y)) = baseB, x >= 0, y >= 0 {
669 return try root(try mul(baseA, baseB), powA)
670 }
671 return nil
672 }
673
674 /// `a^p`, with Calc's square root form for a half.
675 static func root(_ a: Term, _ p: Term) throws -> Term {
676 if p == .number(.frac(1, 2)) { return .op("sqrt", [a]) }
677 if p == .number(.frac(-1, 2)) { return try div(.number(.int(1)), .op("sqrt", [a])) }
678 return try pow(a, p)
679 }
680
681 /// `math-pow`.
682 static func pow(_ a: Term, _ b: Term) throws -> Term {
683 if b == nan { return b }
684 if zerop(a) {
685 if let y = number(b) {
686 if try sign(y) > 0 { return floatp(b) ? try float(a) : a }
687 return .number(try power(number(a)!, y, fractions: fractions))
688 }
689 // `math-pow-of-zero` with a formula.
690 switch try signs(b) {
691 case 4: return a
692 case 1: return try div(.number(.int(1)), a)
693 default: return infinitep(b) != nil ? nan : .op("^", [a, b])
694 }
695 }
696 if a == .number(.int(1)) || b == .number(.int(1)) { return a }
697 if a == .number(.float(1, 0)) || b == .number(.float(1, 0)) { return a }
698 if zerop(b) {
699 if let x = number(a) { return .number(try power(x, number(b)!, fractions: fractions)) }
700 // `math-pow-zero`.
701 if infinitep(a) != nil { return nan }
702 return floatp(b) ? .number(.float(1, 0)) : .number(.int(1))
703 }
704 if let x = number(a), let y = number(b) { return .number(try power(x, y, fractions: fractions)) }
705 return try powFancy(a, b)
706 }
707
708 /// `math-pow-fancy` with a formula.
709 static func powFancy(_ a: Term, _ b: Term) throws -> Term {
710 let (a1, a2) = (arg(a, 1), arg(a, 2))
711 switch head(a) {
712 case "*" where try knownNumInteger(b) || knownNonneg(a1) || knownNonneg(a2):
713 return try mul(try pow(a1, b), try pow(a2, b))
714 case "/" where try knownNumInteger(b) || knownNonneg(a2):
715 return try div(try pow(a1, b), try pow(a2, b))
716 case "/" where try knownNonneg(a1) && !equalInt(a1, 1):
717 return try mul(try pow(a1, b), try pow(try div(.number(.int(1)), a2), b))
718 case "^" where try knownNumInteger(b) || knownNonneg(a1):
719 return try pow(a1, try mul(a2, b))
720 case "sqrt" where try knownNumInteger(b) || knownNonneg(a1):
721 return try pow(a1, try div(b, .number(.int(2))))
722 case "^":
723 if let y = number(b), let q = quarter(y), (1...3).contains(q), try knownEven(a2), try knownReal(a1) {
724 return try absTerm(try pow(a1, try mul(a2, b)))
725 }
726 default: break
727 }
728 if looksNeg(a), case .number(.int(let n)) = b {
729 let p = try pow(try neg(a), b)
730 return n % 2 == 0 ? p : try neg(p)
731 }
732 if head(a) == "abs", try knownReal(a1), try knownEven(b) { return try pow(a1, b) }
733 if let infinity = infinitep(a) {
734 if infinity == nan { return infinity }
735 if head(a) == "neg" { return try mul(try pow(.number(.int(-1)), b), try pow(a1, b)) }
736 if posp(b) { return a }
737 if negp(b) { return floatp(b) ? .number(.float(0, 0)) : .number(.int(0)) }
738 if objectp(b) || infinitep(b) != nil { return nan }
739 throw Unsupported("symbolic arithmetic")
740 }
741 if infinitep(b) != nil {
742 guard let x = number(a), b == inf else { throw Unsupported("symbolic arithmetic") }
743 // `calcFunc-abssqr` of a real number is its square.
744 let scale = try multiply(x, x)
745 if scale == .int(1) || scale == .float(1, 0) { return nan }
746 if try compare(scale, .int(1)) < 0 { return floatp(a) ? .number(.float(0, 0)) : .number(.int(0)) }
747 if try compare(.int(1), x) < 0 { return b }
748 return uinf
749 }
750 return .op("^", [a, b])
751 }
752
753 // MARK: Functions
754
755 /// The functions `function` applies to formulas; `%` is `math-mod`.
756 static let functions: Set<String> = ["sqrt", "abs", "exp", "ln", "min", "max", "eq", "neq", "lt", "gt", "leq", "geq",
757 "land", "lor", "lnot", "%"]
758
759 /// `name` of `args`, at least one a formula, as `math-normalize` calls it: simplified,
760 /// or kept with its arguments when the function rejects them.
761 static func function(_ name: String, _ args: [Term]) throws -> Term {
762 do { return try simplify(name, args) } catch is Rejected { return .op(name, args) }
763 }
764
765 static func simplify(_ name: String, _ args: [Term]) throws -> Term {
766 let kept = Term.op(name, args)
767 switch (name, args.count) {
768 case ("sqrt", 1), ("exp", 1), ("ln", 1):
769 // In symbolic mode these keep a result that isn't exact, which isn't reproduced.
770 guard !symbolicMode else { throw Unsupported("function \(name) in symbolic mode") }
771 switch name {
772 case "sqrt": return try sqrtTerm(args[0])
773 case "exp": return try expTerm(args[0])
774 default: return try lnTerm(args[0])
775 }
776 case ("abs", 1): return try absTerm(args[0])
777 case ("min", _), ("max", _):
778 // `calcFunc-min` rejects an argument that isn't a real number or an infinity.
779 guard !args.isEmpty else { throw Unsupported("arguments") }
780 guard args.allSatisfy({ objectp($0) || infinitep($0) != nil }) else { return kept }
781 return try args.dropFirst().reduce(args[0]) { best, item in
782 switch try compareTerms(best, item) {
783 case 2: return nan
784 case let order: return order == (name == "max" ? -1 : 1) ? item : best
785 }
786 }
787 case ("eq", 2), ("neq", 2), ("lt", 2), ("gt", 2), ("leq", 2), ("geq", 2):
788 let (a, b) = (args[0], args[1])
789 let order = try compareTerms(a, b)
790 if order == 2 {
791 // Both sides negative, or zero, flip.
792 if looksNeg(a) || zerop(a), looksNeg(b) || zerop(b) {
793 return .op(flipped[name]!, [try neg(a), try neg(b)])
794 }
795 return kept
796 }
797 let holds = switch name {
798 case "eq": order == 0
799 case "neq": order != 0
800 case "lt": order == -1
801 case "gt": order == 1
802 case "leq": order != 1
803 default: order != -1
804 }
805 return .number(.int(holds ? 1 : 0))
806 case ("land", 2):
807 let (a, b) = (args[0], args[1])
808 if zerop(a) { return a }
809 if zerop(b) { return b }
810 if try isTrue(a) { return b }
811 if try isTrue(b) { return a }
812 return kept
813 case ("lor", 2):
814 let (a, b) = (args[0], args[1])
815 if zerop(a) { return b }
816 if zerop(b) { return a }
817 if try isTrue(a) { return a }
818 if try isTrue(b) { return b }
819 return kept
820 case ("lnot", 1):
821 let a = args[0]
822 if zerop(a) { return .number(.int(1)) }
823 if try isTrue(a) { return .number(.int(0)) }
824 if case .op(let f, let xs) = a, xs.count == 2, let opposite = negated[f] { return .op(opposite, xs) }
825 return kept
826 case ("%", 2): return try modTerm(args[0], args[1])
827 default: throw Unsupported("function \(name) of a formula")
828 }
829 }
830
831 /// The comparison with its sides negated, and its negation (`calc-tweak-eqn-table`).
832 static let flipped = ["eq": "eq", "neq": "neq", "lt": "gt", "gt": "lt", "leq": "geq", "geq": "leq"]
833 static let negated = ["eq": "neq", "neq": "eq", "lt": "geq", "gt": "leq", "leq": "gt", "geq": "lt"]
834
835 /// `math-is-true`.
836 static func isTrue(_ t: Term) throws -> Bool {
837 if let v = number(t) { return !isZero(v) }
838 return [1, 4, 5, 8, 9, 12, 13].contains(try signs(t))
839 }
840
841 /// `math-compare`: -1, 0 or 1, or 2 when the order isn't known.
842 static func compareTerms(_ a: Term, _ b: Term) throws -> Int {
843 if a == b {
844 switch a {
845 case .number: return 0
846 case .variable, .op("neg", _), .op("*", _), .op("/", _): return infinitep(a) != nil ? 2 : 0
847 default: return 0
848 }
849 }
850 if let x = number(a), let y = number(b) { return try Calc.compare(x, y) }
851 if case .number(.frac(let n, let d)) = a { return try compareTerms(.number(.int(n)), try mul(b, .number(.int(d)))) }
852 if case .number(.frac(let n, let d)) = b { return try compareTerms(try mul(a, .number(.int(d))), .number(.int(n))) }
853 let one = Term.number(.int(1)), minusOne = Term.number(.int(-1))
854 if let infA = infinitep(a) {
855 if a == uinf || a == nan { return 2 }
856 let dirA = try infiniteDirection(a, infA)
857 if let infB = infinitep(b) {
858 if b == uinf || b == nan { return 2 }
859 let dirB = try infiniteDirection(b, infB)
860 return dirA == one && dirB == minusOne ? 1 : dirA == minusOne && dirB == one ? -1 : 2
861 }
862 return dirA == one ? 1 : dirA == minusOne ? -1 : 2
863 }
864 if let infB = infinitep(b) {
865 if b == uinf || b == nan { return 2 }
866 let dirB = try infiniteDirection(b, infB)
867 return dirB == one ? -1 : dirB == minusOne ? 1 : 2
868 }
869 let e = Term.variable("e")
870 if head(a) == "exp", head(b) == "^", arg(b, 1) == e { return try compareTerms(arg(a, 1), arg(b, 2)) }
871 if head(b) == "exp", head(a) == "^", arg(a, 1) == e { return try compareTerms(arg(a, 2), arg(b, 1)) }
872 let half: [Term] = [.number(.frac(1, 2)), .number(.float(5, -1))]
873 if (head(a) == "sqrt" && head(b) == "^" && half.contains(arg(b, 2)))
874 || (head(b) == "sqrt" && head(a) == "^" && half.contains(arg(a, 2))) {
875 return try compareTerms(arg(a, 1), arg(b, 1))
876 }
877 if case .variable = a { return 2 }
878 if case .op(let f, let xs) = a, case .op(let g, let ys) = b, f == g, xs.count == ys.count,
879 try zip(xs, ys).allSatisfy({ try compareTerms($0, $1) == 0 }) { return 0 }
880 return 2
881 }
882
883 /// `math-sqrt` of a formula.
884 static func sqrtTerm(_ a: Term) throws -> Term {
885 if let v = number(a) { return .number(try squareRoot(v)) }
886 // An imaginary result.
887 if [1, 2, 3].contains(try signs(a)) { throw Unsupported("complex result") }
888 let (a1, a2) = (arg(a, 1), arg(a, 2))
889 switch head(a) {
890 case "*" where try knownNonneg(a1) || knownNonneg(a2):
891 return try mul(try sqrtTerm(a1), try sqrtTerm(a2))
892 case "/" where try knownNonneg(a2):
893 return try div(try sqrtTerm(a1), try sqrtTerm(a2))
894 case "/" where try knownNonneg(a1) && !equalInt(a1, 1):
895 return try mul(try sqrtTerm(a1), try sqrtTerm(try div(.number(.int(1)), a2)))
896 case "^" where try knownEven(a2) && knownReal(a1):
897 return try absTerm(try pow(a1, try div(a2, .number(.int(2)))))
898 default: break
899 }
900 if let infinity = infinitep(a) { return try mul(try sqrtTerm(try infiniteDirection(a, infinity)), infinity) }
901 return .op("sqrt", [a])
902 }
903
904 /// `math-abs` of a formula.
905 static func absTerm(_ a: Term) throws -> Term {
906 if let v = number(a) { return .number(try absolute(v)) }
907 if negp(a) { return try neg(a) }
908 if looksNeg(a) { return .op("abs", [try neg(a)]) }
909 let s = try signs(a)
910 if [2, 4, 6].contains(s) { return a }
911 if [1, 3].contains(s) { return try neg(a) }
912 if let infinity = infinitep(a) { return infinity == nan ? nan : inf }
913 return .op("abs", [a])
914 }
915
916 /// `calcFunc-exp` of a formula.
917 static func expTerm(_ a: Term) throws -> Term {
918 if objectp(a) { throw Unsupported("symbolic arithmetic") }
919 if a == inf || a == nan { return a }
920 if a == .op("neg", [inf]) { return .number(.int(0)) }
921 return .op("exp", [a])
922 }
923
924 /// `calcFunc-ln` of a formula.
925 static func lnTerm(_ a: Term) throws -> Term {
926 if objectp(a) { throw Unsupported("symbolic arithmetic") }
927 if a == .variable("e") { return .number(.int(1)) }
928 if head(a) == "^", arg(a, 1) == .variable("e"), try knownReal(arg(a, 2)) { return arg(a, 2) }
929 if infinitep(a) != nil { return a == nan ? nan : inf }
930 return .op("ln", [a])
931 }
932
933 /// `math-mod` with a formula.
934 static func modTerm(_ a: Term, _ b: Term) throws -> Term {
935 if zerop(a) { return a }
936 if objectp(a), objectp(b) { throw Unsupported("symbolic arithmetic") }
937 if b == inf {
938 if posp(a) || zerop(a) { return a }
939 if negp(a) { return b }
940 }
941 return .op("%", [a, b])
942 }
943
944 // MARK: Display
945
946 /// `math-format-value`: `math-compose-expr` in the flat language.
947 static func format(_ t: Term, _ floatFormat: FloatFormat) throws -> String {
948 let text = try compose(t, 0, floatFormat)
949 // Past its width of 1000, `calc-eval` breaks the line.
950 guard text.count < 1000 else { throw Unsupported("symbolic arithmetic") }
951 return text
952 }
953
954 /// Left and right precedence, from `math-standard-ops` with
955 /// `calc-multiplication-has-precedence`.
956 static let operators: [String: (Int, Int)] = ["+": (180, 181), "-": (180, 181), "*": (196, 195), "/": (190, 191), "^": (201, 200),
957 "%": (190, 191), "eq": (160, 161), "neq": (160, 161), "lt": (160, 161),
958 "gt": (160, 161), "leq": (160, 161), "geq": (160, 161), "land": (110, 111),
959 "lor": (100, 101)]
960
961 static let symbols = ["eq": "=", "neq": "!=", "lt": "<", "gt": ">", "leq": "<=", "geq": ">=", "land": "&&", "lor": "||"]
962
963 static func compose(_ t: Term, _ prec: Int, _ floatFormat: FloatFormat, div: Bool = false) throws -> String {
964 switch t {
965 case .number(let v): return try Calc.format(v, floatFormat)
966 case .variable(let name): return name
967 case .op("neg", let args):
968 if prec > 197 { return "(" + (try compose(t, 0, floatFormat)) + ")" }
969 return "-" + (try compose(args[0], 197, floatFormat))
970 case .op("lnot", let args) where args.count == 1:
971 if prec > 1000 { return "(" + (try compose(t, 0, floatFormat)) + ")" }
972 return "!" + (try compose(args[0], 1000, floatFormat))
973 case .op("if", let args) where args.count == 3:
974 if prec > 90 { return "(" + (try compose(t, 0, floatFormat)) + ")" }
975 return try compose(args[0], 91, floatFormat) + " ? " + compose(args[1], 0, floatFormat) + " : "
976 + compose(args[2], 90, floatFormat)
977 case .op(let f, let args):
978 guard let (left, right) = operators[f], args.count == 2 else {
979 return f + "(" + (try args.map { try compose($0, 0, floatFormat) }).joined(separator: ", ") + ")"
980 }
981 if prec > min(left, right) || (div && f == "*") { return "(" + (try compose(t, 0, floatFormat)) + ")" }
982 var lhs = try compose(args[0], left, floatFormat)
983 let rhs = try compose(args[1], right, floatFormat, div: f == "/")
984 if f == "^", lhs.first == "-" { lhs = "(" + lhs + ")" }
985 if f == "*", let next = rhs.first {
986 var lastFactor = args[0]
987 while head(lastFactor) == "*" { lastFactor = arg(lastFactor, 2) }
988 let isVariable = if case .variable = lastFactor { true } else { false }
989 if (next.isASCII && (next.isLetter || next.isNumber)) || ".#_([{".contains(next), !(isVariable && next == "(") {
990 return lhs + " " + rhs
991 }
992 return lhs + "*" + rhs
993 }
994 if f == "^" { return lhs + "^" + rhs }
995 if f == "/", let x = number(args[0]), isWhole(x), case .number(.int) = args[1] { return lhs + "/" + rhs }
996 return lhs + " " + (symbols[f] ?? f) + " " + rhs
997 }
998 }
999 }
1000}