Debian Codegraph @

src/Data/Nat/Show.agda

raw
1 ------------------------------------------------------------------------
2 -- The Agda standard library
3 --
4 -- Showing natural numbers
5 ------------------------------------------------------------------------
6
7 {-# OPTIONS --cubical-compatible --safe #-}
8
9 module Data.Nat.Show where
10
11 open import Data.Bool.Base using (_∧_)
12 open import Data.Char.Base as Char using (Char)
13 open import Data.Digit using (showDigit; toDigits; toNatDigits)
14 open import Data.List.Base as List using (List; []; _∷_)
15 open import Data.List.Effectful using (module TraversableA)
16 open import Data.Maybe.Base as Maybe using (Maybe; nothing; _<∣>_; when)
17 import Data.Maybe.Effectful as Maybe using (applicative)
18 open import Data.Nat using (ℕ; _≤?_; _<ᵇ_; _≤ᵇ_; _∸_; _*_; _+_)
19 open import Data.Product.Base using (proj₁)
20 open import Data.String.Base using (toList; fromList; String)
21 open import Function.Base using (_∘′_; _∘_)
22 open import Relation.Nullary.Decidable using (True)
23
24 ------------------------------------------------------------------------
25 -- Read
26
27 readMaybe : ∀ base {base≤16 : True (base ≤? 16)} → String → Maybe ℕ
28 readMaybe _ "" = nothing
29 readMaybe base = Maybe.map convert
30 ∘′ TraversableA.mapA Maybe.applicative readDigit
31 ∘′ toList
32
33 where
34
35 convert : List ℕ → ℕ
36 convert = List.foldl (λ acc d → base * acc + d) 0
37
38 char0 = Char.toℕ '0'
39 char9 = Char.toℕ '9'
40 chara = Char.toℕ 'a'
41 charf = Char.toℕ 'f'
42
43 readDigit : Char → Maybe ℕ
44 readDigit c = digit Maybe.>>= λ n → when (n <ᵇ base) n where
45
46 charc = Char.toℕ c
47
48 dec = when ((char0 ≤ᵇ charc) ∧ (charc ≤ᵇ char9)) (charc ∸ char0)
49 hex = when ((chara ≤ᵇ charc) ∧ (charc ≤ᵇ charf)) (10 + charc ∸ chara)
50 digit = dec <∣> hex
51
52 ------------------------------------------------------------------------
53 -- Show
54
55 -- Decimal notation
56 -- Time complexity is O(log₁₀(n))
57
58 toDigitChar : ℕ → Char
59 toDigitChar n = Char.fromℕ (n + Char.toℕ '0')
60
61 toDecimalChars : ℕ → List Char
62 toDecimalChars = List.map toDigitChar ∘′ toNatDigits 10
63
64 show : ℕ → String
65 show = fromList ∘′ toDecimalChars
66
67 -- Arbitrary base betwen 2 & 16.
68 -- Warning: when compiled the time complexity of `showInBase b n` is
69 -- O(n) instead of the expected O(log(n)).
70
71 charsInBase : (base : ℕ)
72 {base≥2 : True (2 ≤? base)}
73 {base≤16 : True (base ≤? 16)} →
74 ℕ → List Char
75 charsInBase base {base≥2} {base≤16} = List.map (showDigit {base≤16 = base≤16})
76 ∘ List.reverse
77 ∘ proj₁
78 ∘ toDigits base {base≥2 = base≥2}
79
80 showInBase : (base : ℕ)
81 {base≥2 : True (2 ≤? base)}
82 {base≤16 : True (base ≤? 16)} →
83 ℕ → String
84 showInBase base {base≥2} {base≤16} = fromList
85 ∘ charsInBase base {base≥2} {base≤16}