Debian Codegraph @

src/Data/String.agda

raw
1 ------------------------------------------------------------------------
2 -- The Agda standard library
3 --
4 -- Strings
5 ------------------------------------------------------------------------
6
7 {-# OPTIONS --cubical-compatible --safe #-}
8
9 module Data.String where
10
11 open import Data.Bool.Base using (if_then_else_)
12 open import Data.Char.Base as Char using (Char)
13 open import Function.Base using (_∘_; _$_)
14 open import Data.Nat.Base as ℕ using (ℕ)
15 import Data.Nat.Properties as ℕ
16 open import Data.List.Base as List using (List)
17 open import Data.List.Extrema ℕ.≤-totalOrder
18 open import Data.Vec.Base as Vec using (Vec)
19 open import Data.Char.Base as Char using (Char)
20 import Data.Char.Properties as Char using (_≟_)
21 open import Relation.Nullary.Decidable.Core using (does)
22
23 open import Data.List.Membership.DecPropositional Char._≟_
24
25
26 ------------------------------------------------------------------------
27 -- Re-export contents of base, and decidability of equality
28
29 open import Data.String.Base public
30 open import Data.String.Properties using (_≈?_; _≟_; _<?_; _==_) public
31
32 ------------------------------------------------------------------------
33 -- Conversion functions
34
35 toVec : (s : String) → Vec Char (length s)
36 toVec s = Vec.fromList (toList s)
37
38 fromVec : ∀ {n} → Vec Char n → String
39 fromVec = fromList ∘ Vec.toList
40
41
42 -- enclose string with parens if it contains a space character
43 parensIfSpace : String → String
44 parensIfSpace s = if does (' ' ∈? toList s) then parens s else s
45
46
47 ------------------------------------------------------------------------
48 -- Rectangle
49
50 -- Build a rectangular column by:
51 -- Given a vector of cells and a padding function for each one
52 -- Compute the max of the widths, and pad the strings accordingly.
53
54 rectangle : ∀ {n} → Vec (ℕ → String → String) n →
55 Vec String n → Vec String n
56 rectangle pads cells = Vec.zipWith (λ p c → p width c) pads cells where
57
58 sizes = List.map length (Vec.toList cells)
59 width = max 0 sizes
60
61 -- Special cases for left, center, and right alignment
62
63 rectangleˡ : ∀ {n} → Char → Vec String n → Vec String n
64 rectangleˡ c = rectangle (Vec.replicate _ $ padLeft c)
65
66 rectangleʳ : ∀ {n} → Char → Vec String n → Vec String n
67 rectangleʳ c = rectangle (Vec.replicate _ $ padRight c)
68
69 rectangleᶜ : ∀ {n} → Char → Char → Vec String n → Vec String n
70 rectangleᶜ cₗ cᵣ = rectangle (Vec.replicate _ $ padBoth cₗ cᵣ)