doc-next-gen

Init.Data.ToString.Basic

Module docstring

{}

ToString structure
(α : Type u)
Full source
/--
Types that can be converted into a string for display.

There is no expectation that the resulting string can be parsed back to the original data (see
`Repr` for a similar class with this expectation).
-/
class ToString (α : Type u) where
  /-- Converts a value into a string. -/
  toString : α → String
String Conversion Type
Informal description
A structure for types that can be converted into a string representation for display purposes. There is no requirement that the string can be parsed back to the original data (unlike the `Repr` class which has this expectation).
instToStringId instance
{α} [ToString α] : ToString (id α)
Full source
instance {α} [ToString α] : ToString (id α) :=
  inferInstanceAs (ToString α)
String Representation of Identity Type
Informal description
For any type $\alpha$ with a string representation, the identity function $\mathrm{id} \alpha$ (which is just $\alpha$ itself) also has a string representation.
instToStringId_1 instance
{α} [ToString α] : ToString (Id α)
Full source
instance {α} [ToString α] : ToString (Id α) :=
  inferInstanceAs (ToString α)
String Representation of Identity Types
Informal description
For any type $\alpha$ with a string representation, the identity type `Id α` also has a string representation.
instToStringString instance
: ToString String
Full source
instance : ToString String :=
  ⟨fun s => s⟩
String Representation of Strings
Informal description
The type `String` has a canonical string representation.
instToStringBool instance
: ToString Bool
Full source
instance : ToString Bool :=
  ⟨fun b => cond b "true" "false"⟩
String Representation of Boolean Values
Informal description
The Boolean type `Bool` has a canonical string representation, where `true` is converted to the string `"true"` and `false` is converted to the string `"false"`.
List.toString definition
[ToString α] : List α → String
Full source
/--
Converts a list into a string, using `ToString.toString` to convert its elements.

The resulting string resembles list literal syntax, with the elements separated by `", "` and
enclosed in square brackets.

The resulting string may not be valid Lean syntax, because there's no such expectation for
`ToString` instances.

Examples:
* `[1, 2, 3].toString = "[1, 2, 3]"`
* `["cat", "dog"].toString = "[cat, dog]"`
* `["cat", "dog", ""].toString = "[cat, dog, ]"`
-/
protected def List.toString [ToString α] : List α → String
  | [] => "[]"
  | [x] => "[" ++ toString x ++ "]"
  | x::xs => xs.foldl (· ++ ", " ++ toString ·) ("[" ++ toString x) |>.push ']'
String representation of a list
Informal description
The function converts a list of elements of type $\alpha$ (where each element can be converted to a string via `ToString`) into a string representation resembling list literal syntax. The elements are separated by `", "` and enclosed in square brackets. For example: - The list `[1, 2, 3]` is converted to `"[1, 2, 3]"` - The list `["cat", "dog"]` is converted to `"[cat, dog]"` - The list `["cat", "dog", ""]` is converted to `"[cat, dog, ]"`
instToStringList instance
{α : Type u} [ToString α] : ToString (List α)
Full source
instance {α : Type u} [ToString α] : ToString (List α) :=
  ⟨List.toString⟩
String Representation of Lists
Informal description
For any type $\alpha$ with a string representation, the type `List α` of lists of elements of type $\alpha$ also has a string representation. The string representation of a list is obtained by converting each element to a string, separating them with commas, and enclosing the result in square brackets.
instToStringPUnit instance
: ToString PUnit.{u + 1}
Full source
instance : ToString PUnitPUnit.{u+1} :=
  ⟨fun _ => "()"⟩
String Representation of the Polymorphic Unit Type
Informal description
The universe-polymorphic unit type `PUnit` has a string representation.
instToStringULift instance
{α : Type u} [ToString α] : ToString (ULift.{v} α)
Full source
instance {α : Type u} [ToString α] : ToString (ULift.{v} α) :=
  ⟨fun v => toString v.1⟩
String Representation of Universe-Lifted Types
Informal description
For any type $\alpha$ with a string representation, the universe-lifted type $\text{ULift}.\{\nu\} \alpha$ also has a string representation.
instToStringUnit instance
: ToString Unit
Full source
instance : ToString Unit :=
  ⟨fun _ => "()"⟩
String Representation of the Unit Type
Informal description
The unit type `Unit` has a string representation.
instToStringNat instance
: ToString Nat
Full source
instance : ToString Nat :=
  ⟨fun n => Nat.repr n⟩
String Representation of Natural Numbers
Informal description
The natural numbers $\mathbb{N}$ have a string representation.
instToStringPos instance
: ToString String.Pos
Full source
instance : ToString String.Pos :=
  ⟨fun p => Nat.repr p.byteIdx⟩
String Representation of Byte Positions in UTF-8 Strings
Informal description
The type `String.Pos`, representing a byte position in a UTF-8 encoded string, can be converted to a string representation.
instToStringInt instance
: ToString Int
Full source
instance : ToString Int where
  toString
    | Int.ofNat m   => toString m
    | Int.negSucc m => "-" ++ toString (succ m)
String Representation of Integers
Informal description
The integers $\mathbb{Z}$ have a string representation.
instToStringChar instance
: ToString Char
Full source
instance : ToString Char :=
  ⟨fun c => c.toString⟩
String Representation of Unicode Characters
Informal description
Every Unicode character can be converted to a string representation.
instToStringFin instance
(n : Nat) : ToString (Fin n)
Full source
instance (n : Nat) : ToString (Fin n) :=
  ⟨fun f => toString (Fin.val f)⟩
String Representation for Finite Natural Numbers
Informal description
For any natural number $n$, the finite type $\mathrm{Fin}\,n$ of natural numbers less than $n$ has a string representation.
instToStringUSize instance
: ToString USize
Full source
instance : ToString USize :=
  ⟨fun n => toString n.toNat⟩
String Representation of Word-Sized Unsigned Integers
Informal description
The platform-dependent unsigned word-size integers `USize` have a string representation.
instToStringFormat instance
: ToString Format
Full source
instance : ToString Format where
  toString f := f.pretty
String Representation of Format Objects
Informal description
The type `Format` can be converted to a string representation.
addParenHeuristic definition
(s : String) : String
Full source
def addParenHeuristic (s : String) : String :=
  if "(".isPrefixOf s || "[".isPrefixOf s || "{".isPrefixOf s || "#[".isPrefixOf s then s
  else if !s.any Char.isWhitespace then s
  else "(" ++ s ++ ")"
Parentheses addition heuristic for strings
Informal description
The function takes a string `s` and adds parentheses around it if the string contains whitespace and does not already start with a parenthesis, bracket, or brace. Specifically: 1. If `s` starts with `(`, `[`, `{`, or `#[`, it returns `s` unchanged. 2. If `s` contains no whitespace characters, it returns `s` unchanged. 3. Otherwise, it returns `s` enclosed in parentheses, i.e., `(s)`.
instToStringOption instance
{α : Type u} [ToString α] : ToString (Option α)
Full source
instance {α : Type u} [ToString α] : ToString (Option α) := ⟨fun
  | none => "none"
  | (some a) => "(some " ++ addParenHeuristic (toString a) ++ ")"⟩
String Representation of Optional Values
Informal description
For any type $\alpha$ with a string representation, the optional type `Option α` also has a string representation. Specifically: - The string representation of `none` is `"none"`. - The string representation of `some x` is the string representation of `x` enclosed in parentheses if it contains whitespace, otherwise it is just the string representation of `x`.
instToStringSum instance
{α : Type u} {β : Type v} [ToString α] [ToString β] : ToString (Sum α β)
Full source
instance {α : Type u} {β : Type v} [ToString α] [ToString β] : ToString (Sum α β) := ⟨fun
  | (inl a) => "(inl " ++ addParenHeuristic (toString a) ++ ")"
  | (inr b) => "(inr " ++ addParenHeuristic (toString b) ++ ")"⟩
String Representation of Sum Types
Informal description
For any types $\alpha$ and $\beta$ with string representations, the sum type $\alpha \oplus \beta$ also has a string representation. Specifically, elements of the form $\text{inl}(a)$ for $a \in \alpha$ are converted to the string representation of $a$ prefixed with "inl ", and elements of the form $\text{inr}(b)$ for $b \in \beta$ are converted to the string representation of $b$ prefixed with "inr ".
instToStringSigma instance
{α : Type u} {β : α → Type v} [ToString α] [∀ x, ToString (β x)] : ToString (Sigma β)
Full source
instance {α : Type u} {β : α → Type v} [ToString α] [∀ x, ToString (β x)] : ToString (Sigma β) := ⟨fun ⟨a, b⟩ =>
  "⟨"  ++ toString a ++ ", " ++ toString b ++ "⟩"⟩
String Representation of Dependent Sum Types
Informal description
For any type $\alpha$ and type-valued function $\beta$ on $\alpha$, if both $\alpha$ and each $\beta x$ have string representations, then the dependent sum type $\Sigma x : \alpha, \beta x$ also has a string representation.
instToStringSubtype instance
{α : Type u} {p : α → Prop} [ToString α] : ToString (Subtype p)
Full source
instance {α : Type u} {p : α → Prop} [ToString α] : ToString (Subtype p) := ⟨fun s =>
  toString (val s)⟩
String Representation of Subtypes
Informal description
For any type $\alpha$ with a predicate $p : \alpha \to \text{Prop}$, if $\alpha$ has a string representation (i.e., an instance of `ToString α`), then the subtype $\{x : \alpha \mid p x\}$ also has a string representation.
String.toInt? definition
(s : String) : Option Int
Full source
/--
Interprets a string as the decimal representation of an integer, returning it. Returns `none` if the
string does not contain a decimal integer.

A string can be interpreted as a decimal integer if it is not empty, its first character is either
`'-'` or a digit, and all remaining characters are digits.

Use `String.isInt` to check whether `String.toInt?` would return `some`. `String.toInt!` is an
alternative that panics instead of returning `none` when the string is not an integer.

Examples:
 * `"".toInt? = none`
 * `"0".toInt? = some 0`
 * `"5".toInt? = some 5`
 * `"-5".toInt? = some (-5)`
 * `"587".toInt? = some 587`
 * `"-587".toInt? = some (-587)`
 * `" 5".toInt? = none`
 * `"2-3".toInt? = none`
 * `"0xff".toInt? = none`
-/
def String.toInt? (s : String) : Option Int := do
  if s.get 0 = '-' then do
    let v ← (s.toSubstring.drop 1).toNat?;
    pure <| - Int.ofNat v
  else
   Int.ofNat <$> s.toNat?
String to integer conversion (optional)
Informal description
The function interprets a string \( s \) as a decimal integer, returning `some n` if \( s \) represents a valid integer \( n \), and `none` otherwise. A string is valid if it is non-empty, starts with either a digit or '-', and all remaining characters are digits.
String.isInt definition
(s : String) : Bool
Full source
/--
Checks whether the string can be interpreted as the decimal representation of an integer.

A string can be interpreted as a decimal integer if it is not empty, its first character is
`'-'` or a digit, and all subsequent characters are digits. Leading `+` characters are not allowed.

Use `String.toInt?` or `String.toInt!` to convert such a string to an integer.

Examples:
 * `"".isInt = false`
 * `"0".isInt = true`
 * `"-0".isInt = true`
 * `"5".isInt = true`
 * `"587".isInt = true`
 * `"-587".isInt = true`
 * `"+587".isInt = false`
 * `" 5".isInt = false`
 * `"2-3".isInt = false`
 * `"0xff".isInt = false`
-/
def String.isInt (s : String) : Bool :=
  if s.get 0 = '-' then
    (s.toSubstring.drop 1).isNat
  else
    s.isNat
Check if string is a decimal integer
Informal description
A function that checks whether a string \( s \) can be interpreted as a decimal integer. The string must satisfy the following conditions: 1. It is non-empty. 2. Its first character is either `'-'` or a digit. 3. All subsequent characters are digits (leading `'+'` characters are not allowed). The function returns `true` if all conditions are met, and `false` otherwise.
String.toInt! definition
(s : String) : Int
Full source
/--
Interprets a string as the decimal representation of an integer, returning it. Panics if the string
does not contain a decimal integer.

A string can be interpreted as a decimal integer if it is not empty, its first character is `'-'` or
a digit, and all remaining characters are digits.

Use `String.isInt` to check whether `String.toInt!` would return a value. `String.toInt?` is a safer
alternative that returns `none` instead of panicking when the string is not an integer.

Examples:
 * `"0".toInt! = 0`
 * `"5".toInt! = 5`
 * `"587".toInt! = 587`
 * `"-587".toInt! = -587`
-/
def String.toInt! (s : String) : Int :=
  match s.toInt? with
  | somesome v => v
  | none   => panic "Int expected"
String to integer conversion (panicking)
Informal description
The function interprets a string \( s \) as a decimal integer and returns the corresponding integer. It panics (raises an error) if the string does not represent a valid decimal integer. A string is considered valid if it is non-empty, starts with either a digit or '-', and all remaining characters are digits. Examples: - \( \texttt{"0".toInt!} = 0 \) - \( \texttt{"5".toInt!} = 5 \) - \( \texttt{"587".toInt!} = 587 \) - \( \texttt{"-587".toInt!} = -587 \)
instToStringExcept instance
[ToString ε] [ToString α] : ToString (Except ε α)
Full source
instance [ToString ε] [ToString α] : ToString (Except ε α) where
  toString
    | Except.error e => "error: " ++ toString e
    | Except.ok a    => "ok: " ++ toString a
String Conversion for Exceptional Results
Informal description
For any types $\varepsilon$ and $\alpha$ that can be converted to strings, the type `Except ε α` can also be converted to a string.
instReprExcept instance
[Repr ε] [Repr α] : Repr (Except ε α)
Full source
instance [Repr ε] [Repr α] : Repr (Except ε α) where
  reprPrec
    | Except.error e, prec => Repr.addAppParen ("Except.error " ++ reprArg e) prec
    | Except.ok a, prec    => Repr.addAppParen ("Except.ok " ++ reprArg a) prec
Representation Format for Exceptional Results
Informal description
For any types $\varepsilon$ and $\alpha$ that have a representation format, the type `Except ε α` also has a representation format. This means that values of type `Except ε α` (which can be either a value of type $\alpha$ or an error of type $\varepsilon$) can be formatted in a standard way.