text.bend source
text.bend on the hub · documented module
# bend-float64's text: show prints the shortest decimal that reads back to the same float64, laid out as Python's# repr (0.1, 1e+16, 1.5e-07, 123.0, -0.0, inf, nan); parse reads Python's float() grammar and rounds correctly# (to nearest, ties to even), however many digits the text has. Both are exact: big-integer arithmetic, no# approximation. Pure.import Baseimport ./wide.bend as Wimport ./big.bend as Bimport ./float64.bend as F# ---- shortest digits (Burger and Dybvig's free-format algorithm, exact) ----# the digits d1 d2 .. dn and the decimal point's place: the value is 0.d1d2..dn * 10^decpt (decpt a signed word)type Digits is Data: Digits{ds: List<&2, U32>, decpt: U32}type DR is Data: DR{d: U32, r: List<&2, U32>}# s, 2s, 4s and 8s, made once by doublingtype S4 is Data: S4{s1: List<&2, U32>, s2: List<&2, U32>, s4: List<&2, U32>, s8: List<&2, U32>}def s4_of(+s: List<&2, U32>) -> S4: +s2 = B.add(s, s) +s4 = B.add(s2, s2) S4{s, s2, s4, B.add(s4, s4)}# one step of r / s: t = s * w taken from r when it fitsdef dr_step(x: DR, +t: List<&2, U32>, +w: U32) -> DR: match x: case DR{+d, +r}: +ge = B.le(t, r) DR{(d + Bool.to_u32(ge) * w : U32), Bool.pick(List<&2, U32>, ge, B.sub(r, t), r)}# r / s and r mod s, for r < 16 s: four steps of binary long divisiondef divrem(+r: List<&2, U32>, m: S4) -> DR: match m: case S4{s1, s2, s4, s8}: dr_step(dr_step(dr_step(dr_step(DR{0, r}, s8, 8), s4, 4), s2, 2), s1, 1)def bound_ok(ok: Bool, +c: Cmp) -> Bool: match ok: case True{}: Cmp.is_le(c) case False{}: Cmp.is_lt(c)# both ends reachable: the nearer digit; halfway, the even onedef last_both(+d: U32, +r: List<&2, U32>, +s: List<&2, U32>) -> U32: +c = B.cmp(B.shl(r, 1), s) Bool.pick(U32, Cmp.is_lt(c), d, Bool.pick(U32, Cmp.is_gt(c), (d + 1 : U32), Bool.pick(U32, U32.is_eq(U32.and(d, 1), 0), d, (d + 1 : U32))))def gen_pick(lo: Bool, hi: Bool, +d: U32, +r: List<&2, U32>, +s: List<&2, U32>, more: Unit -> List<&2, U32>) -> List<&2, U32>: match lo hi: case False{} False{}: d <> more(Unit{}) case True{} False{}: [d] case False{} True{}: [(d + 1 : U32)] case True{} True{}: [last_both(d, r, s)]# one digit a step: the next digit, and whether the digits so far, ending here, are within the rounding intervaldef gen(n: Nat, q: DR, +s: List<&2, U32>, +m: S4, +mp: List<&2, U32>, +mm: List<&2, U32>, +ok: Bool) -> List<&2, U32>: match n q: case 0n _: [] case 1n+k DR{+d, +r}: gen_pick(bound_ok(ok, B.cmp(r, mm)), bound_ok(ok, B.cmp(s, B.add(r, mp))), d, r, s, u => gen(k, divrem(B.mul10(r), m), s, m, B.mul10(mp), B.mul10(mm), ok))type BD is Data: BD{r: List<&2, U32>, s: List<&2, U32>, mp: List<&2, U32>, mm: List<&2, U32>, k: U32}# raise k while r + m+ reaches s (past the decimal point's place)def fixup(n: Nat, b: BD, +ok: Bool) -> BD: match n b: case 0n x: x case 1n+j BD{+r, +s, +mp, +mm, +k}: Bool.pick(BD, bound_ok(ok, B.cmp(s, B.add(r, mp))), fixup(j, BD{r, B.mul10(s), mp, mm, (k + 1 : U32)}, ok), BD{r, s, mp, mm, k})def is_neg(+x: U32) -> Bool: U32.is_le(2147483648, x)# scale by the estimate 10^kdef scale_go(neg: Bool, +r: List<&2, U32>, +s: List<&2, U32>, +mp: List<&2, U32>, +mm: List<&2, U32>, +k: U32) -> BD: match neg: case True{}: BD{B.mul_pow10(r, (0 - k : U32)), s, B.mul_pow10(mp, (0 - k : U32)), B.mul_pow10(mm, (0 - k : U32)), k} case False{}: BD{r, B.mul_pow10(s, k), mp, mm, k}def scale(b: BD) -> BD: match b: case BD{r, s, mp, mm, +k}: scale_go(is_neg(k), r, s, mp, mm, k)# ceil(x * log10(2)) for a signed x, |x| < 1650def ceil_log10_2(+x: U32) -> U32: Bool.pick(U32, U32.is_eq(x, 0), 0, Bool.pick(U32, is_neg(x), (0 - U32.shrn(((0 - x : U32) * 78913 : U32), 18n) : U32), (U32.shrn((x * 78913 : U32), 18n) + 1 : U32)))def digits_go(b: BD, +ok: Bool) -> Digits: match b: case BD{r, +s, mp, mm, k}: +m = s4_of(s) Digits{gen(20n, divrem(B.mul10(r), m), s, m, B.mul10(mp), B.mul10(mm), ok), k}def setup_go(neg: Bool, asym: Bool, +f: List<&2, U32>, +be: U32, +k: U32) -> BD: match neg asym: case True{} True{}: BD{B.shl(f, 2), B.shl([1], (2 - be : U32)), [2], [1], k} case True{} False{}: BD{B.shl(f, 1), B.shl([1], (1 - be : U32)), [1], [1], k} case False{} True{}: BD{B.shl(f, (be + 2 : U32)), [4], B.shl([1], (be + 1 : U32)), B.shl([1], be), k} case False{} False{}: BD{B.shl(f, (be + 1 : U32)), [2], B.shl([1], be), B.shl([1], be), k}# m * 2^be, be = e - 1075: r / s is the value, m+ / s and m- / s half the gaps to its neighbours (the lower gap is# half as wide when m is a power of two above the smallest exponent)def setup(+m: W.W64, +e: U32, +k: U32) -> BD: +be = (e - 1075 : U32) +f = B.of_w64(m) +asym = Bool.and(W.eq(m, W.W64{1048576, 0}), U32.is_lt(1, e)) setup_go(is_neg(be), asym, f, be, k)# the shortest digits of the finite nonzero m * 2^(e - 1075) that read back to itdef shortest(+e: U32, +m: W.W64) -> Digits: +ok = U32.is_eq(U32.and(W.low(m), 1), 0) digits_go(fixup(3n, scale(setup(m, e, ceil_log10_2((B.bitlen(B.of_w64(m)) - 1 + e - 1075 : U32)))), ok), ok)# ---- layout, as Python's repr ----def digit_chars(ds: List<&2, U32>, rest: String) -> String: match ds: case []: rest case d <> t: SCon{Chr{(d + 48 : U32)}, digit_chars(t, rest)}def zero_chars(n: Nat, rest: String) -> String: match n: case 0n: rest case 1n+k: SCon{Chr{48}, zero_chars(k, rest)}def take_d(n: Nat, xs: List<&2, U32>) -> List<&2, U32>: match n xs: case 0n _: [] case 1n+k Nil{}: [] case 1n+k y <> t: y <> take_d(k, t)def drop_d(n: Nat, xs: List<&2, U32>) -> List<&2, U32>: match n xs: case 0n ys: ys case 1n+k Nil{}: [] case 1n+k y <> t: drop_d(k, t)def len_d(xs: List<&2, U32>) -> U32: match xs: case []: 0 case x <> t: (1 + len_d(t) : U32)def exp_text(+x: U32) -> String: +neg = is_neg(x) +a = Bool.pick(U32, neg, (0 - x : U32), x) Bool.pick(String, neg, "-", "+") ++ Bool.pick(String, U32.is_lt(a, 10), "0", "") ++ U32.show(a)def frac_part(ds: List<&2, U32>) -> String: match ds: case []: "" case d <> t: "." ++ digit_chars(d <> t, "")def sci(ds: List<&2, U32>, +decpt: U32) -> String: match ds: case []: "0.0" case d <> t: digit_chars([d], "") ++ frac_part(t) ++ "e" ++ exp_text((decpt - 1 : U32))# 0 < decpt < 17def fixed_pos(inside: Bool, +ds: List<&2, U32>, +n: U32, +decpt: U32) -> String: match inside: case True{}: digit_chars(take_d(U32.to_nat(decpt), ds), "." ++ digit_chars(drop_d(U32.to_nat(decpt), ds), "")) case False{}: digit_chars(ds, zero_chars(U32.to_nat((decpt - n : U32)), ".0"))# 0, 1: exponent form, a leading 0., digits then the pointtype Form is Data: FSci{} FLead{} FPos{}def form_of(+decpt: U32) -> Form: Bool.pick(Form, Bool.or(Bool.and(is_neg(decpt), U32.is_le(4, (0 - decpt : U32))), Bool.and(Bool.not(is_neg(decpt)), U32.is_lt(16, decpt))), FSci{}, Bool.pick(Form, Bool.or(is_neg(decpt), U32.is_eq(decpt, 0)), FLead{}, FPos{}))def layout_f(f: Form, +ds: List<&2, U32>, +decpt: U32) -> String: match f: case FSci{}: sci(ds, decpt) case FLead{}: "0." ++ zero_chars(U32.to_nat((0 - decpt : U32)), digit_chars(ds, "")) case FPos{}: fixed_pos(U32.is_lt(decpt, len_d(ds)), ds, len_d(ds), decpt)def layout(d: Digits) -> String: match d: case Digits{ds, +decpt}: layout_f(form_of(decpt), ds, decpt)def show_c(c: F.Cls) -> String: match c: case F.FNan{}: "nan" case F.FInf{s}: Bool.pick(String, U32.is_eq(s, 0), "inf", "-inf") case F.FZero{s}: Bool.pick(String, U32.is_eq(s, 0), "0.0", "-0.0") case F.FFin{s, +e, +m}: Bool.pick(String, U32.is_eq(s, 0), "", "-") ++ layout(shortest(e, m))# the shortest text that reads back to x, as Python's repr(x)def show(x: F.F64) -> String: show_c(F.cls(x))# ---- reading ----def codes(s: String) -> List<&2, U32>: match s: case SNil{}: [] case SCon{Chr{c}, t}: c <> codes(t)# the whitespace Python's float() strips: str.isspace without 28 .. 31def is_space(+c: U32) -> Bool: Bool.or(Bool.or(Bool.and(U32.is_le(9, c), U32.is_le(c, 13)), U32.is_eq(c, 32)), Bool.or(Bool.or(U32.is_eq(c, 133), U32.is_eq(c, 160)), Bool.or(Bool.or(U32.is_eq(c, 5760), Bool.and(U32.is_le(8192, c), U32.is_le(c, 8202))), Bool.or(Bool.or(U32.is_eq(c, 8232), U32.is_eq(c, 8233)), Bool.or(Bool.or(U32.is_eq(c, 8239), U32.is_eq(c, 8287)), U32.is_eq(c, 12288))))))def strip_lead(xs: List<&2, U32>) -> List<&2, U32>: match xs: case []: [] case +c <> +t: Bool.pick(List<&2, U32>, is_space(c), strip_lead(t), c <> t)def strip(xs: List<&2, U32>) -> List<&2, U32>: List.reverse(&2, U32, strip_lead(List.reverse(&2, U32, strip_lead(xs))))def lower(+c: U32) -> U32: Bool.pick(U32, Bool.and(U32.is_le(65, c), U32.is_le(c, 90)), (c + 32 : U32), c)def word_is(xs: List<&2, U32>, w: List<&2, U32>) -> Bool: match xs w: case Nil{} Nil{}: True{} case x <> xt y <> yt: Bool.and(U32.is_eq(lower(x), y), word_is(xt, yt)) case _ _: False{}# the number's text so far: the state, its digits (last first), how many came after the point, the exponent# (clamped at 10^8) and its sign. States: 0 nothing, 1 an integer digit, 2 an integer _, 3 a point first,# 4 a point after digits, 5 a fraction digit, 6 a fraction _, 7 e, 8 the exponent's sign, 9 an exponent digit,# 10 an exponent _, 11 not a numbertype PS is Data: PS{st: U32, ds: List<&2, U32>, nfrac: U32, ex: U32, exneg: Bool}def st_digit(+st: U32) -> U32: Bool.pick(U32, U32.is_eq(st, 0), 1, Bool.pick(U32, U32.is_le(st, 2), 1, Bool.pick(U32, U32.is_le(st, 6), 5, Bool.pick(U32, U32.is_le(st, 10), 9, 11))))def st_under(+st: U32) -> U32: Bool.pick(U32, U32.is_eq(st, 1), 2, Bool.pick(U32, U32.is_eq(st, 5), 6, Bool.pick(U32, U32.is_eq(st, 9), 10, 11)))def st_point(+st: U32) -> U32: Bool.pick(U32, U32.is_eq(st, 0), 3, Bool.pick(U32, U32.is_eq(st, 1), 4, 11))def st_e(+st: U32) -> U32: Bool.pick(U32, Bool.or(U32.is_eq(st, 1), Bool.or(U32.is_eq(st, 4), U32.is_eq(st, 5))), 7, 11)def st_sign(+st: U32) -> U32: Bool.pick(U32, U32.is_eq(st, 7), 8, 11)def is_dig(+c: U32) -> Bool: Bool.and(U32.is_le(48, c), U32.is_le(c, 57))# where a digit goes, from the state it arrives intype DK is Data: DInt{} DFrac{} DExp{} DBad{}def digit_kind(+st: U32) -> DK: Bool.pick(DK, U32.is_le(st, 2), DInt{}, Bool.pick(DK, U32.is_le(st, 6), DFrac{}, Bool.pick(DK, U32.is_le(st, 10), DExp{}, DBad{})))def push_digit(k: DK, ds: List<&2, U32>, +nfrac: U32, +ex: U32, +exneg: Bool, +d: U32) -> PS: match k: case DInt{}: PS{1, d <> ds, nfrac, ex, exneg} case DFrac{}: PS{5, d <> ds, (nfrac + 1 : U32), ex, exneg} case DExp{}: PS{9, ds, nfrac, Bool.pick(U32, U32.is_lt(ex, 100000000), (ex * 10 + d : U32), ex), exneg} case DBad{}: PS{11, ds, nfrac, ex, exneg}# a character's classtype CC is Data: CDigit{d: U32} CUnder{} CPoint{} CE{} CSign{neg: Bool} COther{}def class_of(+c: U32) -> CC: Bool.pick(CC, is_dig(c), CDigit{(c - 48 : U32)}, Bool.pick(CC, U32.is_eq(c, 95), CUnder{}, Bool.pick(CC, U32.is_eq(c, 46), CPoint{}, Bool.pick(CC, U32.is_eq(lower(c), 101), CE{}, Bool.pick(CC, Bool.or(U32.is_eq(c, 43), U32.is_eq(c, 45)), CSign{U32.is_eq(c, 45)}, COther{})))))def step_c(k: CC, p: PS) -> PS: match k p: case CDigit{d} PS{+st, ds, nfrac, ex, exneg}: push_digit(digit_kind(st_digit(st)), ds, nfrac, ex, exneg, d) case CUnder{} PS{st, ds, nfrac, ex, exneg}: PS{st_under(st), ds, nfrac, ex, exneg} case CPoint{} PS{st, ds, nfrac, ex, exneg}: PS{st_point(st), ds, nfrac, ex, exneg} case CE{} PS{st, ds, nfrac, ex, exneg}: PS{st_e(st), ds, nfrac, ex, exneg} case CSign{neg} PS{st, ds, nfrac, ex, exneg}: PS{st_sign(st), ds, nfrac, ex, neg} case COther{} PS{st, ds, nfrac, ex, exneg}: PS{11, ds, nfrac, ex, exneg}def step(p: PS, +c: U32) -> PS: step_c(class_of(c), p)def run(xs: List<&2, U32>, p: PS) -> PS: match xs: case []: p case c <> t: run(t, step(p, c))# ---- digits to the nearest float64 ----# trailing zeros (at the front of the last-first list) dropped and countedtype TZ is Data: TZ{ds: List<&2, U32>, n: U32}def drop_tz(xs: List<&2, U32>, +n: U32) -> TZ: match xs: case []: TZ{[], n} case +d <> +t: Bool.pick(TZ, U32.is_eq(d, 0), drop_tz(t, (n + 1 : U32)), TZ{d <> t, n})def drop_lz(xs: List<&2, U32>) -> List<&2, U32>: match xs: case []: [] case +d <> +t: Bool.pick(List<&2, U32>, U32.is_eq(d, 0), drop_lz(t), d <> t)def big_of(xs: List<&2, U32>, +acc: List<&2, U32>) -> List<&2, U32>: match xs: case []: acc case d <> t: big_of(t, B.add(B.mul10(acc), B.of_u32(d)))type QW is Data: QW{q: W.W64, r: List<&2, U32>}# n steps of long division, quotient bit i firstdef div_bits(n: Nat, +i: U32, +num: List<&2, U32>, +den: List<&2, U32>, +q: W.W64) -> QW: match n: case 0n: QW{q, num} case 1n+k: +t = B.shl(den, i) +ge = B.le(t, num) div_bits(k, (i - 1 : U32), Bool.pick(List<&2, U32>, ge, B.sub(num, t), num), den, W.or(q, Bool.pick(W.W64, ge, W.shl(W.w(1), i), W.w(0))))def qw_sig(x: QW) -> W.W64: match x: case QW{q, r}: W.jam_or(q, Bool.not(B.is_zero(r)))def top_pack(+s: U32, t: B.Top) -> F.F64: match t: case B.Top{sig, k}: F.round_pack(s, (1084 + k : U32), sig)def quot(neg: Bool, +d: List<&2, U32>, +m: List<&2, U32>, +k: U32) -> QW: match neg: case True{}: div_bits(64n, 63, d, B.shl(m, (0 - k : U32)), W.w(0)) case False{}: div_bits(64n, 63, B.shl(d, k), m, W.w(0))# d / m: a quotient of 63 or 64 bits by long division (d or m first shifted to line them up), the remainder stickydef small_value(+s: U32, +d: List<&2, U32>, +m: List<&2, U32>) -> F.F64: +k = (B.bitlen(m) - B.bitlen(d) + 63 : U32) F.round_pack(s, (1084 - k : U32), qw_sig(quot(is_neg(k), d, m, k)))# the float64 nearest s * d * 10^e: d a nonzero big integer, e a signed worddef exact_go(neg: Bool, +s: U32, d: List<&2, U32>, +e: U32) -> F.F64: match neg: case True{}: small_value(s, d, B.pow10((0 - e : U32))) case False{}: top_pack(s, B.top64(B.mul_pow10(d, e)))def exact(+s: U32, d: List<&2, U32>, +e: U32) -> F.F64: exact_go(is_neg(e), s, d, e)# what the size of the number decides: zero digits, past the largest float64, below half the smallesttype Range is Data: RZero{} RInf{} RTiny{} RExact{}def range_of(+n: U32, +t: U32) -> Range: Bool.pick(Range, U32.is_eq(n, 0), RZero{}, Bool.pick(Range, Bool.and(Bool.not(is_neg(t)), U32.is_lt(310, t)), RInf{}, Bool.pick(Range, Bool.and(is_neg(t), U32.is_lt(324, (0 - t : U32))), RTiny{}, RExact{})))# a big integer below 2^64 times 2^k as a float64 (exact when it fits in 53 bits)def big_f64(+d: List<&2, U32>) -> F.F64: top_pack(0, B.top64(d))# Clinger's fast path: d < 10^15 and 10^|e| (|e| <= 22) are both exact float64s, so one correctly rounded multiply or# divide is the correctly rounded answerdef fast(neg: Bool, +d: List<&2, U32>, +e: U32) -> F.F64: match neg: case True{}: F.div(big_f64(d), big_f64(B.pow10((0 - e : U32)))) case False{}: F.mul(big_f64(d), big_f64(B.pow10(e)))def exact_or_fast(quick: Bool, +s: U32, d: List<&2, U32>, +e: U32) -> F.F64: match quick: case True{}: F.with_sign(s, fast(is_neg(e), d, e)) case False{}: exact(s, d, e)def value_r(r: Range, +s: U32, +n: U32, ds: List<&2, U32>, +e: U32) -> F.F64: match r: case RZero{}: F.zero(s) case RInf{}: F.inf(s) case RTiny{}: F.zero(s) case RExact{}: exact_or_fast(Bool.and(U32.is_le(n, 15), Bool.and(U32.is_le((e + 22 : U32), 44), Bool.not(is_neg((e + 22 : U32))))), s, big_of(ds, []), e)# digits (first first, no leading or trailing zeros, n of them) times 10^e: past 800 digits the rest is only# "something nonzero", a final 1, which rounds the samedef value(+s: U32, +ds: List<&2, U32>, +n: U32, +e: U32) -> F.F64: +long = U32.is_lt(800, n) +ds2 = Bool.pick(List<&2, U32>, long, List.append(&2, U32, take_d(800n, ds), [1]), ds) +n2 = Bool.pick(U32, long, 801, n) +e2 = Bool.pick(U32, long, (e + n - 801 : U32), e) value_r(range_of(n, (n2 + e2 : U32)), s, n2, ds2, e2)def number(+s: U32, t: TZ, +nfrac: U32, +ex: U32, +exneg: Bool) -> F.F64: match t: case TZ{ds, tz}: +fwd = drop_lz(List.reverse(&2, U32, ds)) value(s, fwd, len_d(fwd), (Bool.pick(U32, exneg, (0 - ex : U32), ex) - nfrac + tz : U32))def accepting(+st: U32) -> Bool: Bool.or(Bool.or(U32.is_eq(st, 1), U32.is_eq(st, 4)), Bool.or(U32.is_eq(st, 5), U32.is_eq(st, 9)))def bad(+text: String) -> Result<&2, &2, String, F.F64>: Fail{"could not convert string to float: '" ++ text ++ "'"}def finish_ok(ok: Bool, +s: U32, ds: List<&2, U32>, +nfrac: U32, +ex: U32, +exneg: Bool, +text: String) -> Result<&2, &2, String, F.F64>: match ok: case True{}: Done{number(s, drop_tz(ds, 0), nfrac, ex, exneg)} case False{}: bad(text)def finish(p: PS, +s: U32, +text: String) -> Result<&2, &2, String, F.F64>: match p: case PS{+st, ds, nfrac, ex, exneg}: finish_ok(accepting(st), s, ds, nfrac, ex, exneg, text)# what the text after the sign spells: infinity, nan, or a number to readtype Spelt is Data: WInf{} WNan{} WNum{}def word_of(+xs: List<&2, U32>) -> Spelt: Bool.pick(Spelt, Bool.or(word_is(xs, [105, 110, 102]), word_is(xs, [105, 110, 102, 105, 110, 105, 116, 121])), WInf{}, Bool.pick(Spelt, word_is(xs, [110, 97, 110]), WNan{}, WNum{}))def body_w(w: Spelt, +s: U32, xs: List<&2, U32>, +text: String) -> Result<&2, &2, String, F.F64>: match w: case WInf{}: Done{F.inf(s)} case WNan{}: Done{F.F64{U32.or(s, 2146959360), 0}} case WNum{}: finish(run(xs, PS{0, [], 0, 0, False{}}), s, text)def body(+s: U32, +xs: List<&2, U32>, +text: String) -> Result<&2, &2, String, F.F64>: body_w(word_of(xs), s, xs, text)# a leading sign: 45 is -, 43 is +type Sgn is Data: SMinus{} SPlus{} SNone{}def sgn_of(+c: U32) -> Sgn: Bool.pick(Sgn, U32.is_eq(c, 45), SMinus{}, Bool.pick(Sgn, U32.is_eq(c, 43), SPlus{}, SNone{}))def signed_c(g: Sgn, +c: U32, t: List<&2, U32>, +text: String) -> Result<&2, &2, String, F.F64>: match g: case SMinus{}: body(2147483648, t, text) case SPlus{}: body(0, t, text) case SNone{}: body(0, c <> t, text)def signed(xs: List<&2, U32>, +text: String) -> Result<&2, &2, String, F.F64>: match xs: case []: bad(text) case +c <> t: signed_c(sgn_of(c), c, t, text)# the float64 that Python's float(text) gives (ASCII digits), or why the text is not a numberdef parse(+text: String) -> Result<&2, &2, String, F.F64>: signed(strip(codes(text)), text)