aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/data/number.lux
blob: 13ffe71dae964b009a0cf2babfd17989dee7690e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
(.module: {#.doc "Implementations of common structures for Lux's primitive number types."}
  [lux #*
   [control
    number
    [monoid (#+ Monoid)]
    [equivalence (#+ Equivalence)]
    hash
    ["." order (#+ Order)]
    enum
    interval
    [codec (#+ Codec)]]
   [data
    ["." error (#+ Error)]
    ["." maybe]
    ["." text]]]
  [/
   ["." i64]])

## [Structures]
(do-template [<type> <test>]
  [(structure: #export _ (Equivalence <type>)
     (def: = <test>))]

  [ Nat n/=]
  [ Int i/=]
  [ Rev r/=]
  [Frac f/=]
  )

(do-template [<type> <eq> <lt> <lte> <gt> <gte>]
  [(structure: #export _ (Order <type>)
     (def: eq <eq>)
     (def: < <lt>)
     (def: <= <lte>)
     (def: > <gt>)
     (def: >= <gte>))]

  [ Nat Equivalence<Nat>  n/< n/<= n/> n/>=]
  [ Int Equivalence<Int>  i/< i/<= i/> i/>=]
  [Rev  Equivalence<Rev>  r/< r/<= r/> r/>=]
  [Frac Equivalence<Frac> f/< f/<= f/> f/>=]
  )

(structure: #export _ (Number Nat)
  (def: + n/+)
  (def: - n/-)
  (def: * n/*)
  (def: / n//)
  (def: % n/%)
  (def: negate id)
  (def: abs id)
  (def: (signum x)
    (case x
      0 0
      _  1))
  )

(do-template [<type> <order> <+> <-> <*> </> <%> <=> <<> <0> <1> <-1>]
  [(structure: #export _ (Number <type>)
     (def: + <+>)
     (def: - <->)
     (def: * <*>)
     (def: / </>)
     (def: % <%>)
     (def: negate (<*> <-1>))
     (def: (abs x)
       (if (<<> <0> x)
         (<*> <-1> x)
         x))
     (def: (signum x)
       (cond (<=> <0> x) <0>
             (<<> <0> x) <-1>
             ## else
             <1>))
     )]

  [ Int  Order<Int> i/+ i/- i/* i// i/% i/= i/<   +0   +1   -1]
  [Frac Order<Frac> f/+ f/- f/* f// f/% f/= f/< +0.0 +1.0 -1.0]
  )

(structure: #export _ (Number Rev)
  (def: + r/+)
  (def: - r/-)
  (def: * r/*)
  (def: / r//)
  (def: % r/%)
  (def: (negate x) (r/- x (:coerce Rev -1)))
  (def: abs id)
  (def: (signum x)
    (:coerce Rev -1)))

(do-template [<type> <order> <succ> <pred>]
  [(structure: #export _ (Enum <type>)
     (def: order <order>)
     (def: succ <succ>)
     (def: pred <pred>))]

  [Nat  Order<Nat>  inc dec]
  [Int  Order<Int>  inc dec]
  [Frac Order<Frac> (f/+ ("lux frac smallest")) (f/- ("lux frac smallest"))]
  [Rev  Order<Rev>  inc dec]
  )

(do-template [<type> <enum> <top> <bottom>]
  [(structure: #export _ (Interval <type>)
     (def: enum <enum>)
     (def: top <top>)
     (def: bottom <bottom>))]

  [ Nat Enum<Nat>  (:coerce Nat -1) 0]
  [ Int Enum<Int>  +9_223_372_036_854_775_807 -9_223_372_036_854_775_808]
  [Frac Enum<Frac> ("lux frac max") ("lux frac min")]
  [ Rev Enum<Rev>  (:coerce Rev -1) (:coerce Rev 0)]
  )

(do-template [<name> <type> <identity> <compose>]
  [(structure: #export <name> (Monoid <type>)
     (def: identity <identity>)
     (def: compose <compose>))]

  [ Add@Monoid<Nat>  Nat 0                         n/+]
  [ Mul@Monoid<Nat>  Nat 1                         n/*]
  [ Max@Monoid<Nat>  Nat (:: Interval<Nat> bottom)  n/max]
  [ Min@Monoid<Nat>  Nat (:: Interval<Nat> top)     n/min]
  [ Add@Monoid<Int>  Int +0                          i/+]
  [ Mul@Monoid<Int>  Int +1                          i/*]
  [ Max@Monoid<Int>  Int (:: Interval<Int> bottom)  i/max]
  [ Min@Monoid<Int>  Int (:: Interval<Int> top)     i/min]
  [Add@Monoid<Frac> Frac +0.0                        f/+]
  [Mul@Monoid<Frac> Frac +1.0                        f/*]
  [Max@Monoid<Frac> Frac (:: Interval<Frac> bottom) f/max]
  [Min@Monoid<Frac> Frac (:: Interval<Frac> top)    f/min]
  [ Add@Monoid<Rev>  Rev (:: Interval<Rev> bottom)  r/+]
  [ Mul@Monoid<Rev>  Rev (:: Interval<Rev> top)     r/*]
  [ Max@Monoid<Rev>  Rev (:: Interval<Rev> bottom)  r/max]
  [ Min@Monoid<Rev>  Rev (:: Interval<Rev> top)     r/min]
  )

(do-template [<name> <numerator> <doc>]
  [(def: #export <name>
     {#.doc <doc>}
     Frac
     (f// +0.0 <numerator>))]

  [not-a-number       +0.0 "Not a number."]
  [positive-infinity  +1.0 "Positive infinity."]
  [negative-infinity -1.0 "Negative infinity."]
  )

(def: #export (not-a-number? number)
  {#.doc "Tests whether a frac is actually not-a-number."}
  (-> Frac Bit)
  (not (f/= number number)))

(def: #export (frac? value)
  (-> Frac Bit)
  (not (or (not-a-number? value)
           (f/= positive-infinity value)
           (f/= negative-infinity value))))

(do-template [<type> <encoder> <decoder> <error>]
  [(structure: #export _ (Codec Text <type>)
     (def: (encode x)
       (<encoder> [x]))

     (def: (decode input)
       (case (<decoder> [input])
         (#.Some value)
         (#error.Success value)

         #.None
         (#error.Error <error>))))]

  [Frac "lux frac encode" "lux frac decode" "Could not decode Frac"]
  )

## [Values & Syntax]
(def: (get-char full idx)
  (-> Text Nat (Maybe Text))
  ("lux text clip" full idx (inc idx)))

(def: (binary-character value)
  (-> Nat (Maybe Text))
  (case value
    0 (#.Some "0")
    1 (#.Some "1")
    _ #.None))

(def: (binary-value digit)
  (-> Text (Maybe Nat))
  (case digit
    "0" (#.Some 0)
    "1" (#.Some 1)
    _ #.None))

(def: (octal-character value)
  (-> Nat (Maybe Text))
  (case value
    0 (#.Some "0")
    1 (#.Some "1")
    2 (#.Some "2")
    3 (#.Some "3")
    4 (#.Some "4")
    5 (#.Some "5")
    6 (#.Some "6")
    7 (#.Some "7")
    _ #.None))

(def: (octal-value digit)
  (-> Text (Maybe Nat))
  (case digit
    "0" (#.Some 0)
    "1" (#.Some 1)
    "2" (#.Some 2)
    "3" (#.Some 3)
    "4" (#.Some 4)
    "5" (#.Some 5)
    "6" (#.Some 6)
    "7" (#.Some 7)
    _ #.None))

(def: (decimal-character value)
  (-> Nat (Maybe Text))
  (case value
    0 (#.Some "0")
    1 (#.Some "1")
    2 (#.Some "2")
    3 (#.Some "3")
    4 (#.Some "4")
    5 (#.Some "5")
    6 (#.Some "6")
    7 (#.Some "7")
    8 (#.Some "8")
    9 (#.Some "9")
    _ #.None))

(def: (decimal-value digit)
  (-> Text (Maybe Nat))
  (case digit
    "0" (#.Some 0)
    "1" (#.Some 1)
    "2" (#.Some 2)
    "3" (#.Some 3)
    "4" (#.Some 4)
    "5" (#.Some 5)
    "6" (#.Some 6)
    "7" (#.Some 7)
    "8" (#.Some 8)
    "9" (#.Some 9)
    _ #.None))

(def: (hexadecimal-character value)
  (-> Nat (Maybe Text))
  (case value
    0 (#.Some "0")
    1 (#.Some "1")
    2 (#.Some "2")
    3 (#.Some "3")
    4 (#.Some "4")
    5 (#.Some "5")
    6 (#.Some "6")
    7 (#.Some "7")
    8 (#.Some "8")
    9 (#.Some "9")
    10 (#.Some "A")
    11 (#.Some "B")
    12 (#.Some "C")
    13 (#.Some "D")
    14 (#.Some "E")
    15 (#.Some "F")
    _ #.None))

(def: (hexadecimal-value digit)
  (-> Text (Maybe Nat))
  (case digit
    "0" (#.Some 0)
    "1" (#.Some 1)
    "2" (#.Some 2)
    "3" (#.Some 3)
    "4" (#.Some 4)
    "5" (#.Some 5)
    "6" (#.Some 6)
    "7" (#.Some 7)
    "8" (#.Some 8)
    "9" (#.Some 9)
    (^or "a" "A") (#.Some 10)
    (^or "b" "B") (#.Some 11)
    (^or "c" "C") (#.Some 12)
    (^or "d" "D") (#.Some 13)
    (^or "e" "E") (#.Some 14)
    (^or "f" "F") (#.Some 15)
    _ #.None))

(do-template [<struct> <base> <to-character> <to-value> <error>]
  [(structure: #export <struct> (Codec Text Nat)
     (def: (encode value)
       (loop [input value
              output ""]
         (let [digit (maybe.assume (<to-character> (n/% <base> input)))
               output' ("lux text concat" digit output)
               input' (n// <base> input)]
           (if (n/= 0 input')
             output'
             (recur input' output')))))

     (def: (decode repr)
       (let [input-size ("lux text size" repr)]
         (if (n/> 0 input-size)
           (loop [idx 0
                  output 0]
             (if (n/< input-size idx)
               (let [digit (maybe.assume (get-char repr idx))]
                 (case (<to-value> digit)
                   #.None
                   (#error.Error ("lux text concat" <error> repr))

                   (#.Some digit-value)
                   (recur (inc idx)
                          (|> output (n/* <base>) (n/+ digit-value)))))
               (#error.Success output)))
           (#error.Error ("lux text concat" <error> repr))))))]

  [Binary@Codec<Text,Nat> 2  binary-character      binary-value      "Invalid binary syntax for Nat: "]
  [Octal@Codec<Text,Nat>  8  octal-character       octal-value       "Invalid octal syntax for Nat: "]
  [_                      10 decimal-character     decimal-value     "Invalid syntax for Nat: "]
  [Hex@Codec<Text,Nat>    16 hexadecimal-character hexadecimal-value "Invalid hexadecimal syntax for Nat: "]
  )

(def: (int/sign!! value)
  (-> Int Text)
  (if (i/< +0 value)
    "-"
    "+"))

(def: (int/sign?? representation)
  (-> Text (Maybe Int))
  (case (get-char representation 0)
    (^ (#.Some "-"))
    (#.Some -1)

    (^ (#.Some "+"))
    (#.Some +1)

    _
    #.None))

(def: (int-decode-loop input-size repr sign <base> <to-value> <error>)
  (-> Nat Text Int Int (-> Text (Maybe Nat)) Text (Error Int))
  (loop [idx 1
         output +0]
    (if (n/< input-size idx)
      (let [digit (maybe.assume (get-char repr idx))]
        (case (<to-value> digit)
          #.None
          (#error.Error <error>)

          (#.Some digit-value)
          (recur (inc idx)
                 (|> output (i/* <base>) (i/+ (.int digit-value))))))
      (#error.Success (i/* sign output)))))

(do-template [<struct> <base> <to-character> <to-value> <error>]
  [(structure: #export <struct> (Codec Text Int)
     (def: (encode value)
       (if (i/= +0 value)
         "+0"
         (loop [input (|> value (i// <base>) (:: Number<Int> abs))
                output (|> value (i/% <base>) (:: Number<Int> abs) .nat
                           <to-character>
                           maybe.assume)]
           (if (i/= +0 input)
             ("lux text concat" (int/sign!! value) output)
             (let [digit (maybe.assume (<to-character> (.nat (i/% <base> input))))]
               (recur (i// <base> input)
                      ("lux text concat" digit output)))))))

     (def: (decode repr)
       (let [input-size ("lux text size" repr)]
         (if (n/> 1 input-size)
           (case (int/sign?? repr)
             (#.Some sign)
             (int-decode-loop input-size repr sign <base> <to-value> <error>)

             #.None
             (#error.Error <error>))
           (#error.Error <error>)))))]

  [Binary@Codec<Text,Int> +2  binary-character      binary-value      "Invalid binary syntax for Int: "]
  [Octal@Codec<Text,Int>  +8  octal-character       octal-value       "Invalid octal syntax for Int: "]
  [_                      +10 decimal-character     decimal-value     "Invalid syntax for Int: "]
  [Hex@Codec<Text,Int>    +16 hexadecimal-character hexadecimal-value "Invalid hexadecimal syntax for Int: "]
  )

(def: (de-prefix input)
  (-> Text Text)
  (maybe.assume ("lux text clip" input 1 ("lux text size" input))))

(do-template [<struct> <nat> <char-bit-size> <error>]
  [(structure: #export <struct> (Codec Text Rev)
     (def: (encode value)
       (let [raw-output (de-prefix (:: <nat> encode (:coerce Nat value)))
             max-num-chars (n// <char-bit-size> 64)
             raw-size ("lux text size" raw-output)
             zero-padding (loop [zeroes-left (n/- raw-size max-num-chars)
                                 output ""]
                            (if (n/= 0 zeroes-left)
                              output
                              (recur (dec zeroes-left)
                                     ("lux text concat" "0" output))))
             padded-output ("lux text concat" zero-padding raw-output)]
         ("lux text concat" "." padded-output)))

     (def: (decode repr)
       (let [repr-size ("lux text size" repr)]
         (if (n/>= 2 repr-size)
           (case ("lux text char" repr 0)
             (^multi (^ (#.Some (char ".")))
                     [(:: <nat> decode (de-prefix repr))
                      (#error.Success output)])
             (#error.Success (:coerce Rev output))

             _
             (#error.Error ("lux text concat" <error> repr)))
           (#error.Error ("lux text concat" <error> repr))))))]

  [Binary@Codec<Text,Rev> Binary@Codec<Text,Nat> 1 "Invalid binary syntax: "]
  [Octal@Codec<Text,Rev>  Octal@Codec<Text,Nat>  3 "Invalid octal syntax: "]
  [Hex@Codec<Text,Rev>    Hex@Codec<Text,Nat>    4 "Invalid hexadecimal syntax: "]
  )

(do-template [<struct> <int> <base> <char-set> <error>]
  [(structure: #export <struct> (Codec Text Frac)
     (def: (encode value)
       (let [whole (frac-to-int value)
             whole-part (:: <int> encode whole)
             decimal (:: Number<Frac> abs (f/% +1.0 value))
             decimal-part (if (f/= +0.0 decimal)
                            ".0"
                            (loop [dec-left decimal
                                   output ""]
                              (if (f/= +0.0 dec-left)
                                ("lux text concat" "." output)
                                (let [shifted (f/* <base> dec-left)
                                      digit (|> shifted (f/% <base>) frac-to-int .nat
                                                (get-char <char-set>) maybe.assume)]
                                  (recur (f/% +1.0 shifted)
                                         ("lux text concat" output digit))))))]
         ("lux text concat" whole-part decimal-part)))

     (def: (decode repr)
       (case ("lux text index" repr "." 0)
         (#.Some split-index)
         (let [whole-part (maybe.assume ("lux text clip" repr 0 split-index))
               decimal-part (maybe.assume ("lux text clip" repr (inc split-index) ("lux text size" repr)))]
           (case [(:: <int> decode whole-part)
                  (:: <int> decode decimal-part)]
             (^multi [(#error.Success whole) (#error.Success decimal)]
                     (i/>= +0 decimal))
             (let [sign (if (i/< +0 whole)
                          -1.0
                          +1.0)
                   div-power (loop [muls-left ("lux text size" decimal-part)
                                    output +1.0]
                               (if (n/= 0 muls-left)
                                 output
                                 (recur (dec muls-left)
                                        (f/* <base> output))))
                   adjusted-decimal (|> decimal int-to-frac (f// div-power))
                   dec-rev (case (:: Hex@Codec<Text,Rev> decode ("lux text concat" "." decimal-part))
                             (#error.Success dec-rev)
                             dec-rev

                             (#error.Error error)
                             (error! error))]
               (#error.Success (f/+ (int-to-frac whole)
                                    (f/* sign adjusted-decimal))))

             _
             (#error.Error ("lux text concat" <error> repr))))

         _
         (#error.Error ("lux text concat" <error> repr)))))]

  [Binary@Codec<Text,Frac> Binary@Codec<Text,Int> +2.0 "01" "Invalid binary syntax: "]
  )

(def: (segment-digits chunk-size digits)
  (-> Nat Text (List Text))
  (case digits
    ""
    (list)

    _
    (let [num-digits ("lux text size" digits)]
      (if (n/<= chunk-size num-digits)
        (list digits)
        (let [boundary (n/- chunk-size num-digits)
              chunk (maybe.assume ("lux text clip" digits boundary num-digits))
              remaining (maybe.assume ("lux text clip" digits 0 boundary))]
          (list& chunk (segment-digits chunk-size remaining)))))))

(def: (bin-segment-to-hex input)
  (-> Text Text)
  (case input
    "0000" "0"
    "0001" "1"
    "0010" "2"
    "0011" "3"
    "0100" "4"
    "0101" "5"
    "0110" "6"
    "0111" "7"
    "1000" "8"
    "1001" "9"
    "1010" "A"
    "1011" "B"
    "1100" "C"
    "1101" "D"
    "1110" "E"
    "1111" "F"
    _ (undefined)))

(def: (hex-segment-to-bin input)
  (-> Text Text)
  (case input
    "0" "0000"
    "1" "0001"
    "2" "0010"
    "3" "0011"
    "4" "0100"
    "5" "0101"
    "6" "0110"
    "7" "0111"
    "8" "1000"
    "9" "1001"
    (^or "a" "A") "1010"
    (^or "b" "B") "1011"
    (^or "c" "C") "1100"
    (^or "d" "D") "1101"
    (^or "e" "E") "1110"
    (^or "f" "F") "1111"
    _ (undefined)))

(def: (bin-segment-to-octal input)
  (-> Text Text)
  (case input
    "000" "0"
    "001" "1"
    "010" "2"
    "011" "3"
    "100" "4"
    "101" "5"
    "110" "6"
    "111" "7"
    _ (undefined)))

(def: (octal-segment-to-bin input)
  (-> Text Text)
  (case input
    "0" "000"
    "1" "001"
    "2" "010"
    "3" "011"
    "4" "100"
    "5" "101"
    "6" "110"
    "7" "111"
    _ (undefined)))

(def: (map f xs)
  (All [a b] (-> (-> a b) (List a) (List b)))
  (case xs
    #.Nil
    #.Nil
    
    (#.Cons x xs')
    (#.Cons (f x) (map f xs'))))

(def: (re-join-chunks xs)
  (-> (List Text) Text)
  (case xs
    #.Nil
    ""

    (#.Cons x xs')
    ("lux text concat" x (re-join-chunks xs'))))

(do-template [<from> <from-translator> <to> <to-translator> <base-bits>]
  [(def: (<from> on-left? input)
     (-> Bit Text Text)
     (let [max-num-chars (n// <base-bits> 64)
           input-size ("lux text size" input)
           zero-padding (let [num-digits-that-need-padding (n/% <base-bits> input-size)]
                          (if (n/= 0 num-digits-that-need-padding)
                            ""
                            (loop [zeroes-left (n/- num-digits-that-need-padding
                                                    <base-bits>)
                                   output ""]
                              (if (n/= 0 zeroes-left)
                                output
                                (recur (dec zeroes-left)
                                       ("lux text concat" "0" output))))))
           padded-input (if on-left?
                          ("lux text concat" zero-padding input)
                          ("lux text concat" input zero-padding))]
       (|> padded-input
           (segment-digits <base-bits>)
           (map <from-translator>)
           re-join-chunks)))

   (def: <to>
     (-> Text Text)
     (|>> (segment-digits 1)
          (map <to-translator>)
          re-join-chunks))]

  [binary-to-hex   bin-segment-to-hex   hex-to-binary   hex-segment-to-bin   4]
  [binary-to-octal bin-segment-to-octal octal-to-binary octal-segment-to-bin 3]
  )

(do-template [<struct> <error> <from> <to>]
  [(structure: #export <struct> (Codec Text Frac)
     (def: (encode value)
       (let [sign (:: Number<Frac> signum value)
             raw-bin (:: Binary@Codec<Text,Frac> encode value)
             dot-idx (maybe.assume ("lux text index" raw-bin "." 0))
             whole-part (maybe.assume ("lux text clip" raw-bin
                                       (if (f/= -1.0 sign) 1 0)
                                       dot-idx))
             decimal-part (maybe.assume ("lux text clip" raw-bin (inc dot-idx) ("lux text size" raw-bin)))
             hex-output (|> (<from> #0 decimal-part)
                            ("lux text concat" ".")
                            ("lux text concat" (<from> #1 whole-part))
                            ("lux text concat" (if (f/= -1.0 sign) "-" "")))]
         hex-output))

     (def: (decode repr)
       (let [sign (case ("lux text index" repr "-" 0)
                    (#.Some 0)
                    -1.0

                    _
                    +1.0)]
         (case ("lux text index" repr "." 0)
           (#.Some split-index)
           (let [whole-part (maybe.assume ("lux text clip" repr (if (f/= -1.0 sign) 1 0) split-index))
                 decimal-part (maybe.assume ("lux text clip" repr (inc split-index) ("lux text size" repr)))
                 as-binary (|> (<to> decimal-part)
                               ("lux text concat" ".")
                               ("lux text concat" (<to> whole-part))
                               ("lux text concat" (if (f/= -1.0 sign) "-" "")))]
             (case (:: Binary@Codec<Text,Frac> decode as-binary)
               (#error.Error _)
               (#error.Error ("lux text concat" <error> repr))

               output
               output))

           _
           (#error.Error ("lux text concat" <error> repr))))))]

  [Octal@Codec<Text,Frac> "Invalid octaladecimal syntax: " binary-to-octal octal-to-binary]
  [Hex@Codec<Text,Frac>   "Invalid hexadecimal syntax: "   binary-to-hex   hex-to-binary]
  )

(macro: (encoding-doc tokens state)
  (case tokens
    (^ (list [cursor (#.Text encoding)] example-1 example-2))
    (let [encoding ($_ "lux text concat"
                       "Given syntax for a "
                       encoding
                       " number, generates a Nat, an Int, a Rev or a Frac.")
          underscore "Allows for the presence of underscore in the numbers."
          description [cursor (#.Text ($_ "lux text concat"
                                          encoding "\n"
                                          underscore))]]
      (#error.Success [state (list (` (doc (~ description)
                                           (~ example-1)
                                           (~ example-2))))]))

    _
    (#error.Error "Wrong syntax for \"encoding-doc\".")))

(def: (underscore-prefixed? number)
  (-> Text Bit)
  (case ("lux text index" number "_" 0)
    (#.Some 0)
    #1

    _
    #0))

(def: clean-underscores
  (-> Text Text)
  (text.replace-all "_" ""))

(do-template [<macro> <nat> <int> <rev> <frac> <error> <doc>]
  [(macro: #export (<macro> tokens state)
     {#.doc <doc>}
     (case tokens
       (#.Cons [meta (#.Text repr')] #.Nil)
       (if (underscore-prefixed? repr')
         (#error.Error <error>)
         (let [repr (clean-underscores repr')]
           (case (:: <nat> decode repr)
             (#error.Success value)
             (#error.Success [state (list [meta (#.Nat value)])])

             (^multi (#error.Error _)
                     [(:: <int> decode repr) (#error.Success value)])
             (#error.Success [state (list [meta (#.Int value)])])

             (^multi (#error.Error _)
                     [(:: <rev> decode repr) (#error.Success value)])
             (#error.Success [state (list [meta (#.Rev value)])])

             (^multi (#error.Error _)
                     [(:: <frac> decode repr) (#error.Success value)])
             (#error.Success [state (list [meta (#.Frac value)])])

             _
             (#error.Error <error>))))

       _
       (#error.Error <error>)))]

  [bin Binary@Codec<Text,Nat> Binary@Codec<Text,Int> Binary@Codec<Text,Rev> Binary@Codec<Text,Frac>
   "Invalid binary syntax."
   (encoding-doc "binary" (bin "+11001001") (bin "+11_00_10_01"))]
  [oct Octal@Codec<Text,Nat>  Octal@Codec<Text,Int>  Octal@Codec<Text,Rev>  Octal@Codec<Text,Frac>
   "Invalid octal syntax."
   (encoding-doc "octal" (oct "+615243") (oct "+615_243"))]
  [hex Hex@Codec<Text,Nat>    Hex@Codec<Text,Int>    Hex@Codec<Text,Rev>    Hex@Codec<Text,Frac>
   "Invalid hexadecimal syntax."
   (encoding-doc "hexadecimal" (hex "deadBEEF") (hex "dead_BEEF"))]
  )

## The following code allows one to encode/decode Rev numbers as text.
## This is not a simple algorithm, and it requires subverting the Rev
## abstraction a bit.
## It takes into account the fact that Rev numbers are represented by
## Lux as 64-bit integers.
## A valid way to model them is as Lux's Nat type.
## This is a somewhat hackish way to do things, but it allows one to
## write the encoding/decoding algorithm once, in pure Lux, rather
## than having to implement it on the compiler for every platform
## targeted by Lux.
(type: Digits (Array Nat))

(def: (make-digits _)
  (-> Any Digits)
  ("lux array new" i64.width))

(def: (digits-get idx digits)
  (-> Nat Digits Nat)
  (maybe.default 0 ("lux array get" digits idx)))

(def: (digits-put idx digit digits)
  (-> Nat Nat Digits Digits)
  ("lux array put" digits idx digit))

(def: (prepend left right)
  (-> Text Text Text)
  ("lux text concat" left right))

(def: (digits-times-5! idx output)
  (-> Nat Digits Digits)
  (loop [idx idx
         carry 0
         output output]
    (if (i/>= +0 (:coerce Int idx))
      (let [raw (|> (digits-get idx output)
                    (n/* 5)
                    (n/+ carry))]
        (recur (dec idx)
               (n// 10 raw)
               (digits-put idx (n/% 10 raw) output)))
      output)))

(def: (digits-power power)
  (-> Nat Digits)
  (loop [times power
         output (|> (make-digits [])
                    (digits-put power 1))]
    (if (i/>= +0 (:coerce Int times))
      (recur (dec times)
             (digits-times-5! power output))
      output)))

(def: (digits-to-text digits)
  (-> Digits Text)
  (loop [idx (dec i64.width)
         all-zeroes? #1
         output ""]
    (if (i/>= +0 (:coerce Int idx))
      (let [digit (digits-get idx digits)]
        (if (and (n/= 0 digit)
                 all-zeroes?)
          (recur (dec idx) #1 output)
          (recur (dec idx)
                 #0
                 ("lux text concat"
                  (:: Codec<Text,Int> encode (:coerce Int digit))
                  output))))
      (if all-zeroes?
        "0"
        output))))

(def: (digits-add param subject)
  (-> Digits Digits Digits)
  (loop [idx (dec i64.width)
         carry 0
         output (make-digits [])]
    (if (i/>= +0 (:coerce Int idx))
      (let [raw ($_ n/+
                    carry
                    (digits-get idx param)
                    (digits-get idx subject))]
        (recur (dec idx)
               (n// 10 raw)
               (digits-put idx (n/% 10 raw) output)))
      output)))

(def: (text-to-digits input)
  (-> Text (Maybe Digits))
  (let [length ("lux text size" input)]
    (if (n/<= i64.width length)
      (loop [idx 0
             output (make-digits [])]
        (if (n/< length idx)
          (let [char (maybe.assume (get-char input idx))]
            (case ("lux text index" "+0123456789" char 0)
              #.None
              #.None

              (#.Some digit)
              (recur (inc idx)
                     (digits-put idx digit output))))
          (#.Some output)))
      #.None)))

(def: (digits-lt param subject)
  (-> Digits Digits Bit)
  (loop [idx 0]
    (and (n/< i64.width idx)
         (let [pd (digits-get idx param)
               sd (digits-get idx subject)]
           (if (n/= pd sd)
             (recur (inc idx))
             (n/< pd sd))))))

(def: (digits-sub-once! idx param subject)
  (-> Nat Nat Digits Digits)
  (let [sd (digits-get idx subject)]
    (if (n/>= param sd)
      (digits-put idx (n/- param sd) subject)
      (let [diff (|> sd
                     (n/+ 10)
                     (n/- param))]
        (|> subject
            (digits-put idx diff)
            (digits-sub-once! (dec idx) 1))))))

(def: (digits-sub! param subject)
  (-> Digits Digits Digits)
  (loop [idx (dec i64.width)
         output subject]
    (if (i/>= +0 (.int idx))
      (recur (dec idx)
             (digits-sub-once! idx (digits-get idx param) output))
      output)))

(structure: #export _ (Codec Text Rev)
  (def: (encode input)
    (let [input (:coerce Nat input)
          last-idx (dec i64.width)]
      (if (n/= 0 input)
        ".0"
        (loop [idx last-idx
               digits (make-digits [])]
          (if (i/>= +0 (:coerce Int idx))
            (if (i64.set? idx input)
              (let [digits' (digits-add (digits-power (n/- idx last-idx))
                                        digits)]
                (recur (dec idx)
                       digits'))
              (recur (dec idx)
                     digits))
            ("lux text concat" "." (digits-to-text digits))
            )))))

  (def: (decode input)
    (let [length ("lux text size" input)
          dotted? (case ("lux text index" input "." 0)
                    (#.Some 0)
                    #1

                    _
                    #0)]
      (if (and dotted?
               (n/<= (inc i64.width) length))
        (case (|> ("lux text clip" input 1 length)
                  maybe.assume
                  text-to-digits)
          (#.Some digits)
          (loop [digits digits
                 idx 0
                 output 0]
            (if (n/< i64.width idx)
              (let [power (digits-power idx)]
                (if (digits-lt power digits)
                  ## Skip power
                  (recur digits (inc idx) output)
                  (recur (digits-sub! power digits)
                         (inc idx)
                         (i64.set (n/- idx (dec i64.width)) output))))
              (#error.Success (:coerce Rev output))))

          #.None
          (#error.Error ("lux text concat" "Wrong syntax for Rev: " input)))
        (#error.Error ("lux text concat" "Wrong syntax for Rev: " input))))
    ))

(def: (log2 input)
  (-> Frac Frac)
  (f// ("lux math log" +2.0)
       ("lux math log" input)))

(def: double-bias Nat 1023)

(def: mantissa-size Nat 52)
(def: exponent-size Nat 11)

(def: #export (frac-to-bits input)
  (-> Frac I64)
  (i64 (cond (not-a-number? input)
             (hex "7FF7FFFFFFFFFFFF")

             (f/= positive-infinity input)
             (hex "7FF0000000000000")

             (f/= negative-infinity input)
             (hex "FFF0000000000000")

             (f/= +0.0 input)
             (let [reciprocal (f// input +1.0)]
               (if (f/= positive-infinity reciprocal)
                 ## Positive zero
                 (hex "0000000000000000")
                 ## Negative zero
                 (hex "8000000000000000")))

             ## else
             (let [sign (:: Number<Frac> signum input)
                   input (:: Number<Frac> abs input)
                   exponent ("lux math floor" (log2 input))
                   exponent-mask (|> 1 (i64.left-shift exponent-size) dec) 
                   mantissa (|> input
                                ## Normalize
                                (f// ("lux math pow" +2.0 exponent))
                                ## Make it int-equivalent
                                (f/* ("lux math pow" +2.0 +52.0)))
                   sign-bit (if (f/= -1.0 sign) 1 0)
                   exponent-bits (|> exponent frac-to-int .nat (n/+ double-bias) (i64.and exponent-mask))
                   mantissa-bits (|> mantissa frac-to-int .nat)]
               ($_ i64.or
                   (i64.left-shift 63 sign-bit)
                   (i64.left-shift mantissa-size exponent-bits)
                   (i64.clear mantissa-size mantissa-bits)))
             )))

(do-template [<getter> <mask> <size> <offset>]
  [(def: <mask> (|> 1 (i64.left-shift <size>) dec (i64.left-shift <offset>)))
   (def: (<getter> input)
     (-> (I64 Any) I64)
     (|> input (i64.and <mask>) (i64.logical-right-shift <offset>) i64))]

  [mantissa mantissa-mask mantissa-size 0]
  [exponent exponent-mask exponent-size mantissa-size]
  [sign     sign-mask     1            (n/+ exponent-size mantissa-size)]
  )

(def: #export (bits-to-frac input)
  (-> (I64 Any) Frac)
  (let [S (sign input)
        E (exponent input)
        M (mantissa input)]
    (cond (n/= (hex "7FF") E)
          (if (n/= 0 M)
            (if (n/= 0 S)
              positive-infinity
              negative-infinity)
            not-a-number)

          (and (n/= 0 E) (n/= 0 M))
          (if (n/= 0 S)
            +0.0
            (f/* -1.0 +0.0))

          ## else
          (let [normalized (|> M (i64.set mantissa-size)
                               .int int-to-frac
                               (f// ("lux math pow" +2.0 +52.0)))
                power (|> E (n/- double-bias)
                          .int int-to-frac
                          ("lux math pow" +2.0))
                shifted (f/* power
                             normalized)]
            (if (n/= 0 S)
              shifted
              (f/* -1.0 shifted))))))

## [Hash]
(structure: #export _ (Hash Nat)
  (def: eq Equivalence<Nat>)
  (def: hash id))

(structure: #export _ (Hash Int)
  (def: eq Equivalence<Int>)
  (def: hash .nat))

(structure: #export _ (Hash Frac)
  (def: eq Equivalence<Frac>)
  
  (def: hash frac-to-bits))

(structure: #export _ (Hash Rev)
  (def: eq Equivalence<Rev>)
  (def: hash (|>> (:coerce Nat))))