Commit e012e27afe

e012e27afeee8bf8b27b23e1379fb29e08ee4385

parent: 17afc0f1d0

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-21 19:07 UTC

Simplify Calc functions, comparisons and if on formulas

Layout: unified · split

Sources/OrgCore/Compute/Calc.swift +53 −8
@@ -1131,6 +1131,8 @@ public enum Calc {
1131 1131
1132 mutating func not() throws -> Node { 1132 mutating func not() throws -> Node {
1133 if peek() == "!", i + 1 >= chars.count || chars[i + 1] != "=" { 1133 if peek() == "!", i + 1 >= chars.count || chars[i + 1] != "=" {
1134 // Calc reads `!!` as one token.
1135 if i + 1 < chars.count, chars[i + 1] == "!" { throw Unsupported("formula syntax") }
1134 i += 1 1136 i += 1
1135 return .unary("!", try not()) 1137 return .unary("!", try not())
1136 } 1138 }
@@ -1418,19 +1420,31 @@ public enum Calc {
1418 switch node { 1420 switch node {
1419 case .number(let v): return v 1421 case .number(let v): return v
1420 case .vector(let items): return .vector(try items.map(eval)) 1422 case .vector(let items): return .vector(try items.map(eval))
1421 case .unary("!", let operand): return .int(try truth(try eval(operand)) ? 0 : 1) 1423 case .unary("!", let operand):
1424 let a = try eval(operand)
1425 if isSymbolic(a) || a == .nan { return value(try Symbolic.function("lnot", [try term(a)])) }
1426 return .int(try truth(a) ? 0 : 1)
1422 case .unary(_, let operand): 1427 case .unary(_, let operand):
1423 let a = try eval(operand) 1428 let a = try eval(operand)
1424 do { return try negate(a) } catch is Rejected { return .symbolic(.op("neg", [try term(a)])) } 1429 do { return try negate(a) } catch is Rejected { return .symbolic(.op("neg", [try term(a)])) }
1425 case .binary(let op, let l, let r): 1430 case .binary(let op, let l, let r):
1426 let (a, b) = (try eval(l), try eval(r)) 1431 let (a, b) = (try eval(l), try eval(r))
1432 if isSymbolic(a, b) || a == .nan || b == .nan, let name = Self.symbolicOperators[op] {
1433 return value(try Symbolic.function(name, [try term(a), try term(b)]))
1434 }
1427 do { 1435 do {
1428 return try binary(op, a, b) 1436 return try binary(op, a, b)
1429 } catch is Rejected { 1437 } catch is Rejected {
1430 // `math-normalize` keeps the operation, its arguments evaluated. 1438 // `math-normalize` keeps the operation, its arguments evaluated.
1431 guard let name = ["+": "+", "-": "-", "*": "*", "/": "/", "^": "^"][op] else { throw Unsupported("division by zero") } 1439 guard let name = ["+": "+", "-": "-", "*": "*", "/": "/", "^": "^", "%": "%"][op] else { throw Unsupported("division by zero") }
1432 return .symbolic(.op(name, [try term(a), try term(b)])) 1440 return .symbolic(.op(name, [try term(a), try term(b)]))
1433 } 1441 }
1442 case .call("if", let args) where args.count == 3:
1443 let c = try eval(args[0])
1444 // Calc keeps the branches of a formula's condition as written, and evaluates
1445 // only the branch a number's condition picks.
1446 if isSymbolic(c) || c == .nan { return .symbolic(.op("if", [try term(c), try literal(args[1]), try literal(args[2])])) }
1447 return try eval(try truth(c) ? args[1] : args[2])
1434 case .call(let name, let args): 1448 case .call(let name, let args):
1435 let values = try args.map(eval) 1449 let values = try args.map(eval)
1436 // In symbolic mode Calc keeps these unevaluated when the result isn't exact, 1450 // In symbolic mode Calc keeps these unevaluated when the result isn't exact,
@@ -1438,8 +1452,21 @@ public enum Calc {
1438 if modes.symbolic, Self.inexact.contains(name) || (!modes.degrees && ["sin", "cos", "tan"].contains(name)) { 1452 if modes.symbolic, Self.inexact.contains(name) || (!modes.degrees && ["sin", "cos", "tan"].contains(name)) {
1439 throw Unsupported("function \(name) in symbolic mode") 1453 throw Unsupported("function \(name) in symbolic mode")
1440 } 1454 }
1441 if values.contains(where: Self.hasSymbol) { 1455 // `nan` is a formula to these functions.
1456 if values.contains(where: Self.hasSymbol)
1457 || ((Symbolic.functions.contains(name) || name == "vmax" || name == "vmin") && values.contains(where: Self.hasNaN)) {
1442 // Calc leaves most functions of a formula alone, and simplifies some. 1458 // Calc leaves most functions of a formula alone, and simplifies some.
1459 let isVector = { (v: Value) in if case .vector = v { true } else { false } }
1460 if Symbolic.functions.contains(name), !values.contains(where: isVector) {
1461 return value(try Symbolic.function(name, try values.map(term)))
1462 }
1463 // `math-reduce-many-vecs`: `max` of the elements in turn.
1464 if name == "vmax" || name == "vmin", values.allSatisfy(isVector) {
1465 let items = try elements(values).map(term)
1466 return try extra(2) {
1467 value(try items.dropFirst().reduce(items[0]) { try Symbolic.function(name == "vmax" ? "max" : "min", [$0, $1]) })
1468 }
1469 }
1443 guard ["vsum", "vprod", "vmean", "vcount"].contains(name), 1470 guard ["vsum", "vprod", "vmean", "vcount"].contains(name),
1444 values.allSatisfy({ if case .vector = $0 { true } else { !Self.hasSymbol($0) } }) else { 1471 values.allSatisfy({ if case .vector = $0 { true } else { !Self.hasSymbol($0) } }) else {
1445 throw Unsupported("function \(name) of a formula") 1472 throw Unsupported("function \(name) of a formula")
@@ -1455,10 +1482,31 @@ public enum Calc {
1455 } 1482 }
1456 } 1483 }
1457 1484
1485 static let symbolicOperators: [Character: String] = ["=": "eq", "≠": "neq", "<": "lt", ">": "gt", "≤": "leq", "≥": "geq",
1486 "&": "land", "|": "lor", "%": "%"]
1487
1488 /// A branch of `if` as Calc reads it, unevaluated.
1489 func literal(_ node: Node) throws -> Term {
1490 switch node {
1491 case .number, .variable: return try term(try eval(node))
1492 case .unary("-", let a): return .op("neg", [try literal(a)])
1493 case .binary(let op, let a, let b) where "+-*/^".contains(op): return .op(String(op), [try literal(a), try literal(b)])
1494 default: throw Unsupported("condition")
1495 }
1496 }
1497
1458 static let inexact: Set<String> = ["sqrt", "exp", "ln", "log10", "log", "vsdev", "vpsdev", "vgmean", "vhmean", "vcorr", 1498 static let inexact: Set<String> = ["sqrt", "exp", "ln", "log10", "log", "vsdev", "vpsdev", "vgmean", "vhmean", "vcorr",
1459 "vcov", "vpcov", "agmean", "pow", "nroot", "hypot", "sinh", "cosh", "tanh", "arcsinh", 1499 "vcov", "vpcov", "agmean", "pow", "nroot", "hypot", "sinh", "cosh", "tanh", "arcsinh",
1460 "arccosh", "arctanh", "arcsin", "arccos", "arctan", "arctan2", "fact", "dfact"] 1500 "arccosh", "arctanh", "arcsin", "arccos", "arctan", "arctan2", "fact", "dfact"]
1461 1501
1502 static func hasNaN(_ v: Value) -> Bool {
1503 switch v {
1504 case .nan: true
1505 case .vector(let items): items.contains(where: hasNaN)
1506 default: false
1507 }
1508 }
1509
1462 static func hasSymbol(_ v: Value) -> Bool { 1510 static func hasSymbol(_ v: Value) -> Bool {
1463 switch v { 1511 switch v {
1464 case .symbolic: true 1512 case .symbolic: true
@@ -1505,8 +1553,8 @@ public enum Calc {
1505 1553
1506 /// `math-mod`: the remainder with the divisor's sign. 1554 /// `math-mod`: the remainder with the divisor's sign.
1507 func mod(_ a: Value, _ b: Value) throws -> Value { 1555 func mod(_ a: Value, _ b: Value) throws -> Value {
1508 if isZero(a) { return a } 1556 if isZero(a), (try? sign(b)) != nil { return a }
1509 if isZero(b) { throw Unsupported("division by zero") } 1557 if isZero(b), (try? sign(a)) != nil { throw Rejected() }
1510 // `math-imod` only for natural numbers; otherwise the quotient is a float without F. 1558 // `math-imod` only for natural numbers; otherwise the quotient is a float without F.
1511 if case .int(let x) = a, case .int(let y) = b, x >= 0, y > 0 { return .int(x % y) } 1559 if case .int(let x) = a, case .int(let y) = b, x >= 0, y > 0 { return .int(x % y) }
1512 let q = try floorOf(try divide(a, b, fractions: modes.preferFractions)) 1560 let q = try floorOf(try divide(a, b, fractions: modes.preferFractions))
@@ -1626,9 +1674,6 @@ public enum Calc {
1626 try items.sort { try compare($0, $1) < 0 } 1674 try items.sort { try compare($0, $1) < 0 }
1627 if items.count % 2 == 1 { return items[items.count / 2] } 1675 if items.count % 2 == 1 { return items[items.count / 2] }
1628 return try divide(try add(items[items.count / 2 - 1], items[items.count / 2]), .int(2), fractions: modes.preferFractions) 1676 return try divide(try add(items[items.count / 2 - 1], items[items.count / 2]), .int(2), fractions: modes.preferFractions)
1629 case "if":
1630 guard args.count == 3 else { throw Unsupported("arguments") }
1631 return try truth(args[0]) ? args[1] : args[2]
1632 case "vvar", "vpvar", "vsdev", "vpsdev": 1677 case "vvar", "vpvar", "vsdev", "vpsdev":
1633 let variance = try covariance(try elements(args), population: name == "vpvar" || name == "vpsdev") 1678 let variance = try covariance(try elements(args), population: name == "vpvar" || name == "vpsdev")
1634 return name.hasSuffix("sdev") ? try squareRoot(variance) : variance 1679 return name.hasSuffix("sdev") ? try squareRoot(variance) : variance
Sources/OrgCore/Compute/CalcSymbolic.swift +310 −16
@@ -3,7 +3,9 @@ import Foundation
3/// Calc's arithmetic on formulas it can't reduce to a number: variables, `inf`, `uinf`, and 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` 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 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 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
7/// those functions would decide from declarations, units, matrices or intervals throws 9/// those functions would decide from declarations, units, matrices or intervals throws
8/// `Calc.Unsupported`. 10/// `Calc.Unsupported`.
9extension Calc { 11extension Calc {
@@ -163,7 +165,7 @@ extension Calc {
163 return 7 165 return 7
164 } 166 }
165 if f == "neg" { return negSigns(try signs(a1, try origin.map(neg))) } 167 if f == "neg" { return negSigns(try signs(a1, try origin.map(neg))) }
166 let origin = origin.flatMap { zerop($0) ? nil : $0 } 168 var origin = origin.flatMap { zerop($0) ? nil : $0 }
167 let zero = Term.number(.int(0)) 169 let zero = Term.number(.int(0))
168 if f == "*" || (f == "/" && origin != nil), objectp(a1) { 170 if f == "*" || (f == "/" && origin != nil), objectp(a1) {
169 let s = f == "*" 171 let s = f == "*"
@@ -211,6 +213,32 @@ extension Calc {
211 case "i": return 8 213 case "i": return 8
212 default: return 15 214 default: return 15
213 } 215 }
216 case .op("%", let args):
217 let s2 = try signs(args[1])
218 sign = s2 >= 8 ? 7 : s2 == 2 ? 2 : [4, 6].contains(s2) ? 6 : [1, 3].contains(s2) ? 3 : 7
219 case .op("abs", let args):
220 let s1 = try signs(args[0])
221 sign = s1 == 2 ? 2 : [1, 4, 5].contains(s1) ? 4 : 6
222 case .op("exp", let args):
223 let s1 = try signs(args[0])
224 if s1 >= 8 {
225 sign = 15
226 } else if origin == nil || negp(origin!) {
227 sign = 4
228 } else {
229 origin = try sub(origin!, .number(.int(1)))
230 if zerop(origin!) { origin = nil }
231 sign = s1
232 }
233 case .op("ln", let args):
234 sign = try knownNonneg(args[0]) ? try signs(args[0], .number(.int(1))) : 15
235 case .op("sqrt", let args):
236 let s1 = try signs(args[0])
237 sign = [2, 4, 6].contains(s1) ? s1 : 15
238 case .op(let f, _) where ["eq", "neq", "lt", "gt", "leq", "geq", "lnot", "max", "min"].contains(f):
239 sign = 7
240 // Nothing is declared about the other functions.
241 case .op(let f, _) where functions.contains(f) || f == "if": return 15
214 default: throw Unsupported("function \(f ?? "")") 242 default: throw Unsupported("function \(f ?? "")")
215 } 243 }
216 guard let origin else { return sign } 244 guard let origin else { return sign }
@@ -220,6 +248,35 @@ extension Calc {
220 248
221 static func knownNonneg(_ t: Term) throws -> Bool { [2, 4, 6].contains(try signs(t)) } 249 static func knownNonneg(_ t: Term) throws -> Bool { [2, 4, 6].contains(try signs(t)) }
222 250
251 static func knownReal(_ t: Term) throws -> Bool { try signs(t) < 8 }
252
253 /// `math-known-evenp`.
254 static func knownEven(_ t: Term) throws -> Bool {
255 switch t {
256 case .number(.int(let n)): return n % 2 == 0
257 case .number(.float(let m, let e)) where e >= 0: return e > 0 || m % 2 == 0
258 case .op("*", let args):
259 if try knownEven(args[0]) { return try knownNumInteger(args[1]) }
260 return try knownNumInteger(args[0]) && knownEven(args[1])
261 case .op("+", let args), .op("-", let args):
262 return try (knownEven(args[0]) && knownEven(args[1])) || (knownOdd(args[0]) && knownOdd(args[1]))
263 case .op("neg", let args): return try knownEven(args[0])
264 default: return false
265 }
266 }
267
268 /// `math-known-oddp`.
269 static func knownOdd(_ t: Term) throws -> Bool {
270 switch t {
271 case .number(.int(let n)): return n % 2 != 0
272 case .number(.float(let m, let e)) where e >= 0: return e == 0 && m % 2 != 0
273 case .op("+", let args), .op("-", let args):
274 return try (knownEven(args[0]) && knownOdd(args[1])) || (knownOdd(args[0]) && knownEven(args[1]))
275 case .op("neg", let args): return try knownOdd(args[0])
276 default: return false
277 }
278 }
279
223 /// `math-known-num-integerp`. 280 /// `math-known-num-integerp`.
224 static func knownNumInteger(_ t: Term) throws -> Bool { 281 static func knownNumInteger(_ t: Term) throws -> Bool {
225 if let v = number(t) { return isWhole(v) } 282 if let v = number(t) { return isWhole(v) }
@@ -244,8 +301,18 @@ extension Calc {
244 case .number: throw Unsupported("symbolic arithmetic") 301 case .number: throw Unsupported("symbolic arithmetic")
245 case .variable: return 63 302 case .variable: return 63
246 case .op("neg", let args): return try possibleTypes(args[0]) 303 case .op("neg", let args): return try possibleTypes(args[0])
247 case .op(let f, let args) where args.count == 2 && ["+", "-", "*", "/", "^"].contains(f): 304 case .op("sqrt", let args):
248 let (t1, t2) = (try possibleTypes(args[0], num: num), try possibleTypes(args[1], num: num)) 305 let s1 = try signs(args[0])
306 let t = (s1 & 2 > 0 ? 3 : 0) | (s1 & 1 > 0 ? 16 : 0) | (s1 & 4 > 0 ? 15 : 0) | (s1 & 8 > 0 ? 32 : 0)
307 return t < 16 ? t : 63
308 case .op("abs", let args):
309 let t1 = try possibleTypes(args[0])
310 return t1 >= 16 ? 15 : t1
311 case .op(let f, let args) where args.count == 2 && ["+", "-", "*", "/", "^", "%"].contains(f):
312 // `%` keeps only the real bits, which the merged values above 15 don't give.
313 if f == "%", args.contains(where: { containsHead($0, "sqrt") }) { throw Unsupported("symbolic arithmetic") }
314 var (t1, t2) = (try possibleTypes(args[0], num: num), try possibleTypes(args[1], num: num))
315 if f == "%" { (t1, t2) = (t1 & 15, t2 & 15) }
249 let t12 = t1 | t2 316 let t12 = t1 | t2
250 if f == "^" { 317 if f == "^" {
251 guard t2 <= 3, try knownNonneg(args[1]), t1 < 16 else { 318 guard t2 <= 3, try knownNonneg(args[1]), t1 < 16 else {
@@ -260,12 +327,18 @@ extension Calc {
260 return t1 == 4 || t2 == 4 || fractions ? 5 : 15 327 return t1 == 4 || t2 == 4 || fractions ? 5 : 15
261 } 328 }
262 let mask = t12 <= 3 ? 1 329 let mask = t12 <= 3 ? 1
263 : ((t1 <= 3 && t2 & 3 == 0) || (t2 <= 3 && t1 & 3 == 0)) && f != "*" ? 4 : 5 330 : ((t1 <= 3 && t2 & 3 == 0) || (t2 <= 3 && t1 & 3 == 0)) && (f == "+" || f == "-") ? 4 : 5
264 return merge(t1, t2, mask) 331 return merge(t1, t2, mask)
332 case .op(let f, _) where functions.contains(f) || f == "if": return 63
265 default: throw Unsupported("function \(head(a) ?? "")") 333 default: throw Unsupported("function \(head(a) ?? "")")
266 } 334 }
267 } 335 }
268 336
337 static func containsHead(_ t: Term, _ f: String) -> Bool {
338 guard case .op(let g, let args) = t else { return false }
339 return g == f || args.contains { containsHead($0, f) }
340 }
341
269 // MARK: Arithmetic 342 // MARK: Arithmetic
270 343
271 /// `math-normalize`: the operations applied again from the leaves, floats rounded 344 /// `math-normalize`: the operations applied again from the leaves, floats rounded
@@ -274,6 +347,12 @@ extension Calc {
274 switch t { 347 switch t {
275 case .number(.float(let m, let e)): return .number(try makeFloat(Int128(m), e)) 348 case .number(.float(let m, let e)): return .number(try makeFloat(Int128(m), e))
276 case .number, .variable: return t 349 case .number, .variable: return t
350 // `math-normalize-logical-op`: the branches stay as written unless the condition
351 // is a number.
352 case .op("if", let args) where args.count == 3:
353 let c = try normalize(args[0])
354 guard let v = number(c) else { return .op("if", [c, args[1], args[2]]) }
355 return try normalize(isZero(v) ? args[2] : args[1])
277 case .op(let f, let args): 356 case .op(let f, let args):
278 let args = try args.map(normalize) 357 let args = try args.map(normalize)
279 do { return try apply(f, args) } catch is Rejected { return .op(f, args) } 358 do { return try apply(f, args) } catch is Rejected { return .op(f, args) }
@@ -288,7 +367,9 @@ extension Calc {
288 case ("/", 2): return try div(args[0], args[1]) 367 case ("/", 2): return try div(args[0], args[1])
289 case ("^", 2): return try pow(args[0], args[1]) 368 case ("^", 2): return try pow(args[0], args[1])
290 case ("neg", 1): return try neg(args[0]) 369 case ("neg", 1): return try neg(args[0])
291 default: throw Unsupported("function \(f)") 370 default:
371 guard functions.contains(f) else { throw Unsupported("function \(f)") }
372 return try function(f, args)
292 } 373 }
293 } 374 }
294 375
@@ -547,7 +628,9 @@ extension Calc {
547 func split(_ t: Term) throws -> (Term, Term) { 628 func split(_ t: Term) throws -> (Term, Term) {
548 var (base, power) = (t, Term.number(.int(1))) 629 var (base, power) = (t, Term.number(.int(1)))
549 if head(t) == "^", objectp(arg(t, 2)) { (base, power) = (arg(t, 1), arg(t, 2)) } 630 if head(t) == "^", objectp(arg(t, 2)) { (base, power) = (arg(t, 1), arg(t, 2)) }
550 if head(t) == "sqrt" || head(t) == "exp" { throw Unsupported("symbolic arithmetic") } 631 if head(t) == "sqrt" { (base, power) = (arg(t, 1), .number(.frac(1, 2))) }
632 // Only in symbolic mode does `exp` of a number stay.
633 if head(t) == "exp", objectp(arg(t, 1)) { throw Unsupported("symbolic arithmetic") }
551 if case .number(.frac(let n, let d)) = base, n < d { 634 if case .number(.frac(let n, let d)) = base, n < d {
552 (base, power) = (try div(.number(.int(1)), base), try neg(power)) 635 (base, power) = (try div(.number(.int(1)), base), try neg(power))
553 } 636 }
@@ -567,17 +650,22 @@ extension Calc {
567 if looksNeg(sum), ratp(baseA), posp(baseA) { 650 if looksNeg(sum), ratp(baseA), posp(baseA) {
568 (baseA, sum) = (try div(.number(.int(1)), baseA), try neg(sum)) 651 (baseA, sum) = (try div(.number(.int(1)), baseA), try neg(sum))
569 } 652 }
570 if sum == .number(.frac(1, 2)) || sum == .number(.frac(-1, 2)) { throw Unsupported("symbolic arithmetic") } 653 return try root(baseA, sum)
571 return try pow(baseA, sum)
572 } 654 }
573 } 655 }
574 if powA == powB, case .number(.int(let x)) = baseA, case .number(.int(let y)) = baseB, x >= 0, y >= 0 { 656 if powA == powB, case .number(.int(let x)) = baseA, case .number(.int(let y)) = baseB, x >= 0, y >= 0 {
575 if powA == .number(.frac(1, 2)) || powA == .number(.frac(-1, 2)) { throw Unsupported("symbolic arithmetic") } 657 return try root(try mul(baseA, baseB), powA)
576 return try pow(try mul(baseA, baseB), powA)
577 } 658 }
578 return nil 659 return nil
579 } 660 }
580 661
662 /// `a^p`, with Calc's square root form for a half.
663 static func root(_ a: Term, _ p: Term) throws -> Term {
664 if p == .number(.frac(1, 2)) { return .op("sqrt", [a]) }
665 if p == .number(.frac(-1, 2)) { return try div(.number(.int(1)), .op("sqrt", [a])) }
666 return try pow(a, p)
667 }
668
581 /// `math-pow`. 669 /// `math-pow`.
582 static func pow(_ a: Term, _ b: Term) throws -> Term { 670 static func pow(_ a: Term, _ b: Term) throws -> Term {
583 if b == nan { return b } 671 if b == nan { return b }
@@ -617,16 +705,19 @@ extension Calc {
617 return try mul(try pow(a1, b), try pow(try div(.number(.int(1)), a2), b)) 705 return try mul(try pow(a1, b), try pow(try div(.number(.int(1)), a2), b))
618 case "^" where try knownNumInteger(b) || knownNonneg(a1): 706 case "^" where try knownNumInteger(b) || knownNonneg(a1):
619 return try pow(a1, try mul(a2, b)) 707 return try pow(a1, try mul(a2, b))
708 case "sqrt" where try knownNumInteger(b) || knownNonneg(a1):
709 return try pow(a1, try div(b, .number(.int(2))))
620 case "^": 710 case "^":
621 // `math-known-evenp` of an exponent with a variable is false. 711 if let y = number(b), let q = quarter(y), (1...3).contains(q), try knownEven(a2), try knownReal(a1) {
622 if case .number(let n) = a2, isWhole(n), try trunc(n) % 2 == 0, let y = number(b), let q = quarter(y), 712 return try absTerm(try pow(a1, try mul(a2, b)))
623 (1...3).contains(q), try signs(a1) < 8 { throw Unsupported("symbolic arithmetic") } 713 }
624 default: break 714 default: break
625 } 715 }
626 if looksNeg(a), case .number(.int(let n)) = b { 716 if looksNeg(a), case .number(.int(let n)) = b {
627 let p = try pow(try neg(a), b) 717 let p = try pow(try neg(a), b)
628 return n % 2 == 0 ? p : try neg(p) 718 return n % 2 == 0 ? p : try neg(p)
629 } 719 }
720 if head(a) == "abs", try knownReal(a1), try knownEven(b) { return try pow(a1, b) }
630 if let infinity = infinitep(a) { 721 if let infinity = infinitep(a) {
631 if infinity == nan { return infinity } 722 if infinity == nan { return infinity }
632 if head(a) == "neg" { return try mul(try pow(.number(.int(-1)), b), try pow(a1, b)) } 723 if head(a) == "neg" { return try mul(try pow(.number(.int(-1)), b), try pow(a1, b)) }
@@ -647,6 +738,197 @@ extension Calc {
647 return .op("^", [a, b]) 738 return .op("^", [a, b])
648 } 739 }
649 740
741 // MARK: Functions
742
743 /// The functions `function` applies to formulas; `%` is `math-mod`.
744 static let functions: Set<String> = ["sqrt", "abs", "exp", "ln", "min", "max", "eq", "neq", "lt", "gt", "leq", "geq",
745 "land", "lor", "lnot", "%"]
746
747 /// `name` of `args`, at least one a formula, as `math-normalize` calls it: simplified,
748 /// or kept with its arguments when the function rejects them.
749 static func function(_ name: String, _ args: [Term]) throws -> Term {
750 do { return try simplify(name, args) } catch is Rejected { return .op(name, args) }
751 }
752
753 static func simplify(_ name: String, _ args: [Term]) throws -> Term {
754 let kept = Term.op(name, args)
755 switch (name, args.count) {
756 case ("sqrt", 1), ("exp", 1), ("ln", 1):
757 // In symbolic mode these keep a result that isn't exact, which isn't reproduced.
758 guard !symbolicMode else { throw Unsupported("function \(name) in symbolic mode") }
759 switch name {
760 case "sqrt": return try sqrtTerm(args[0])
761 case "exp": return try expTerm(args[0])
762 default: return try lnTerm(args[0])
763 }
764 case ("abs", 1): return try absTerm(args[0])
765 case ("min", _), ("max", _):
766 // `calcFunc-min` rejects an argument that isn't a real number or an infinity.
767 guard !args.isEmpty else { throw Unsupported("arguments") }
768 guard args.allSatisfy({ objectp($0) || infinitep($0) != nil }) else { return kept }
769 return try args.dropFirst().reduce(args[0]) { best, item in
770 switch try compareTerms(best, item) {
771 case 2: return nan
772 case let order: return order == (name == "max" ? -1 : 1) ? item : best
773 }
774 }
775 case ("eq", 2), ("neq", 2), ("lt", 2), ("gt", 2), ("leq", 2), ("geq", 2):
776 let (a, b) = (args[0], args[1])
777 let order = try compareTerms(a, b)
778 if order == 2 {
779 // Both sides negative, or zero, flip.
780 if looksNeg(a) || zerop(a), looksNeg(b) || zerop(b) {
781 return .op(flipped[name]!, [try neg(a), try neg(b)])
782 }
783 return kept
784 }
785 let holds = switch name {
786 case "eq": order == 0
787 case "neq": order != 0
788 case "lt": order == -1
789 case "gt": order == 1
790 case "leq": order != 1
791 default: order != -1
792 }
793 return .number(.int(holds ? 1 : 0))
794 case ("land", 2):
795 let (a, b) = (args[0], args[1])
796 if zerop(a) { return a }
797 if zerop(b) { return b }
798 if try isTrue(a) { return b }
799 if try isTrue(b) { return a }
800 return kept
801 case ("lor", 2):
802 let (a, b) = (args[0], args[1])
803 if zerop(a) { return b }
804 if zerop(b) { return a }
805 if try isTrue(a) { return a }
806 if try isTrue(b) { return b }
807 return kept
808 case ("lnot", 1):
809 let a = args[0]
810 if zerop(a) { return .number(.int(1)) }
811 if try isTrue(a) { return .number(.int(0)) }
812 if case .op(let f, let xs) = a, xs.count == 2, let opposite = negated[f] { return .op(opposite, xs) }
813 return kept
814 case ("%", 2): return try modTerm(args[0], args[1])
815 default: throw Unsupported("function \(name) of a formula")
816 }
817 }
818
819 /// The comparison with its sides negated, and its negation (`calc-tweak-eqn-table`).
820 static let flipped = ["eq": "eq", "neq": "neq", "lt": "gt", "gt": "lt", "leq": "geq", "geq": "leq"]
821 static let negated = ["eq": "neq", "neq": "eq", "lt": "geq", "gt": "leq", "leq": "gt", "geq": "lt"]
822
823 /// `math-is-true`.
824 static func isTrue(_ t: Term) throws -> Bool {
825 if let v = number(t) { return !isZero(v) }
826 return [1, 4, 5, 8, 9, 12, 13].contains(try signs(t))
827 }
828
829 /// `math-compare`: -1, 0 or 1, or 2 when the order isn't known.
830 static func compareTerms(_ a: Term, _ b: Term) throws -> Int {
831 if a == b {
832 switch a {
833 case .number: return 0
834 case .variable, .op("neg", _), .op("*", _), .op("/", _): return infinitep(a) != nil ? 2 : 0
835 default: return 0
836 }
837 }
838 if let x = number(a), let y = number(b) { return try Calc.compare(x, y) }
839 if case .number(.frac(let n, let d)) = a { return try compareTerms(.number(.int(n)), try mul(b, .number(.int(d)))) }
840 if case .number(.frac(let n, let d)) = b { return try compareTerms(try mul(a, .number(.int(d))), .number(.int(n))) }
841 let one = Term.number(.int(1)), minusOne = Term.number(.int(-1))
842 if let infA = infinitep(a) {
843 if a == uinf || a == nan { return 2 }
844 let dirA = try infiniteDirection(a, infA)
845 if let infB = infinitep(b) {
846 if b == uinf || b == nan { return 2 }
847 let dirB = try infiniteDirection(b, infB)
848 return dirA == one && dirB == minusOne ? 1 : dirA == minusOne && dirB == one ? -1 : 2
849 }
850 return dirA == one ? 1 : dirA == minusOne ? -1 : 2
851 }
852 if let infB = infinitep(b) {
853 if b == uinf || b == nan { return 2 }
854 let dirB = try infiniteDirection(b, infB)
855 return dirB == one ? -1 : dirB == minusOne ? 1 : 2
856 }
857 let e = Term.variable("e")
858 if head(a) == "exp", head(b) == "^", arg(b, 1) == e { return try compareTerms(arg(a, 1), arg(b, 2)) }
859 if head(b) == "exp", head(a) == "^", arg(a, 1) == e { return try compareTerms(arg(a, 2), arg(b, 1)) }
860 let half: [Term] = [.number(.frac(1, 2)), .number(.float(5, -1))]
861 if (head(a) == "sqrt" && head(b) == "^" && half.contains(arg(b, 2)))
862 || (head(b) == "sqrt" && head(a) == "^" && half.contains(arg(a, 2))) {
863 return try compareTerms(arg(a, 1), arg(b, 1))
864 }
865 if case .variable = a { return 2 }
866 if case .op(let f, let xs) = a, case .op(let g, let ys) = b, f == g, xs.count == ys.count,
867 try zip(xs, ys).allSatisfy({ try compareTerms($0, $1) == 0 }) { return 0 }
868 return 2
869 }
870
871 /// `math-sqrt` of a formula.
872 static func sqrtTerm(_ a: Term) throws -> Term {
873 if let v = number(a) { return .number(try squareRoot(v)) }
874 // An imaginary result.
875 if [1, 2, 3].contains(try signs(a)) { throw Unsupported("complex result") }
876 let (a1, a2) = (arg(a, 1), arg(a, 2))
877 switch head(a) {
878 case "*" where try knownNonneg(a1) || knownNonneg(a2):
879 return try mul(try sqrtTerm(a1), try sqrtTerm(a2))
880 case "/" where try knownNonneg(a2):
881 return try div(try sqrtTerm(a1), try sqrtTerm(a2))
882 case "/" where try knownNonneg(a1) && !equalInt(a1, 1):
883 return try mul(try sqrtTerm(a1), try sqrtTerm(try div(.number(.int(1)), a2)))
884 case "^" where try knownEven(a2) && knownReal(a1):
885 return try absTerm(try pow(a1, try div(a2, .number(.int(2)))))
886 default: break
887 }
888 if let infinity = infinitep(a) { return try mul(try sqrtTerm(try infiniteDirection(a, infinity)), infinity) }
889 return .op("sqrt", [a])
890 }
891
892 /// `math-abs` of a formula.
893 static func absTerm(_ a: Term) throws -> Term {
894 if let v = number(a) { return .number(try absolute(v)) }
895 if negp(a) { return try neg(a) }
896 if looksNeg(a) { return .op("abs", [try neg(a)]) }
897 let s = try signs(a)
898 if [2, 4, 6].contains(s) { return a }
899 if [1, 3].contains(s) { return try neg(a) }
900 if let infinity = infinitep(a) { return infinity == nan ? nan : inf }
901 return .op("abs", [a])
902 }
903
904 /// `calcFunc-exp` of a formula.
905 static func expTerm(_ a: Term) throws -> Term {
906 if objectp(a) { throw Unsupported("symbolic arithmetic") }
907 if a == inf || a == nan { return a }
908 if a == .op("neg", [inf]) { return .number(.int(0)) }
909 return .op("exp", [a])
910 }
911
912 /// `calcFunc-ln` of a formula.
913 static func lnTerm(_ a: Term) throws -> Term {
914 if objectp(a) { throw Unsupported("symbolic arithmetic") }
915 if a == .variable("e") { return .number(.int(1)) }
916 if head(a) == "^", arg(a, 1) == .variable("e"), try knownReal(arg(a, 2)) { return arg(a, 2) }
917 if infinitep(a) != nil { return a == nan ? nan : inf }
918 return .op("ln", [a])
919 }
920
921 /// `math-mod` with a formula.
922 static func modTerm(_ a: Term, _ b: Term) throws -> Term {
923 if zerop(a) { return a }
924 if objectp(a), objectp(b) { throw Unsupported("symbolic arithmetic") }
925 if b == inf {
926 if posp(a) || zerop(a) { return a }
927 if negp(a) { return b }
928 }
929 return .op("%", [a, b])
930 }
931
650 // MARK: Display 932 // MARK: Display
651 933
652 /// `math-format-value`: `math-compose-expr` in the flat language. 934 /// `math-format-value`: `math-compose-expr` in the flat language.
@@ -659,7 +941,12 @@ extension Calc {
659 941
660 /// Left and right precedence, from `math-standard-ops` with 942 /// Left and right precedence, from `math-standard-ops` with
661 /// `calc-multiplication-has-precedence`. 943 /// `calc-multiplication-has-precedence`.
662 static let operators: [String: (Int, Int)] = ["+": (180, 181), "-": (180, 181), "*": (196, 195), "/": (190, 191), "^": (201, 200)] 944 static let operators: [String: (Int, Int)] = ["+": (180, 181), "-": (180, 181), "*": (196, 195), "/": (190, 191), "^": (201, 200),
945 "%": (190, 191), "eq": (160, 161), "neq": (160, 161), "lt": (160, 161),
946 "gt": (160, 161), "leq": (160, 161), "geq": (160, 161), "land": (110, 111),
947 "lor": (100, 101)]
948
949 static let symbols = ["eq": "=", "neq": "!=", "lt": "<", "gt": ">", "leq": "<=", "geq": ">=", "land": "&&", "lor": "||"]
663 950
664 static func compose(_ t: Term, _ prec: Int, _ floatFormat: FloatFormat, div: Bool = false) throws -> String { 951 static func compose(_ t: Term, _ prec: Int, _ floatFormat: FloatFormat, div: Bool = false) throws -> String {
665 switch t { 952 switch t {
@@ -668,6 +955,13 @@ extension Calc {
668 case .op("neg", let args): 955 case .op("neg", let args):
669 if prec > 197 { return "(" + (try compose(t, 0, floatFormat)) + ")" } 956 if prec > 197 { return "(" + (try compose(t, 0, floatFormat)) + ")" }
670 return "-" + (try compose(args[0], 197, floatFormat)) 957 return "-" + (try compose(args[0], 197, floatFormat))
958 case .op("lnot", let args) where args.count == 1:
959 if prec > 1000 { return "(" + (try compose(t, 0, floatFormat)) + ")" }
960 return "!" + (try compose(args[0], 1000, floatFormat))
961 case .op("if", let args) where args.count == 3:
962 if prec > 90 { return "(" + (try compose(t, 0, floatFormat)) + ")" }
963 return try compose(args[0], 91, floatFormat) + " ? " + compose(args[1], 0, floatFormat) + " : "
964 + compose(args[2], 90, floatFormat)
671 case .op(let f, let args): 965 case .op(let f, let args):
672 guard let (left, right) = operators[f], args.count == 2 else { 966 guard let (left, right) = operators[f], args.count == 2 else {
673 return f + "(" + (try args.map { try compose($0, 0, floatFormat) }).joined(separator: ", ") + ")" 967 return f + "(" + (try args.map { try compose($0, 0, floatFormat) }).joined(separator: ", ") + ")"
@@ -687,7 +981,7 @@ extension Calc {
687 } 981 }
688 if f == "^" { return lhs + "^" + rhs } 982 if f == "^" { return lhs + "^" + rhs }
689 if f == "/", let x = number(args[0]), isWhole(x), case .number(.int) = args[1] { return lhs + "/" + rhs } 983 if f == "/", let x = number(args[0]), isWhole(x), case .number(.int) = args[1] { return lhs + "/" + rhs }
690 return lhs + " " + f + " " + rhs 984 return lhs + " " + (symbols[f] ?? f) + " " + rhs
691 } 985 }
692 } 986 }
693 } 987 }
Tests/OrgCoreTests/CalcTests.swift +55 −4
@@ -415,10 +415,61 @@ struct CalcTests {
415 #expect(skipped.count < cases.count / 4, "\(skipped.count) of \(cases.count) refused") 415 #expect(skipped.count < cases.count / 4, "\(skipped.count) of \(cases.count) refused")
416 } 416 }
417 417
418 /// Functions of formulas Calc simplifies, or keeps with their arguments.
419 static let symbolicFunctions = [
420 "sqrt(x)", "sqrt(4 x)", "sqrt(2 x)", "sqrt(x/4)", "sqrt(4/x)", "sqrt(x^2)", "sqrt((-x)^2)", "sqrt(inf)", "sqrt(uinf)",
421 "sqrt(x)^2", "sqrt(x)*sqrt(x)", "sqrt(x)/sqrt(x)", "x sqrt(x)", "2 sqrt(x)", "sqrt(x) + sqrt(x)", "abs(x)", "abs(-x)",
422 "abs(-2 x)", "abs(abs(x))", "abs(x)^2", "abs(x) abs(x)", "abs(-inf)", "abs(x) - abs(x)", "exp(x)", "exp(-x)",
423 "exp(inf)", "exp(-inf)", "exp(x) exp(x)", "exp(x)/exp(x)", "ln(x)", "ln(e)", "ln(e^2)", "ln(inf)", "ln(-inf)",
424 "min(x,1)", "max(x,1)", "max(1,x,2)", "max(inf,1)", "max(inf,inf)", "max(x inf, 1)", "2 max(x,1)", "-max(x,1)",
425 "x<1", "x==x", "x==y", "-x==-1", "0 < -x", "-x < -1", "x<=x", "x != x", "x != y", "1 + (x<1)", "eq(x,y)", "lt(x,1)",
426 "sqrt(x) == x^0.5", "exp(x) == e^x", "abs(x) < 0", "!x", "!(x<1)", "!(x+1)", "lnot(x>1)", "x && 1", "x || 0",
427 "x<1 && y", "x || y", "if(x,1,2)", "if(x, -3, 2.50)", "if(x, -y, 1:2)", "if(x<1,x,1)", "if(x,1,2)+1",
428 "if(inf,1,2)", "if(1,x,y)", "if(0,x,y)", "if(1,2,ln(0))", "x%2", "x%x", "(2 x)%2", "0%x", "x%0", "-1%inf",
429 "2%inf", "x%inf", "x % y % z", "(x % y) * 2", "-x % y", "vmax([x,1])", "vmin([x,1,2])", "vmax([1,2,x])",
430 "vmax([x,y],[1,2])", "vmax([x,1.23456789012345])", "vmin([inf,x])", "vmax([N/A,3,5])", "vmin([2,TBD,1])",
431 ]
432
433 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
434 func symbolicFunctionsMatchCalc() throws {
435 var cases = Self.symbolicFunctions.map { ($0, "(float 8)") }
436 for format in ["(fix 2)", "(sci 3)"] {
437 for e in ["sqrt(2 x)", "max(x, 2.5)", "if(x, 1.5, 2)", "x % 0.5", "vmin([x, 1:3, 0.25])"] { cases.append((e, format)) }
438 }
439 // Generated: the functions applied to formulas of a variable or two and numbers, and
440 // their results combined again. What is refused is left to Emacs.
441 var generator = SystemRandomNumberGenerator()
442 let leaves = ["x", "x", "y", "1", "2", "3", "0", "0.5", "2.5", "1:3", "-1", "-2", "4", "inf", "e", "a b", "-inf", "uinf", "nan", "0.", "1.5e3", "-x", "2 x", "pi"]
443 let unary = ["sqrt", "abs", "exp", "ln", "!"]
444 let binary = ["min", "max", "%", "<", ">", "<=", ">=", "==", "!=", "&&", "||", "+", "-", "*", "/", "^"]
445 func leaf() -> String { leaves.randomElement(using: &generator)! }
446 func expression(_ depth: Int) -> String {
447 if depth == 0 || Int.random(in: 0..<4, using: &generator) == 0 { return leaf() }
448 switch Int.random(in: 0..<10, using: &generator) {
449 case 0..<4:
450 let f = unary.randomElement(using: &generator)!
451 return f == "!" ? "!(\(expression(depth - 1)))" : "\(f)(\(expression(depth - 1)))"
452 case 4..<8:
453 let f = binary.randomElement(using: &generator)!
454 let (a, b) = (expression(depth - 1), f == "^" ? ["2", "3", "-1", "0.5", "x"].randomElement(using: &generator)! : expression(depth - 1))
455 return f.first!.isLetter ? "\(f)(\(a), \(b))" : "(\(a)) \(f) (\(b))"
456 case 8:
457 return "if(\(expression(depth - 1)), \(leaf()), \(leaf()))"
458 default:
459 let items = (0..<Int.random(in: 1...3, using: &generator)).map { _ in expression(depth - 1) }
460 return "\(["vmax", "vmin"].randomElement(using: &generator)!)([\(items.joined(separator: ", "))])"
461 }
462 }
463 for _ in 0..<4000 { cases.append((expression(4), "(float 8)")) }
464 let skipped = try Self.compare(cases)
465 #expect(Set(skipped).intersection(Self.symbolicFunctions) == [], "\(skipped)")
466 #expect(skipped.count < cases.count / 3, "\(skipped.count) of \(cases.count) refused")
467 }
468
418 @Test func unsupported() throws { 469 @Test func unsupported() throws {
419 for e in ["vsum([5 kg])", "vsum([1 2])", "vcount([N A])", "vsum([2 3 4])", "vsum([1 1/2])", "vmin([3 4])", 470 for e in ["vsum([5 kg])", "vsum([1 2])", "vcount([N A])", "vsum([2 3 4])", "vsum([1 1/2])", "vmin([3 4])",
420 "vcount([f (x)])", "vcount([1 [2]])", "vcount([(1) 2])", "vcount([1 sin (2)])", "1.2.3e5", 471 "vcount([f (x)])", "vcount([1 [2]])", "vcount([(1) 2])", "vcount([1 sin (2)])", "1.2.3e5",
421 "sqrt(x)", "vmax([x,1])", "vsum(x,1)", "x<1", "if(x,1,2)", "x%2", "x_1", "x'", "Holidays+1", "café+1", 472 "sqrt(-inf)", "vmax([x,1],2)", "!!x", "if(x,sqrt(4),1)", "eq(x,y,z)", "vsum(x,1)", "x_1", "x'", "Holidays+1", "café+1",
422 "x+<2026-10-05 Mon>", "[x,1]", "vcount([x -1])", "(1/0)+1", "vmean([])", "(-8)^(1/3)", "vvar([5])", "1<2<3", 473 "x+<2026-10-05 Mon>", "[x,1]", "vcount([x -1])", "(1/0)+1", "vmean([])", "(-8)^(1/3)", "vvar([5])", "1<2<3",
423 "vmax([])", "vmin([])", "vrms([1,2])", "vmeane([1,2])", "vcov([1,2],[3])", "vcov([1],[2])", 474 "vmax([])", "vmin([])", "vrms([1,2])", "vmeane([1,2])", "vcov([1,2],[3])", "vcov([1],[2])",
424 "fdiv(7.5,2)", "fdiv(7,0)", "perm(5,6)", "log(8,1)", "log(0,2)", "log(-8,2)", "arctanh(1)", "arccosh(0.5)", 475 "fdiv(7.5,2)", "fdiv(7,0)", "perm(5,6)", "log(8,1)", "log(0,2)", "log(-8,2)", "arctanh(1)", "arccosh(0.5)",
@@ -458,7 +509,7 @@ struct CalcTests {
458 for e in ["x^2/x", "x*x/x", "inf+(1/0)", "x/2", "abs(x)", "x%2", "x*x", "x x", "x*y*x"] { 509 for e in ["x^2/x", "x*x/x", "inf+(1/0)", "x/2", "abs(x)", "x%2", "x*x", "x x", "x*y*x"] {
459 #expect(throws: Calc.Unsupported.self, "\(e)") { try Calc.evaluate(e, numeric: true) } 510 #expect(throws: Calc.Unsupported.self, "\(e)") { try Calc.evaluate(e, numeric: true) }
460 } 511 }
461 for e in ["-x", "x*2", "2 x", "x*y", "x+x", "x+2-2", "nan"] { 512 for e in ["-x", "x*2", "2 x", "x*y", "x+x", "x+2-2", "nan", "x<1", "x && 1", "!x"] {
462 #expect(throws: Calc.Failure("Number expected"), "\(e)") { try Calc.evaluate(e, numeric: true) } 513 #expect(throws: Calc.Failure("Number expected"), "\(e)") { try Calc.evaluate(e, numeric: true) }
463 } 514 }
464 #expect(try Calc.evaluate("x/x", numeric: true) == "1") 515 #expect(try Calc.evaluate("x/x", numeric: true) == "1")
@@ -469,7 +520,7 @@ struct CalcTests {
469 } 520 }
470 var symbolic = Calc.Modes() 521 var symbolic = Calc.Modes()
471 symbolic.symbolic = true 522 symbolic.symbolic = true
472 for e in ["sqrt(2)", "2^0.5", "ln(2)", "x^0.5"] { 523 for e in ["sqrt(2)", "2^0.5", "ln(2)", "x^0.5", "sqrt(x)", "exp(x)"] {
473 #expect(throws: Calc.Unsupported.self, "\(e)") { try Calc.evaluate(e, modes: symbolic) } 524 #expect(throws: Calc.Unsupported.self, "\(e)") { try Calc.evaluate(e, modes: symbolic) }
474 } 525 }
475 } 526 }
@@ -477,7 +528,7 @@ struct CalcTests {
477 /// `;S`: what is computed matches; functions and powers that may not be exact are refused. 528 /// `;S`: what is computed matches; functions and powers that may not be exact are refused.
478 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) 529 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
479 func symbolicModeMatchesCalc() throws { 530 func symbolicModeMatchesCalc() throws {
480 let cases = (Self.fixed + Self.functions + Self.symbolic).map { ($0, "(float 8)") } 531 let cases = (Self.fixed + Self.functions + Self.symbolic + Self.symbolicFunctions).map { ($0, "(float 8)") }
481 let skipped = try Self.compare(cases, symbolic: true) 532 let skipped = try Self.compare(cases, symbolic: true)
482 #expect(Set(skipped).isDisjoint(with: ["1/3", "x+5", "1/0", "2 pi", "vmean([x,2,3])", "sin(30)", "x^2", "round(2.5)"])) 533 #expect(Set(skipped).isDisjoint(with: ["1/3", "x+5", "1/0", "2 pi", "vmean([x,2,3])", "sin(30)", "x^2", "round(2.5)"]))
483 #expect(skipped.count < cases.count / 3, "\(skipped.count) of \(cases.count) refused") 534 #expect(skipped.count < cases.count / 3, "\(skipped.count) of \(cases.count) refused")
Tests/OrgCoreTests/TableFormulaEntryTests.swift +4 −4
@@ -94,12 +94,12 @@ extension TableFormulaEntryTests {
94 #expect(removed.text == "| a | b |\n|---+---|\n| 1 | 2 |\n#+TBLFM: \n" && removed.message == "Formula removed", "\(removed)") 94 #expect(removed.text == "| a | b |\n|---+---|\n| 1 | 2 |\n#+TBLFM: \n" && removed.message == "Formula removed", "\(removed)")
95 // A function of a field holding text needs Emacs: the formula is stored and TAB 95 // A function of a field holding text needs Emacs: the formula is stored and TAB
96 // still moves on. 96 // still moves on.
97 let symbolic = "| a | b |\n| x | =sqrt($1) |\n| y | |\n" 97 let symbolic = "| a | b |\n| x | =floor($1) |\n| y | |\n"
98 let tab = try #require(committed(TableCommand(.nextField), symbolic, after: "($1)")) 98 let tab = try #require(committed(TableCommand(.nextField), symbolic, after: "($1)"))
99 #expect(tab.text == "| a | b |\n| x | =sqrt($1) |\n| y | |\n#+TBLFM: $2=sqrt($1)\n", "\(tab.text.debugDescription)") 99 #expect(tab.text == "| a | b |\n| x | =floor($1) |\n| y | |\n#+TBLFM: $2=floor($1)\n", "\(tab.text.debugDescription)")
100 #expect(tab.caret == (tab.text as NSString).range(of: "| y").location + 2) 100 #expect(tab.caret == (tab.text as NSString).range(of: "| y").location + 2)
101 #expect(tab.message?.hasPrefix("The formula was stored; recalculating it needs Emacs") == true) 101 #expect(tab.message?.hasPrefix("The formula was stored; recalculating it needs Emacs") == true)
102 let prompted = try #require(committed(TableEvalFormula(named: false), symbolic, after: "| x", answers: ["formula": "sqrt($1)"])) 102 let prompted = try #require(committed(TableEvalFormula(named: false), symbolic, after: "| x", answers: ["formula": "floor($1)"]))
103 #expect(prompted.text.hasSuffix("#+TBLFM: $1=sqrt($1)\n") && prompted.message != nil, "\(prompted)") 103 #expect(prompted.text.hasSuffix("#+TBLFM: $1=floor($1)\n") && prompted.message != nil, "\(prompted)")
104 } 104 }
105} 105}
Tests/OrgCoreTests/TableFormulaTests.swift +5
@@ -97,6 +97,11 @@ struct TableFormulaTests {
97 "| r | area | half |\n|---+------+------|\n| 3 | | |\n| x | | |\n#+TBLFM: $2=$1^2*pi::$3=$2/2;S\n", 97 "| r | area | half |\n|---+------+------|\n| 3 | | |\n| x | | |\n#+TBLFM: $2=$1^2*pi::$3=$2/2;S\n",
98 "| a | b | c | d |\n|---+---+---+---|\n| 1 | | n/a | |\n| 2 | 3 | | |\n#+TBLFM: $4=vsum($1..$3)::@2$2=$1 + inf;S\n", 98 "| a | b | c | d |\n|---+---+---+---|\n| 1 | | n/a | |\n| 2 | 3 | | |\n#+TBLFM: $4=vsum($1..$3)::@2$2=$1 + inf;S\n",
99 "| a | b | c |\n|---+---+---|\n| x | 1 | |\n| | 2 | |\n#+TBLFM: $3=$1*$2;E\n", 99 "| a | b | c |\n|---+---+---|\n| x | 1 | |\n| | 2 | |\n#+TBLFM: $3=$1*$2;E\n",
100 // Functions of text fields.
101 "| name | q1 | q2 | q3 | best | worst |\n|------+----+----+----+------+-------|\n| ann | 5 | 7 | 6 | | |\n| bob | 4 | absent | 8 | | |\n| cy | | 2.5 | 1 | | |\n#+TBLFM: $5=vmax($2..$4)::$6=vmin($2..$4)\n",
102 "| item | qty | status | flag |\n|------+-----+--------+------|\n| a | 12 | | |\n| b | n/a | | |\n| c | 3 | | |\n| d | TBD | | |\n#+TBLFM: $3=if($2 > 10, 1, 0)::$4=$2 >= 3 && $2 != 12\n",
103 "| x | abs | root | low | mod |\n|---+-----+------+-----+-----|\n| -4 | | | | |\n| TBD | | | | |\n| 9 | | | | |\n#+TBLFM: $2=abs($1)::$3=sqrt(abs($1))::$4=min($1, 5)::$5=$1 % 4\n",
104 "| a | b | same | e | ln |\n|---+---+------+---+----|\n| N/A | N/A | | | |\n| 1 | 2 | | | |\n| x | y | | | |\n#+TBLFM: $3=$1 == $2::$4=exp($1)::$5=ln($2)\n",
100 // Calc rejects a number with two points. 105 // Calc rejects a number with two points.
101 "| a | b |\n|---+---|\n| 21.11.2026 | |\n| 192.168.1.1 | |\n| 1.5 | |\n#+TBLFM: $2=$1+1\n", 106 "| a | b |\n|---+---|\n| 21.11.2026 | |\n| 192.168.1.1 | |\n| 1.5 | |\n#+TBLFM: $2=$1+1\n",
102 "| a | b |\n|---+---|\n| 21.11.2026 | |\n#+TBLFM: $2=$1+1;T\n", 107 "| a | b |\n|---+---|\n| 21.11.2026 | |\n#+TBLFM: $2=$1+1;T\n",
Tests/OrgProgramsTests/ProgramsTests.swift +4 −4
@@ -23,7 +23,7 @@ struct EmacsFallbackTests {
23 @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) 23 @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
24 func recalculatesTablesNativeCodeCannot() async throws { 24 func recalculatesTablesNativeCodeCannot() async throws {
25 let notes = try Folder() 25 let notes = try Folder()
26 let file = try notes.write("t.org", "* Prices\n| item | n | twice |\n|------+---+-------|\n| x | a | |\n| y | 2 | |\n#+TBLFM: $3=sqrt($2)\n") 26 let file = try notes.write("t.org", "* Prices\n| item | n | twice |\n|------+---+-------|\n| x | a | |\n| y | 2 | |\n#+TBLFM: $3=floor($2)\n")
27 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r"))) 27 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
28 session.open(file.path) 28 session.open(file.path)
29 let step = session.perform(TableRecalculate(all: true), path: file.path, at: 50, expect: nil) 29 let step = session.perform(TableRecalculate(all: true), path: file.path, at: 50, expect: nil)
@@ -31,11 +31,11 @@ struct EmacsFallbackTests {
31 Issue.record("\(step)") 31 Issue.record("\(step)")
32 return 32 return
33 } 33 }
34 #expect(reason == "function sqrt of a formula") 34 #expect(reason == "function floor of a formula")
35 #expect(!lisp) 35 #expect(!lisp)
36 let message = await session.recalculateInEmacs(table: table, point: point, form: form) 36 let message = await session.recalculateInEmacs(table: table, point: point, form: form)
37 #expect(message == "Recalculated in Emacs") 37 #expect(message == "Recalculated in Emacs")
38 #expect(session.document?.text == "* Prices\n| item | n | twice |\n|------+---+-----------|\n| x | a | sqrt(a) |\n| y | 2 | 1.4142136 |\n#+TBLFM: $3=sqrt($2)\n") 38 #expect(session.document?.text == "* Prices\n| item | n | twice |\n|------+---+----------|\n| x | a | floor(a) |\n| y | 2 | 2 |\n#+TBLFM: $3=floor($2)\n")
39 } 39 }
40 40
41 /// `elisp:` links run in Emacs, in a copy of the file with point at the caret; in 41 /// `elisp:` links run in Emacs, in a copy of the file with point at the caret; in
@@ -96,7 +96,7 @@ struct EmacsFallbackTests {
96 @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) 96 @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
97 func cancelingARecalculationLeavesTheTable() async throws { 97 func cancelingARecalculationLeavesTheTable() async throws {
98 let notes = try Folder() 98 let notes = try Folder()
99 let text = "| n | twice |\n|---+-------|\n| a | |\n#+TBLFM: $2=sqrt($1)\n" 99 let text = "| n | twice |\n|---+-------|\n| a | |\n#+TBLFM: $2=floor($1)\n"
100 let file = try notes.write("t.org", text) 100 let file = try notes.write("t.org", text)
101 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r"))) 101 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
102 session.open(file.path) 102 session.open(file.path)
docs/manual/guide/10-tables.org +9 −3
@@ -388,9 +388,15 @@ sums, differences, products, quotients and powers:
388- =inf=, =-inf= and =uinf= (infinity of unknown sign) follow Calc's rules: =inf - inf= is 388- =inf=, =-inf= and =uinf= (infinity of unknown sign) follow Calc's rules: =inf - inf= is
389 =nan=, =1/inf= is =0=, =2^inf= is =inf=. 389 =nan=, =1/inf= is =0=, =2^inf= is =inf=.
390- =vsum=, =vprod=, =vmean= and =vcount= take vectors holding such formulas. 390- =vsum=, =vprod=, =vmean= and =vcount= take vectors holding such formulas.
391 391- =sqrt=, =abs=, =exp=, =ln=, =min=, =max=, =vmax=, =vmin= and =%= simplify a formula
392Other functions of a formula, comparisons and conditions on one, and complex results 392 as Calc does, or keep it: =abs(-x)= is =abs(x)=, =sqrt(4 x)= is =2 sqrt(x)=,
393need Emacs. 393 =vmax($2..$4)= over 4, =absent= and 8 is =max(max(4, absent), 8)=, and =x % 3= stays.
394- Comparisons, =&&=, =||=, =!= and =if= on a formula give a formula unless Calc can
395 decide them: =x == x= is 1, =$2 > 10= with =TBD= in =$2= is =TBD > 10=, and
396 =if($2 > 10, 1, 0)= is =TBD > 10 ? 1 : 0=.
397
398Other functions of a formula, =sqrt=, =exp= and =ln= of one under the =S= flag, and
399complex results such as =sqrt(-inf)= need Emacs.
394 400
395** Mode flags and formats 401** Mode flags and formats
396 402