Sources/OrgCore/Compute/Calc.swift
813 lines · 33699 bytes
1import Foundation
2
3/// The part of Emacs Calc that table formulas use, with Calc's number semantics: exact
4/// integers, decimal floats rounded to `calc-internal-prec` digits after every operation, and
5/// Calc's display formats. Anything outside this domain throws `Calc.Unsupported`, and the
6/// caller hands the work to Emacs.
7public enum Calc {
8 public struct Unsupported: Error, Equatable, CustomStringConvertible {
9 public let reason: String
10 public var description: String { reason }
11 init(_ reason: String) { self.reason = reason }
12 }
13
14 /// An error Calc reports, which a table shows as `#ERROR`.
15 public struct Failure: Error, Equatable, CustomStringConvertible {
16 public let reason: String
17 public var description: String { reason }
18 init(_ reason: String) { self.reason = reason }
19 }
20
21 public indirect enum Value: Equatable, Sendable {
22 case int(Int)
23 /// Mantissa and exponent, normalized: at most `precision` digits, no trailing zeros.
24 case float(Int, Int)
25 case vector([Value])
26 /// A date form: the day number, with the time of day as a fraction.
27 case date(Value)
28 case nan
29 }
30
31 public enum FloatFormat: Equatable, Sendable {
32 case float(Int), fix(Int), sci(Int), eng(Int)
33 }
34
35 public struct Modes: Equatable, Sendable {
36 public var precision = 12
37 public var format = FloatFormat.float(8)
38 public var degrees = true
39 public init() {}
40 }
41
42 /// `calc-eval` of `expression`, as the string Calc would return; with `numeric`, as
43 /// `calc-eval` with `num`, a result that isn't a number is an error.
44 public static func evaluate(_ expression: String, modes: Modes = Modes(), numeric: Bool = false) throws -> String {
45 guard modes.precision == 12 else { throw Unsupported("calc precision") }
46 var parser = Parser(expression)
47 let tree = try parser.parse()
48 let value = try Evaluator(modes: modes).eval(tree)
49 if numeric {
50 switch value {
51 case .int, .float: break
52 default: throw Failure("Number expected")
53 }
54 }
55 return try format(value, modes.format)
56 }
57
58 // MARK: - Numbers
59
60 static let precision = 12
61
62 static func digits(_ x: Int128) -> Int {
63 var n = x.magnitude
64 var count = 1
65 while n >= 10 {
66 n /= 10
67 count += 1
68 }
69 return count
70 }
71
72 static func power10(_ n: Int) throws -> Int128 {
73 guard n >= 0, n <= 37 else { throw Unsupported("number size") }
74 var result: Int128 = 1
75 for _ in 0..<n { result *= 10 }
76 return result
77 }
78
79 /// `math-scale-rounding`: `x` times 10^n, rounding half away from zero when n < 0.
80 static func scaleRounding(_ x: Int128, _ n: Int) throws -> Int128 {
81 if n >= 0 {
82 let (result, overflow) = x.multipliedReportingOverflow(by: try power10(n))
83 if overflow { throw Unsupported("number size") }
84 return result
85 }
86 if x < 0 { return -(try scaleRounding(-x, n)) }
87 if -n > 38 { return 0 }
88 let truncated = -n - 1 > 37 ? 0 : x / (try power10(-n - 1))
89 return (truncated + 5) / 10
90 }
91
92 /// `math-make-float`.
93 static func makeFloat(_ mantissa: Int128, _ exponent: Int) throws -> Value {
94 var m = mantissa
95 var e = exponent
96 if m == 0 { return .float(0, 0) }
97 let excess = digits(m) - precision
98 if excess > 0 {
99 m = try scaleRounding(m, -excess)
100 e += excess
101 }
102 if m == 0 { return .float(0, 0) }
103 while m % 10 == 0 {
104 m /= 10
105 e += 1
106 }
107 return .float(Int(m), e)
108 }
109
110 static func parts(_ v: Value) throws -> (Int128, Int) {
111 switch v {
112 case .int(let i): return (Int128(i), 0)
113 case .float(let m, let e): return (Int128(m), e)
114 case .vector: throw Unsupported("vector arithmetic")
115 case .date, .nan: throw Unsupported("date arithmetic")
116 }
117 }
118
119 static func double(_ v: Value) throws -> Double {
120 switch v {
121 case .int(let i): return Double(i)
122 case .float(let m, let e): return Double(m) * pow(10, Double(e))
123 case .vector: throw Unsupported("vector arithmetic")
124 case .date, .nan: throw Unsupported("date arithmetic")
125 }
126 }
127
128 static func fromDouble(_ d: Double) throws -> Value {
129 guard d.isFinite else { throw Unsupported("infinite result") }
130 if d == 0 { return .float(0, 0) }
131 // Seventeen significant digits are exact for a Double; rounding to 12 follows.
132 let text = String(format: "%.16e", d)
133 let pieces = text.split(separator: "e")
134 let digitsText = pieces[0].replacingOccurrences(of: ".", with: "")
135 guard let mantissa = Int128(digitsText), let exponent = Int(pieces[1]) else { throw Unsupported("number") }
136 return try makeFloat(mantissa, exponent - 16)
137 }
138
139 static func add(_ a: Value, _ b: Value) throws -> Value {
140 switch (a, b) {
141 case (.nan, .vector), (.vector, .nan): throw Unsupported("vector arithmetic")
142 case (.nan, _), (_, .nan): return .nan
143 case (.date, .date): throw Unsupported("date arithmetic")
144 case (.date(let d), _): return .date(try add(d, b))
145 case (_, .date(let d)): return .date(try add(a, d))
146 default: break
147 }
148 if case .int(let x) = a, case .int(let y) = b {
149 let (sum, overflow) = x.addingReportingOverflow(y)
150 if overflow { throw Unsupported("integer size") }
151 return .int(sum)
152 }
153 let (m1, e1) = try parts(a)
154 let (m2, e2) = try parts(b)
155 if m1 == 0 { return try makeFloat(m2, e2) }
156 if m2 == 0 { return try makeFloat(m1, e1) }
157 let ediff = e1 - e2
158 if ediff >= 0 {
159 if ediff >= 2 * precision { return try makeFloat(m1, e1) }
160 return try makeFloat(try scaleRounding(m1, ediff) + m2, e2)
161 }
162 if -ediff >= 2 * precision { return try makeFloat(m2, e2) }
163 return try makeFloat(m1 + (try scaleRounding(m2, -ediff)), e1)
164 }
165
166 static func negate(_ a: Value) throws -> Value {
167 switch a {
168 case .int(let i):
169 guard i != .min else { throw Unsupported("integer size") }
170 return .int(-i)
171 case .float(let m, let e): return .float(-m, e)
172 case .vector: throw Unsupported("vector arithmetic")
173 case .date: throw Unsupported("date arithmetic")
174 case .nan: return .nan
175 }
176 }
177
178 /// `a - b`: a date less a date is the days between them.
179 static func subtract(_ a: Value, _ b: Value) throws -> Value {
180 if case .date(let x) = a, case .date(let y) = b { return try add(x, try negate(y)) }
181 if case .date(let x) = a, b != .nan { return .date(try add(x, try negate(b))) }
182 return try add(a, try negate(b))
183 }
184
185 static func isNaN(_ a: Value, _ b: Value) -> Bool {
186 if case .vector = a { return false }
187 if case .vector = b { return false }
188 return a == .nan || b == .nan
189 }
190
191 static func multiply(_ a: Value, _ b: Value) throws -> Value {
192 if isNaN(a, b) { return .nan }
193 if case .int(let x) = a, case .int(let y) = b {
194 let (product, overflow) = x.multipliedReportingOverflow(by: y)
195 if overflow { throw Unsupported("integer size") }
196 return .int(product)
197 }
198 let (m1, e1) = try parts(a)
199 let (m2, e2) = try parts(b)
200 let (product, overflow) = m1.multipliedReportingOverflow(by: m2)
201 if overflow { throw Unsupported("number size") }
202 return try makeFloat(product, e1 + e2)
203 }
204
205 static func divide(_ a: Value, _ b: Value) throws -> Value {
206 if isNaN(a, b) { return .nan }
207 if case .int(let x) = a, case .int(let y) = b {
208 guard y != 0 else { throw Unsupported("division by zero") }
209 if x % y == 0 { return .int(x / y) }
210 }
211 let (m1, e1) = try parts(a)
212 let (m2, e2) = try parts(b)
213 guard m2 != 0 else { throw Unsupported("division by zero") }
214 // `math-div-float`: scale so the truncated quotient has one digit more than needed.
215 let ldiff = max(precision + 1 - (digits(m1) - digits(m2)), 0)
216 let quotient = (try scaleRounding(m1, ldiff)) / m2
217 return try makeFloat(quotient, e1 - ldiff - e2)
218 }
219
220 static func isInteger(_ v: Value) -> Bool {
221 if case .int = v { return true }
222 return false
223 }
224
225 /// `math-ipow`.
226 static func integerPower(_ a: Value, _ n: Int) throws -> Value {
227 if n < 0 { return try integerPower(try divide(.int(1), a), -n) }
228 if n == 0 { return .int(1) }
229 if n == 1 { return a }
230 let square = try multiply(a, a)
231 if n % 2 == 0 { return try integerPower(square, n / 2) }
232 return try multiply(a, try integerPower(square, n / 2))
233 }
234
235 static func power(_ a: Value, _ b: Value) throws -> Value {
236 if isNaN(a, b) { return .nan }
237 if case .int(let n) = b { return try integerPower(a, n) }
238 let base = try double(a)
239 guard base >= 0 else { throw Unsupported("complex result") }
240 return try fromDouble(pow(base, try double(b)))
241 }
242
243 static func compare(_ a: Value, _ b: Value) throws -> Int {
244 if case .date(let x) = a, case .date(let y) = b { return try compare(x, y) }
245 if a == .nan || b == .nan { throw Unsupported("comparison with nan") }
246 let difference = try add(a, try negate(b))
247 let (m, _) = try parts(difference)
248 return m == 0 ? 0 : (m < 0 ? -1 : 1)
249 }
250
251 // MARK: - Display
252
253 /// `math-format-number`.
254 static func format(_ value: Value, _ floatFormat: FloatFormat) throws -> String {
255 switch value {
256 case .int(let i): return String(i)
257 case .vector: throw Unsupported("vector result")
258 case .nan: return "nan"
259 case .date(let d): return "<" + (try formatDate(d)) + ">"
260 case .float(let m, _) where m < 0:
261 guard case .float(let m, let e) = value else { fatalError() }
262 return "-" + (try format(.float(-m, e), floatFormat))
263 case .float(let m, var exp):
264 var mant = Int128(m)
265 var figs: Int
266 let kind: String
267 switch floatFormat {
268 case .float(let n): (figs, kind) = (n, "float")
269 case .fix(let n): (figs, kind) = (n, "fix")
270 case .sci(let n): (figs, kind) = (n, "sci")
271 case .eng(let n): (figs, kind) = (n, "eng")
272 }
273 if kind == "fix", figs < 0 || exp + digits(mant) > -figs {
274 if figs < 0 { figs = -figs }
275 mant = try scaleRounding(mant, exp + figs)
276 var str = String(mant)
277 if str.count <= figs { str = String(repeating: "0", count: figs + 1 - str.count) + str }
278 if figs > 0 {
279 return String(str.dropLast(figs)) + "." + String(str.suffix(figs))
280 }
281 return str + "."
282 }
283 if figs < 0 { figs += precision }
284 if figs > 0 {
285 let adj = figs - digits(mant)
286 if adj < 0 {
287 mant = try scaleRounding(mant, adj)
288 exp -= adj
289 }
290 }
291 var str = String(mant)
292 let len = str.count
293 let dpos = exp + len
294 // `calc-display-sci-high` 0, `calc-display-sci-low` -3.
295 if kind == "float", dpos <= precision, dpos >= -1 {
296 if dpos == 0 {
297 str = "0." + str
298 } else if exp <= 0, dpos > 0 {
299 str = String(str.prefix(dpos)) + "." + String(str.dropFirst(dpos))
300 } else if exp > 0 {
301 str += String(repeating: "0", count: exp) + "."
302 } else {
303 str = "0." + String(repeating: "0", count: -dpos) + str
304 }
305 return str
306 }
307 let eadj = exp + len
308 let scale = kind == "eng" ? 1 + ((eadj + 300002) % 3) : 1
309 if scale > str.count { str += String(repeating: "0", count: scale - str.count) }
310 if scale < str.count { str = String(str.prefix(scale)) + "." + String(str.dropFirst(scale)) }
311 return str + "e" + String(eadj - scale)
312 }
313 }
314
315 static let weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
316
317 /// `calc-date-format` as Org sets it: `YYYY-MM-DD Www`, then ` hh:mm` for a time of day.
318 static func formatDate(_ value: Value) throws -> String {
319 let days = try double(value)
320 let day = Int(days.rounded(.down))
321 let date = Days.date(day)
322 var text = String(format: "%04d-%02d-%02d ", date.year, date.month, date.day) + weekdays[Days.weekday(day)]
323 if case .float = value, days != Double(day) {
324 let seconds = Int(((days - Double(day)) * 86400).rounded())
325 text += String(format: " %02d:%02d", seconds / 3600, seconds / 60 % 60)
326 }
327 return text
328 }
329
330 /// A date form `<YYYY-MM-DD Www>` or `<YYYY-MM-DD Www hh:mm>`, from the text between
331 /// the brackets.
332 static func parseDate(_ text: String) throws -> Value {
333 guard let m = text.firstMatch(of: /^([0-9]{4})-([0-9]{2})-([0-9]{2})(?: +[A-Za-z]+)?(?: +([0-9]{1,2}):([0-9]{2})(?::([0-9]{2}))?)?$/) else {
334 throw Unsupported("date syntax")
335 }
336 let day = Days.absolute(year: Int(m.1)!, month: Int(m.2)!, day: Int(m.3)!)
337 guard let hour = m.4.flatMap({ Int($0) }), let minute = m.5.flatMap({ Int($0) }) else { return .date(.int(day)) }
338 let seconds = hour * 3600 + minute * 60 + (m.6.flatMap { Int($0) } ?? 0)
339 if seconds == 0 { return .date(.int(day)) }
340 return .date(try add(.int(day), try divide(.int(seconds), .int(86400))))
341 }
342
343 // MARK: - Parsing
344
345 indirect enum Node {
346 case number(Value)
347 case vector([Node])
348 case unary(Character, Node)
349 case binary(Character, Node, Node)
350 case call(String, [Node])
351 }
352
353 struct Parser {
354 let chars: [Character]
355 var i = 0
356
357 init(_ s: String) { chars = Array(s) }
358
359 mutating func skip() {
360 while i < chars.count, chars[i] == " " || chars[i] == "\t" { i += 1 }
361 }
362
363 mutating func peek() -> Character? {
364 skip()
365 return i < chars.count ? chars[i] : nil
366 }
367
368 mutating func parse() throws -> Node {
369 let node = try or()
370 guard peek() == nil else { throw Unsupported("formula syntax") }
371 return node
372 }
373
374 mutating func take(_ token: String) -> Bool {
375 guard peek() != nil else { return false }
376 let t = Array(token)
377 guard i + t.count <= chars.count, Array(chars[i..<(i + t.count)]) == t else { return false }
378 i += t.count
379 return true
380 }
381
382 // `||` < `&&` < `!` < comparisons < sums.
383 mutating func or() throws -> Node {
384 var left = try and()
385 while take("||") { left = .binary("|", left, try and()) }
386 return left
387 }
388
389 mutating func and() throws -> Node {
390 var left = try not()
391 while take("&&") { left = .binary("&", left, try not()) }
392 return left
393 }
394
395 mutating func not() throws -> Node {
396 if peek() == "!", i + 1 >= chars.count || chars[i + 1] != "=" {
397 i += 1
398 return .unary("!", try not())
399 }
400 return try comparison()
401 }
402
403 mutating func comparison() throws -> Node {
404 let left = try sum()
405 for (token, op) in [("==", "="), ("!=", "≠"), ("<=", "≤"), (">=", "≥"), ("<", "<"), (">", ">")] where take(token) {
406 let right = try sum()
407 if let next = peek(), "=!<>".contains(next) { throw Unsupported("chained comparison") }
408 return .binary(Character(op), left, right)
409 }
410 return left
411 }
412
413 // `+ -` < `/` < `*` < unary minus < `^`, as Calc's operator table orders them.
414 mutating func sum() throws -> Node {
415 var left = try quotient()
416 while let c = peek(), c == "+" || c == "-" {
417 i += 1
418 left = .binary(c, left, try quotient())
419 }
420 return left
421 }
422
423 mutating func quotient() throws -> Node {
424 var left = try product()
425 while let c = peek(), c == "/" || c == "%" || c == "\\" {
426 i += 1
427 left = .binary(c, left, try product())
428 }
429 return left
430 }
431
432 mutating func product() throws -> Node {
433 var left = try unary()
434 while peek() == "*" {
435 i += 1
436 left = .binary("*", left, try unary())
437 }
438 return left
439 }
440
441 mutating func unary() throws -> Node {
442 if let c = peek(), c == "-" || c == "+" {
443 i += 1
444 let operand = try unary()
445 return c == "-" ? .unary("-", operand) : operand
446 }
447 return try powerNode()
448 }
449
450 mutating func powerNode() throws -> Node {
451 let base = try primary()
452 if peek() == "^" {
453 i += 1
454 return .binary("^", base, try unary())
455 }
456 return base
457 }
458
459 mutating func primary() throws -> Node {
460 guard let c = peek() else { throw Unsupported("formula syntax") }
461 if c == "(" {
462 i += 1
463 let inner = try or()
464 guard peek() == ")" else { throw Unsupported("formula syntax") }
465 i += 1
466 return inner
467 }
468 if c == "[" {
469 i += 1
470 var items: [Node] = []
471 if peek() != "]" {
472 items.append(try or())
473 while peek() == "," {
474 i += 1
475 items.append(try or())
476 }
477 }
478 guard peek() == "]" else { throw Unsupported("formula syntax") }
479 i += 1
480 return .vector(items)
481 }
482 if c.isASCII, c.isNumber || c == "." { return .number(try number()) }
483 if c == "<" {
484 guard let close = chars[i...].firstIndex(of: ">") else { throw Unsupported("formula syntax") }
485 let text = String(chars[(i + 1)..<close])
486 i = close + 1
487 return .number(try parseDate(text))
488 }
489 if c.isLetter {
490 var name = ""
491 while i < chars.count, chars[i].isLetter || chars[i].isNumber || chars[i] == "_" {
492 name.append(chars[i])
493 i += 1
494 }
495 guard peek() == "(" else {
496 if name == "nan" { return .number(.nan) }
497 throw Unsupported("variable \(name)")
498 }
499 i += 1
500 var args: [Node] = []
501 if peek() != ")" {
502 args.append(try or())
503 while peek() == "," {
504 i += 1
505 args.append(try or())
506 }
507 }
508 guard peek() == ")" else { throw Unsupported("formula syntax") }
509 i += 1
510 return .call(name, args)
511 }
512 throw Unsupported("formula syntax")
513 }
514
515 /// Calc's number syntax: `7`, `007`, `1.5`, `.5`, `5.`, `1e3`, `1.5e-3`.
516 mutating func number() throws -> Value {
517 var whole = ""
518 while i < chars.count, chars[i].isASCII, chars[i].isNumber {
519 whole.append(chars[i])
520 i += 1
521 }
522 var fraction: String?
523 if i < chars.count, chars[i] == "." {
524 i += 1
525 var f = ""
526 while i < chars.count, chars[i].isASCII, chars[i].isNumber {
527 f.append(chars[i])
528 i += 1
529 }
530 fraction = f
531 }
532 var exponent: Int?
533 if i < chars.count, chars[i] == "e" || chars[i] == "E" {
534 var j = i + 1
535 var e = ""
536 if j < chars.count, chars[j] == "-" || chars[j] == "+" {
537 e.append(chars[j])
538 j += 1
539 }
540 var digitsSeen = false
541 while j < chars.count, chars[j].isASCII, chars[j].isNumber {
542 e.append(chars[j])
543 j += 1
544 digitsSeen = true
545 }
546 if digitsSeen {
547 exponent = Int(e)
548 i = j
549 }
550 }
551 guard !whole.isEmpty || !(fraction ?? "").isEmpty else { throw Unsupported("formula syntax") }
552 if fraction == nil, exponent == nil {
553 guard let value = Int(whole) else { throw Unsupported("integer size") }
554 return .int(value)
555 }
556 let digitsText = whole + (fraction ?? "")
557 guard let mantissa = Int128(digitsText.isEmpty ? "0" : digitsText) else { throw Unsupported("number size") }
558 return try makeFloat(mantissa, (exponent ?? 0) - (fraction?.count ?? 0))
559 }
560 }
561
562 // MARK: - Evaluation
563
564 struct Evaluator {
565 let modes: Modes
566
567 func eval(_ node: Node) throws -> Value {
568 switch node {
569 case .number(let v): return v
570 case .vector(let items): return .vector(try items.map(eval))
571 case .unary("!", let operand): return .int(try truth(try eval(operand)) ? 0 : 1)
572 case .unary(_, let operand): return try negate(try eval(operand))
573 case .binary(let op, let l, let r):
574 let a = try eval(l)
575 let b = try eval(r)
576 switch op {
577 case "+": return try add(a, b)
578 case "-": return try subtract(a, b)
579 case "*": return try multiply(a, b)
580 case "/": return try divide(a, b)
581 case "%": return try mod(a, b)
582 case "\\": return try idiv(a, b)
583 case "^": return try power(a, b)
584 case "|": return .int(try truth(a) || truth(b) ? 1 : 0)
585 case "&": return .int(try truth(a) && truth(b) ? 1 : 0)
586 default:
587 let order = try compare(a, b)
588 let holds = switch op {
589 case "=": order == 0
590 case "≠": order != 0
591 case "<": order < 0
592 case ">": order > 0
593 case "≤": order <= 0
594 default: order >= 0
595 }
596 return .int(holds ? 1 : 0)
597 }
598 case .call(let name, let args):
599 return try call(name, try args.map(eval))
600 }
601 }
602
603 /// A condition's value: a number, nonzero for true.
604 func truth(_ v: Value) throws -> Bool {
605 switch v {
606 case .int(let i): return i != 0
607 case .float(let m, _): return m != 0
608 default: throw Unsupported("condition")
609 }
610 }
611
612 /// `math-mod`: the remainder with the divisor's sign.
613 func mod(_ a: Value, _ b: Value) throws -> Value {
614 if case .int(let x) = a, case .int(let y) = b {
615 guard y != 0 else { throw Unsupported("division by zero") }
616 let r = x % y
617 return .int(r != 0 && (r < 0) != (y < 0) ? r + y : r)
618 }
619 let q = try floorOf(try divide(a, b))
620 return try subtract(a, try multiply(b, q))
621 }
622
623 /// `calcFunc-idiv`: the quotient rounded down.
624 func idiv(_ a: Value, _ b: Value) throws -> Value {
625 if case .int(let x) = a, case .int(let y) = b {
626 guard y != 0 else { throw Unsupported("division by zero") }
627 let q = x / y
628 return .int(q * y != x && (x < 0) != (y < 0) ? q - 1 : q)
629 }
630 return try floorOf(try divide(a, b))
631 }
632
633 func floorOf(_ v: Value) throws -> Value {
634 if case .int = v { return v }
635 guard let i = Int(exactly: try double(v).rounded(.down)) else { throw Unsupported("integer size") }
636 return .int(i)
637 }
638
639 /// The sum of squared deviations from the mean, and the count.
640 func deviations(_ args: [Value]) throws -> (Value, Int) {
641 let items = try elements(args)
642 guard !items.isEmpty else { throw Unsupported("empty vector") }
643 let mean = try divide(try items.reduce(Value.int(0)) { try add($0, $1) }, .int(items.count))
644 let squares = try items.reduce(Value.int(0)) { sum, x in
645 let d = try subtract(x, mean)
646 return try add(sum, try multiply(d, d))
647 }
648 return (squares, items.count)
649 }
650
651 func root(_ x: Value) throws -> Value {
652 try call("sqrt", [x])
653 }
654
655 func elements(_ args: [Value]) throws -> [Value] {
656 guard args.count == 1 else { throw Unsupported("arguments") }
657 if case .vector(let items) = args[0] { return items }
658 return [args[0]]
659 }
660
661 func one(_ args: [Value]) throws -> Value {
662 guard args.count == 1 else { throw Unsupported("arguments") }
663 if case .vector = args[0] { throw Unsupported("vector argument") }
664 return args[0]
665 }
666
667 func radians(_ x: Double) -> Double { modes.degrees ? x * .pi / 180 : x }
668 func angle(_ x: Double) -> Double { modes.degrees ? x * 180 / .pi : x }
669
670 func call(_ name: String, _ args: [Value]) throws -> Value {
671 switch name {
672 case "vsum":
673 return try elements(args).reduce(Value.int(0)) { try add($0, $1) }
674 case "vprod":
675 return try elements(args).reduce(Value.int(1)) { try multiply($0, $1) }
676 case "vcount":
677 return .int(try elements(args).count)
678 case "vmean":
679 let items = try elements(args)
680 guard !items.isEmpty else { throw Unsupported("empty vector") }
681 return try divide(try items.reduce(Value.int(0)) { try add($0, $1) }, .int(items.count))
682 case "vmax", "vmin":
683 let items = try elements(args)
684 guard var best = items.first else { throw Unsupported("empty vector") }
685 for item in items.dropFirst() {
686 let order = try compare(item, best)
687 if name == "vmax" ? order > 0 : order < 0 { best = item }
688 }
689 return best
690 case "vmedian":
691 var items = try elements(args)
692 guard !items.isEmpty else { throw Unsupported("empty vector") }
693 try items.sort { try compare($0, $1) < 0 }
694 if items.count % 2 == 1 { return items[items.count / 2] }
695 return try divide(try add(items[items.count / 2 - 1], items[items.count / 2]), .int(2))
696 case "if":
697 guard args.count == 3 else { throw Unsupported("arguments") }
698 return try truth(args[0]) ? args[1] : args[2]
699 case "vvar", "vpvar", "vsdev", "vpsdev":
700 let (squares, n) = try deviations(args)
701 let population = name == "vpvar" || name == "vpsdev"
702 if !population, n < 2 { throw Unsupported("variance of one value") }
703 let variance = try divide(squares, .int(population ? n : n - 1))
704 return name.hasSuffix("sdev") ? try root(variance) : variance
705 case "mod":
706 guard args.count == 2 else { throw Unsupported("arguments") }
707 return try mod(args[0], args[1])
708 case "idiv":
709 guard args.count == 2 else { throw Unsupported("arguments") }
710 return try idiv(args[0], args[1])
711 case "fact":
712 guard case .int(let n) = try one(args), n >= 0 else { throw Unsupported("arguments") }
713 var result = Value.int(1)
714 for k in stride(from: 2, through: n, by: 1) { result = try multiply(result, .int(k)) }
715 return result
716 case "max", "min":
717 guard !args.isEmpty else { throw Unsupported("arguments") }
718 var best = args[0]
719 for item in args.dropFirst() {
720 let order = try compare(item, best)
721 if name == "max" ? order > 0 : order < 0 { best = item }
722 }
723 return best
724 case "abs":
725 let x = try one(args)
726 return try compare(x, .int(0)) < 0 ? try negate(x) : x
727 case "floor", "ceil", "trunc":
728 let x = try one(args)
729 if case .int = x { return x }
730 let d = try double(x)
731 let r = name == "floor" ? d.rounded(.down) : name == "ceil" ? d.rounded(.up) : d.rounded(.towardZero)
732 guard let i = Int(exactly: r) else { throw Unsupported("integer size") }
733 return .int(i)
734 case "round":
735 guard args.count == 1 || args.count == 2 else { throw Unsupported("arguments") }
736 let x = args[0]
737 if args.count == 2 {
738 guard case .int(let places) = args[1] else { throw Unsupported("arguments") }
739 guard case .float(let m, let e) = x else { return x }
740 return try makeFloat(try scaleRounding(Int128(m), e + places), -places)
741 }
742 guard case .float(let m, let e) = x else { return x }
743 guard let i = Int(exactly: try scaleRounding(Int128(m), e)) else { throw Unsupported("integer size") }
744 return .int(i)
745 case "sqrt":
746 let x = try one(args)
747 if case .int(let i) = x {
748 guard i >= 0 else { throw Unsupported("complex result") }
749 let root = Int(Double(i).squareRoot().rounded())
750 if root * root == i { return .int(root) }
751 }
752 let d = try double(x)
753 guard d >= 0 else { throw Unsupported("complex result") }
754 return try fromDouble(d.squareRoot())
755 case "exp":
756 let x = try one(args)
757 if x == .int(0) { return .int(1) }
758 return try fromDouble(Foundation.exp(try double(x)))
759 case "ln":
760 let x = try one(args)
761 if x == .int(1) { return .int(0) }
762 let d = try double(x)
763 guard d > 0 else { throw Unsupported("logarithm domain") }
764 return try fromDouble(Foundation.log(d))
765 case "log10":
766 let x = try one(args)
767 if case .int(let i) = x, i > 0 {
768 var n = i
769 var k = 0
770 while n % 10 == 0 {
771 n /= 10
772 k += 1
773 }
774 if n == 1 { return .int(k) }
775 }
776 let d = try double(x)
777 guard d > 0 else { throw Unsupported("logarithm domain") }
778 return try fromDouble(Foundation.log10(d))
779 case "sin", "cos", "tan":
780 let x = try one(args)
781 if modes.degrees, case .int(let i) = x, i % 90 == 0 {
782 let quarter = ((i / 90) % 4 + 4) % 4
783 switch name {
784 case "sin": return .int([0, 1, 0, -1][quarter])
785 case "cos": return .int([1, 0, -1, 0][quarter])
786 default:
787 guard quarter % 2 == 0 else { throw Unsupported("infinite result") }
788 return .int(0)
789 }
790 }
791 if !modes.degrees, x == .int(0) { return .int(name == "cos" ? 1 : 0) }
792 let r = radians(try double(x))
793 return try fromDouble(name == "sin" ? Foundation.sin(r) : name == "cos" ? Foundation.cos(r) : Foundation.tan(r))
794 case "arcsin", "arccos", "arctan":
795 let x = try one(args)
796 if modes.degrees, case .int(let i) = x {
797 switch (name, i) {
798 case ("arcsin", -1), ("arcsin", 0), ("arcsin", 1): return .int(90 * i)
799 case ("arccos", -1), ("arccos", 0), ("arccos", 1): return .int(90 - 90 * i)
800 case ("arctan", -1), ("arctan", 0), ("arctan", 1): return .int(45 * i)
801 default: break
802 }
803 }
804 let d = try double(x)
805 if name != "arctan", abs(d) > 1 { throw Unsupported("complex result") }
806 let r = name == "arcsin" ? Foundation.asin(d) : name == "arccos" ? Foundation.acos(d) : Foundation.atan(d)
807 return try fromDouble(angle(r))
808 default:
809 throw Unsupported("function \(name)")
810 }
811 }
812 }
813}