fact stringlengths 10 4.79k | type stringclasses 9 values | library stringclasses 44 values | imports listlengths 0 13 | filename stringclasses 718 values | symbolic_name stringlengths 1 76 | docstring stringlengths 10 64.6k ⌀ |
|---|---|---|---|---|---|---|
List.length : List α → Nat
| nil => 0
| cons _ as => HAdd.hAdd (length as) 1 | def | Init.Prelude | [] | Init/Prelude.lean | List.length | The length of a list.
This function is overridden in the compiler to `lengthTR`, which uses constant stack space.
Examples:
* `([] : List String).length = 0`
* `["green", "brown"].length = 2` |
List.lengthTRAux : List α → Nat → Nat
| nil, n => n
| cons _ as, n => lengthTRAux as (Nat.succ n) | def | Init.Prelude | [] | Init/Prelude.lean | List.lengthTRAux | Auxiliary function for `List.lengthTR`. |
List.lengthTR (as : List α) : Nat :=
lengthTRAux as 0 | def | Init.Prelude | [] | Init/Prelude.lean | List.lengthTR | The length of a list.
This is a tail-recursive version of `List.length`, used to implement `List.length` without running
out of stack space.
Examples:
* `([] : List String).lengthTR = 0`
* `["green", "brown"].lengthTR = 2` |
List.get {α : Type u} : (as : List α) → Fin as.length → α
| cons a _, ⟨0, _⟩ => a
| cons _ as, ⟨Nat.succ i, h⟩ => get as ⟨i, Nat.le_of_succ_le_succ h⟩ | def | Init.Prelude | [] | Init/Prelude.lean | List.get | Returns the element at the provided index, counting from `0`.
In other words, for `i : Fin as.length`, `as.get i` returns the `i`'th element of the list `as`.
Because the index is a `Fin` bounded by the list's length, the index will never be out of bounds.
Examples:
* `["spring", "summer", "fall", "winter"].get (2 : Fin 4) = "fall"`
* `["spring", "summer", "fall", "winter"].get (0 : Fin 4) = "spring"` |
List.set : (l : List α) → (n : Nat) → (a : α) → List α
| cons _ as, 0, b => cons b as
| cons a as, Nat.succ n, b => cons a (set as n b)
| nil, _, _ => nil | def | Init.Prelude | [] | Init/Prelude.lean | List.set | Replaces the value at (zero-based) index `n` in `l` with `a`. If the index is out of bounds, then
the list is returned unmodified.
Examples:
* `["water", "coffee", "soda", "juice"].set 1 "tea" = ["water", "tea", "soda", "juice"]`
* `["water", "coffee", "soda", "juice"].set 4 "tea" = ["water", "coffee", "soda", "juice"]` |
@[specialize]
List.foldl {α : Type u} {β : Type v} (f : α → β → α) : (init : α) → List β → α
| a, nil => a
| a, cons b l => foldl f (f a b) l | def | Init.Prelude | [] | Init/Prelude.lean | List.foldl | Folds a function over a list from the left, accumulating a value starting with `init`. The
accumulated value is combined with the each element of the list in order, using `f`.
Examples:
* `[a, b, c].foldl f z = f (f (f z a) b) c`
* `[1, 2, 3].foldl (· ++ toString ·) "" = "123"`
* `[1, 2, 3].foldl (s!"({·} {·})") "" = "((( 1) 2) 3)"` |
List.concat {α : Type u} : List α → α → List α
| nil, b => cons b nil
| cons a as, b => cons a (concat as b) | def | Init.Prelude | [] | Init/Prelude.lean | List.concat | Adds an element to the *end* of a list.
The added element is the last element of the resulting list.
Examples:
* `List.concat ["red", "yellow"] "green" = ["red", "yellow", "green"]`
* `List.concat [1, 2, 3] 4 = [1, 2, 3, 4]`
* `List.concat [] () = [()]` |
protected List.append : (xs ys : List α) → List α
| nil, bs => bs
| cons a as, bs => cons a (List.append as bs) | def | Init.Prelude | [] | Init/Prelude.lean | List.append | Appends two lists. Normally used via the `++` operator.
Appending lists takes time proportional to the length of the first list: `O(|xs|)`.
Examples:
* `[1, 2, 3] ++ [4, 5] = [1, 2, 3, 4, 5]`.
* `[] ++ [4, 5] = [4, 5]`.
* `[1, 2, 3] ++ [] = [1, 2, 3]`. |
List.flatten : List (List α) → List α
| nil => nil
| cons l L => List.append l (flatten L) | def | Init.Prelude | [] | Init/Prelude.lean | List.flatten | Concatenates a list of lists into a single list, preserving the order of the elements.
`O(|flatten L|)`.
Examples:
* `[["a"], ["b", "c"]].flatten = ["a", "b", "c"]`
* `[["a"], [], ["b", "c"], ["d", "e", "f"]].flatten = ["a", "b", "c", "d", "e", "f"]` |
@[specialize] List.map (f : α → β) : (l : List α) → List β
| nil => nil
| cons a as => cons (f a) (map f as) | def | Init.Prelude | [] | Init/Prelude.lean | List.map | Applies a function to each element of the list, returning the resulting list of values.
`O(|l|)`.
Examples:
* `[a, b, c].map f = [f a, f b, f c]`
* `[].map Nat.succ = []`
* `["one", "two", "three"].map (·.length) = [3, 3, 5]`
* `["one", "two", "three"].map (·.reverse) = ["eno", "owt", "eerht"]` |
@[inline] List.flatMap {α : Type u} {β : Type v} (b : α → List β) (as : List α) : List β := flatten (map b as) | def | Init.Prelude | [] | Init/Prelude.lean | List.flatMap | Applies a function that returns a list to each element of a list, and concatenates the resulting
lists.
Examples:
* `[2, 3, 2].flatMap List.range = [0, 1, 0, 1, 2, 0, 1]`
* `["red", "blue"].flatMap String.toList = ['r', 'e', 'd', 'b', 'l', 'u', 'e']` |
Array (α : Type u) where
/--
Converts a `List α` into an `Array α`.
The function `List.toArray` is preferred.
At runtime, this constructor is overridden by `List.toArrayImpl` and is `O(n)` in the length of
the list.
-/
mk ::
/--
Converts an `Array α` into a `List α` that contains the same elements in the same order.
At runtime, this is implemented by `Array.toListImpl` and is `O(n)` in the length of the
array.
-/
toList : List α
attribute [extern "lean_array_to_list"] Array.toList
attribute [extern "lean_array_mk"] Array.mk | structure | Init.Prelude | [] | Init/Prelude.lean | Array | `Array α` is the type of [dynamic arrays](https://en.wikipedia.org/wiki/Dynamic_array) with elements
from `α`. This type has special support in the runtime.
Arrays perform best when unshared. As long as there is never more than one reference to an array,
all updates will be performed _destructively_. This results in performance comparable to mutable
arrays in imperative programming languages.
An array has a size and a capacity. The size is the number of elements present in the array, while
the capacity is the amount of memory currently allocated for elements. The size is accessible via
`Array.size`, but the capacity is not observable from Lean code. `Array.emptyWithCapacity n` creates
an array which is equal to `#[]`, but internally allocates an array of capacity `n`. When the size
exceeds the capacity, allocation is required to grow the array.
From the point of view of proofs, `Array α` is just a wrapper around `List α`. |
@[match_pattern]
List.toArray (xs : List α) : Array α := .mk xs | abbrev | Init.Prelude | [] | Init/Prelude.lean | List.toArray | Converts a `List α` into an `Array α`.
`O(|xs|)`. At runtime, this operation is implemented by `List.toArrayImpl` and takes time linear in
the length of the list. `List.toArray` should be used instead of `Array.mk`.
Examples:
* `[1, 2, 3].toArray = #[1, 2, 3]`
* `["monday", "wednesday", friday"].toArray = #["monday", "wednesday", friday"].` |
@[extern "lean_mk_empty_array_with_capacity"]
Array.mkEmpty {α : Type u} (c : @& Nat) : Array α where
toList := List.nil | def | Init.Prelude | [] | Init/Prelude.lean | Array.mkEmpty | Constructs a new empty array with initial capacity `c`.
This will be deprecated in favor of `Array.emptyWithCapacity` in the future. |
@[extern "lean_mk_empty_array_with_capacity", expose]
Array.emptyWithCapacity {α : Type u} (c : @& Nat) : Array α where
toList := List.nil | def | Init.Prelude | [] | Init/Prelude.lean | Array.emptyWithCapacity | Constructs a new empty array with initial capacity `c`. |
@[expose]
Array.empty {α : Type u} : Array α := emptyWithCapacity 0 | def | Init.Prelude | [] | Init/Prelude.lean | Array.empty | Constructs a new empty array with initial capacity `0`.
Use `Array.emptyWithCapacity` to create an array with a greater initial capacity. |
@[extern "lean_array_get_size", tagged_return]
Array.size {α : Type u} (a : @& Array α) : Nat :=
a.toList.length | def | Init.Prelude | [] | Init/Prelude.lean | Array.size | Gets the number of elements stored in an array.
This is a cached value, so it is `O(1)` to access. The space allocated for an array, referred to as
its _capacity_, is at least as large as its size, but may be larger. The capacity of an array is an
internal detail that's not observable by Lean code. |
@[extern "lean_array_fget_borrowed"]
unsafe Array.getInternalBorrowed {α : Type u} (a : @& Array α) (i : @& Nat) (h : LT.lt i a.size) : α :=
a.toList.get ⟨i, h⟩ | opaque | Init.Prelude | [] | Init/Prelude.lean | Array.getInternalBorrowed | Version of `Array.getInternal` that does not increment the reference count of its result.
This is only intended for direct use by the compiler. |
@[extern "lean_array_fget"]
Array.getInternal {α : Type u} (a : @& Array α) (i : @& Nat) (h : LT.lt i a.size) : α :=
a.toList.get ⟨i, h⟩ | def | Init.Prelude | [] | Init/Prelude.lean | Array.getInternal | Use the indexing notation `a[i]` instead.
Access an element from an array without needing a runtime bounds checks,
using a `Nat` index and a proof that it is in bounds.
This function does not use `get_elem_tactic` to automatically find the proof that
the index is in bounds. This is because the tactic itself needs to look up values in
arrays. |
@[inline] Array.getD (a : Array α) (i : Nat) (v₀ : α) : α :=
dite (LT.lt i a.size) (fun h => a.getInternal i h) (fun _ => v₀) | abbrev | Init.Prelude | [] | Init/Prelude.lean | Array.getD | Returns the element at the provided index, counting from `0`. Returns the fallback value `v₀` if the
index is out of bounds.
To return an `Option` depending on whether the index is in bounds, use `a[i]?`. To panic if the
index is out of bounds, use `a[i]!`.
Examples:
* `#["spring", "summer", "fall", "winter"].getD 2 "never" = "fall"`
* `#["spring", "summer", "fall", "winter"].getD 0 "never" = "spring"`
* `#["spring", "summer", "fall", "winter"].getD 4 "never" = "never"` |
@[extern "lean_array_get_borrowed"]
unsafe Array.get!InternalBorrowed {α : Type u} [Inhabited α] (a : @& Array α) (i : @& Nat) : α | opaque | Init.Prelude | [] | Init/Prelude.lean | Array.get | Version of `Array.get!Internal` that does not increment the reference count of its result.
This is only intended for direct use by the compiler. |
@[extern "lean_array_get"]
Array.get!Internal {α : Type u} [Inhabited α] (a : @& Array α) (i : @& Nat) : α :=
Array.getD a i default | def | Init.Prelude | [] | Init/Prelude.lean | Array.get | Use the indexing notation `a[i]!` instead.
Access an element from an array, or panic if the index is out of bounds. |
@[extern "lean_array_push", expose]
Array.push {α : Type u} (a : Array α) (v : α) : Array α where
toList := List.concat a.toList v | def | Init.Prelude | [] | Init/Prelude.lean | Array.push | Adds an element to the end of an array. The resulting array's size is one greater than the input
array. If there are no other references to the array, then it is modified in-place.
This takes amortized `O(1)` time because `Array α` is represented by a dynamic array.
Examples:
* `#[].push "apple" = #["apple"]`
* `#["apple"].push "orange" = #["apple", "orange"]` |
Array.mkArray0 {α : Type u} : Array α :=
emptyWithCapacity 0 | def | Init.Prelude | [] | Init/Prelude.lean | Array.mkArray0 | Create array `#[]` |
Array.mkArray1 {α : Type u} (a₁ : α) : Array α :=
(emptyWithCapacity 1).push a₁ | def | Init.Prelude | [] | Init/Prelude.lean | Array.mkArray1 | Create array `#[a₁]` |
Array.mkArray2 {α : Type u} (a₁ a₂ : α) : Array α :=
((emptyWithCapacity 2).push a₁).push a₂ | def | Init.Prelude | [] | Init/Prelude.lean | Array.mkArray2 | Create array `#[a₁, a₂]` |
Array.mkArray3 {α : Type u} (a₁ a₂ a₃ : α) : Array α :=
(((emptyWithCapacity 3).push a₁).push a₂).push a₃ | def | Init.Prelude | [] | Init/Prelude.lean | Array.mkArray3 | Create array `#[a₁, a₂, a₃]` |
Array.mkArray4 {α : Type u} (a₁ a₂ a₃ a₄ : α) : Array α :=
((((emptyWithCapacity 4).push a₁).push a₂).push a₃).push a₄ | def | Init.Prelude | [] | Init/Prelude.lean | Array.mkArray4 | Create array `#[a₁, a₂, a₃, a₄]` |
Array.mkArray5 {α : Type u} (a₁ a₂ a₃ a₄ a₅ : α) : Array α :=
(((((emptyWithCapacity 5).push a₁).push a₂).push a₃).push a₄).push a₅ | def | Init.Prelude | [] | Init/Prelude.lean | Array.mkArray5 | Create array `#[a₁, a₂, a₃, a₄, a₅]` |
Array.mkArray6 {α : Type u} (a₁ a₂ a₃ a₄ a₅ a₆ : α) : Array α :=
((((((emptyWithCapacity 6).push a₁).push a₂).push a₃).push a₄).push a₅).push a₆ | def | Init.Prelude | [] | Init/Prelude.lean | Array.mkArray6 | Create array `#[a₁, a₂, a₃, a₄, a₅, a₆]` |
Array.mkArray7 {α : Type u} (a₁ a₂ a₃ a₄ a₅ a₆ a₇ : α) : Array α :=
(((((((emptyWithCapacity 7).push a₁).push a₂).push a₃).push a₄).push a₅).push a₆).push a₇ | def | Init.Prelude | [] | Init/Prelude.lean | Array.mkArray7 | Create array `#[a₁, a₂, a₃, a₄, a₅, a₆, a₇]` |
Array.mkArray8 {α : Type u} (a₁ a₂ a₃ a₄ a₅ a₆ a₇ a₈ : α) : Array α :=
((((((((emptyWithCapacity 8).push a₁).push a₂).push a₃).push a₄).push a₅).push a₆).push a₇).push a₈ | def | Init.Prelude | [] | Init/Prelude.lean | Array.mkArray8 | Create array `#[a₁, a₂, a₃, a₄, a₅, a₆, a₇, a₈]` |
protected Array.appendCore {α : Type u} (as : Array α) (bs : Array α) : Array α :=
let rec loop (i : Nat) (j : Nat) (as : Array α) : Array α :=
dite (LT.lt j bs.size)
(fun hlt =>
match i with
| 0 => as
| Nat.succ i' => loop i' (hAdd j 1) (as.push (bs.getInternal j hlt)))
(fun _ => as)
loop bs.size 0 as | def | Init.Prelude | [] | Init/Prelude.lean | Array.appendCore | Slower `Array.append` used in quotations. |
ByteArray where
/--
Packs an array of bytes into a `ByteArray`.
Converting between `Array` and `ByteArray` takes linear time.
-/
mk ::
/--
The data contained in the byte array.
Converting between `Array` and `ByteArray` takes linear time.
-/
data : Array UInt8
attribute [extern "lean_byte_array_mk"] ByteArray.mk
attribute [extern "lean_byte_array_data"] ByteArray.data | structure | Init.Prelude | [] | Init/Prelude.lean | ByteArray | Returns the slice of `as` from indices `start` to `stop` (exclusive). The resulting array has size
`(min stop as.size) - start`.
If `start` is greater or equal to `stop`, the result is empty. If `stop` is greater than the size of
`as`, the size is used instead.
Examples:
* `#[0, 1, 2, 3, 4].extract 1 3 = #[1, 2]`
* `#[0, 1, 2, 3, 4].extract 1 30 = #[1, 2, 3, 4]`
* `#[0, 1, 2, 3, 4].extract 0 0 = #[]`
* `#[0, 1, 2, 3, 4].extract 2 1 = #[]`
* `#[0, 1, 2, 3, 4].extract 2 2 = #[]`
* `#[0, 1, 2, 3, 4].extract 2 3 = #[2]`
* `#[0, 1, 2, 3, 4].extract 2 4 = #[2, 3]`
-/
-- NOTE: used in the quotation elaborator output
def Array.extract (as : Array α) (start : Nat := 0) (stop : Nat := as.size) : Array α :=
let rec loop (i : Nat) (j : Nat) (bs : Array α) : Array α :=
dite (LT.lt j as.size)
(fun hlt =>
match i with
| 0 => bs
| Nat.succ i' => loop i' (hAdd j 1) (bs.push (as.getInternal j hlt)))
(fun _ => bs)
let sz' := Nat.sub (min stop as.size) start
loop sz' start (emptyWithCapacity sz')
/--
`ByteArray` is like `Array UInt8`, but with an efficient run-time representation as a packed
byte buffer. |
@[extern "lean_mk_empty_byte_array"]
ByteArray.emptyWithCapacity (c : @& Nat) : ByteArray :=
{ data := Array.empty } | def | Init.Prelude | [] | Init/Prelude.lean | ByteArray.emptyWithCapacity | Constructs a new empty byte array with initial capacity `c`. |
ByteArray.empty : ByteArray := emptyWithCapacity 0 | def | Init.Prelude | [] | Init/Prelude.lean | ByteArray.empty | Constructs a new empty byte array with initial capacity `0`.
Use `ByteArray.emptyWithCapacity` to create an array with a greater initial capacity. |
@[extern "lean_byte_array_push"]
ByteArray.push : ByteArray → UInt8 → ByteArray
| ⟨bs⟩, b => ⟨bs.push b⟩ | def | Init.Prelude | [] | Init/Prelude.lean | ByteArray.push | Adds an element to the end of an array. The resulting array's size is one greater than the input
array. If there are no other references to the array, then it is modified in-place.
This takes amortized `O(1)` time because `ByteArray` is represented by a dynamic array. |
List.toByteArray (bs : List UInt8) : ByteArray :=
let rec loop
| nil, r => r
| cons b bs, r => loop bs (r.push b)
loop bs ByteArray.empty | def | Init.Prelude | [] | Init/Prelude.lean | List.toByteArray | Converts a list of bytes into a `ByteArray`. |
@[extern "lean_byte_array_size", tagged_return]
ByteArray.size : (@& ByteArray) → Nat
| ⟨bs⟩ => bs.size | def | Init.Prelude | [] | Init/Prelude.lean | ByteArray.size | Returns the number of bytes in the byte array.
This is the number of bytes actually in the array, as distinct from its capacity, which is the
amount of memory presently allocated for the array. |
String.utf8EncodeChar (c : Char) : List UInt8 :=
let v := c.val.toNat
ite (LE.le v 0x7f)
(List.cons (UInt8.ofNat v) List.nil)
(ite (LE.le v 0x7ff)
(List.cons
(UInt8.ofNat (HAdd.hAdd (HMod.hMod (HDiv.hDiv v 64) 0x20) 0xc0))
(List.cons
(UInt8.ofNat (HAdd.hAdd (HMod.hMod v 0x40) 0x80))
List.nil))
(ite (LE.le v 0xffff)
(List.cons
(UInt8.ofNat (HAdd.hAdd (HMod.hMod (HDiv.hDiv v 4096) 0x10) 0xe0))
(List.cons
(UInt8.ofNat (HAdd.hAdd (HMod.hMod (HDiv.hDiv v 64) 0x40) 0x80))
(List.cons
(UInt8.ofNat (HAdd.hAdd (HMod.hMod v 0x40) 0x80))
List.nil)))
(List.cons
(UInt8.ofNat (HAdd.hAdd (HMod.hMod (HDiv.hDiv v 262144) 0x08) 0xf0))
(List.cons
(UInt8.ofNat (HAdd.hAdd (HMod.hMod (HDiv.hDiv v 4096) 0x40) 0x80))
(List.cons
(UInt8.ofNat (HAdd.hAdd (HMod.hMod (HDiv.hDiv v 64) 0x40) 0x80))
(List.cons
(UInt8.ofNat (HAdd.hAdd (HMod.hMod v 0x40) 0x80))
List.nil)))))) | def | Init.Prelude | [] | Init/Prelude.lean | String.utf8EncodeChar | Returns the sequence of bytes in a character's UTF-8 encoding. |
List.utf8Encode (l : List Char) : ByteArray :=
l.flatMap String.utf8EncodeChar |>.toByteArray | def | Init.Prelude | [] | Init/Prelude.lean | List.utf8Encode | Encode a list of characters (Unicode scalar value) in UTF-8. This is an inefficient model
implementation. Use `List.asString` instead. |
ByteArray.IsValidUTF8 (b : ByteArray) : Prop
/--
Show that a byte array is valid UTF-8 by exhibiting it as `List.utf8Encode m` for some list `m`
of characters.
-/
| intro (m : List Char) (hm : Eq b (List.utf8Encode m)) | inductive | Init.Prelude | [] | Init/Prelude.lean | ByteArray.IsValidUTF8 | A byte array is valid UTF-8 if it is of the form `List.Internal.utf8Encode m` for some `m`.
Note that in order for this definition to be well-behaved it is necessary to know that this `m`
is unique. To show this, one defines UTF-8 decoding and shows that encoding and decoding are
mutually inverse. |
String where ofByteArray ::
/-- The bytes of the UTF-8 encoding of the string. Since strings have a special representation in
the runtime, this function actually takes linear time and space at runtime. For efficient access
to the string's bytes, use `String.utf8ByteSize` and `String.getUTF8Byte`. -/
toByteArray : ByteArray
/-- The bytes of the string form valid UTF-8. -/
isValidUTF8 : ByteArray.IsValidUTF8 toByteArray
attribute [extern "lean_string_to_utf8"] String.toByteArray
attribute [extern "lean_string_from_utf8_unchecked"] String.ofByteArray | structure | Init.Prelude | [] | Init/Prelude.lean | String | A string is a sequence of Unicode scalar values.
At runtime, strings are represented by [dynamic arrays](https://en.wikipedia.org/wiki/Dynamic_array)
of bytes using the UTF-8 encoding. Both the size in bytes (`String.utf8ByteSize`) and in characters
(`String.length`) are cached and take constant time. Many operations on strings perform in-place
modifications when the reference to the string is unique. |
@[extern "lean_string_dec_eq"]
String.decEq (s₁ s₂ : @& String) : Decidable (Eq s₁ s₂) :=
match s₁, s₂ with
| ⟨⟨⟨s₁⟩⟩, _⟩, ⟨⟨⟨s₂⟩⟩, _⟩ =>
dite (Eq s₁ s₂) (fun h => match s₁, s₂, h with | _, _, Eq.refl _ => isTrue rfl)
(fun h => isFalse
(fun h' => h (congrArg (fun s => Array.toList (ByteArray.data (String.toByteArray s))) h'))) | def | Init.Prelude | [] | Init/Prelude.lean | String.decEq | Decides whether two strings are equal. Normally used via the `DecidableEq String` instance and the
`=` operator.
At runtime, this function is overridden with an efficient native implementation. |
String.Pos.Raw where
/-- Get the underlying byte index of a `String.Pos.Raw` -/
byteIdx : Nat := 0 | structure | Init.Prelude | [] | Init/Prelude.lean | String.Pos.Raw | A byte position in a `String`, according to its UTF-8 encoding.
Character positions (counting the Unicode code points rather than bytes) are represented by plain
`Nat`s. Indexing a `String` by a `String.Pos.Raw` takes constant time, while character positions need to
be translated internally to byte positions, which takes linear time.
A byte position `p` is *valid* for a string `s` if `0 ≤ p ≤ s.rawEndPos` and `p` lies on a UTF-8
character boundary, see `String.Pos.IsValid`.
There is another type, `String.Pos`, which bundles the validity predicate. Using `String.Pos`
instead of `String.Pos.Raw` is recommended because it will lead to less error handling and fewer edge cases. |
Substring.Raw where
/-- The underlying string. -/
str : String
/-- The byte position of the start of the string slice. -/
startPos : String.Pos.Raw
/-- The byte position of the end of the string slice. -/
stopPos : String.Pos.Raw | structure | Init.Prelude | [] | Init/Prelude.lean | Substring.Raw | A region or slice of some underlying string.
A substring contains a string together with the start and end byte positions of a region of
interest. Actually extracting a substring requires copying and memory allocation, while many
substrings of the same underlying string may exist with very little overhead, and they are more
convenient than tracking the bounds by hand.
Using its constructor explicitly, it is possible to construct a `Substring` in which one or both of
the positions is invalid for the string. Many operations will return unexpected or confusing results
if the start and stop positions are not valid. For this reason, `Substring` will be deprecated in
favor of `String.Slice`, which always represents a valid substring. |
@[inline, expose] Substring.Raw.bsize : Substring.Raw → Nat
| ⟨_, b, e⟩ => e.byteIdx.sub b.byteIdx | def | Init.Prelude | [] | Init/Prelude.lean | Substring.Raw.bsize | The number of bytes used by the string's UTF-8 encoding. |
@[extern "lean_string_utf8_byte_size", tagged_return]
String.utf8ByteSize (s : @& String) : Nat :=
s.toByteArray.size | def | Init.Prelude | [] | Init/Prelude.lean | String.utf8ByteSize | The number of bytes used by the string's UTF-8 encoding.
At runtime, this function takes constant time because the byte length of strings is cached. |
@[inline] String.rawEndPos (s : String) : String.Pos.Raw where
byteIdx := utf8ByteSize s | def | Init.Prelude | [] | Init/Prelude.lean | String.rawEndPos | A UTF-8 byte position that points at the end of a string, just after the last character.
* `"abc".rawEndPos = ⟨3⟩`
* `"L∃∀N".rawEndPos = ⟨8⟩` |
@[inline] String.toRawSubstring (s : String) : Substring.Raw where
str := s
startPos := {}
stopPos := s.rawEndPos | def | Init.Prelude | [] | Init/Prelude.lean | String.toRawSubstring | Converts a `String` into a `Substring` that denotes the entire string. |
String.toRawSubstring' (s : String) : Substring.Raw :=
s.toRawSubstring | def | Init.Prelude | [] | Init/Prelude.lean | String.toRawSubstring' | Converts a `String` into a `Substring` that denotes the entire string.
This is a version of `String.toRawSubstring` that doesn't have an `@[inline]` annotation. |
unsafe unsafeCast {α : Sort u} {β : Sort v} (a : α) : β :=
PLift.down (ULift.down.{max u v} (cast lcProof (ULift.up.{max u v} (PLift.up a)))) | def | Init.Prelude | [] | Init/Prelude.lean | unsafeCast | This function will cast a value of type `α` to type `β`, and is a no-op in the
compiler. This function is **extremely dangerous** because there is no guarantee
that types `α` and `β` have the same data representation, and this can lead to
memory unsafety. It is also logically unsound, since you could just cast
`True` to `False`. For all those reasons this function is marked as `unsafe`.
It is implemented by lifting both `α` and `β` into a common universe, and then
using `cast (lcProof : ULift (PLift α) = ULift (PLift β))` to actually perform
the cast. All these operations are no-ops in the compiler.
Using this function correctly requires some knowledge of the data representation
of the source and target types. Some general classes of casts which are safe in
the current runtime:
* `Array α` to `Array β` where `α` and `β` have compatible representations,
or more generally for other inductive types.
* `Quot α r` and `α`.
* `@Subtype α p` and `α`, or generally any structure containing only one
non-`Prop` field of type `α`.
* Casting `α` to/from `NonScalar` when `α` is a boxed generic type
(i.e. a function that accepts an arbitrary type `α` and is not specialized to
a scalar type like `UInt8`). |
@[never_extract, extern "lean_panic_fn"]
panicCore {α : Sort u} [Inhabited α] (msg : String) : α := default | def | Init.Prelude | [] | Init/Prelude.lean | panicCore | Auxiliary definition for `panic`. -/
/-
This is a workaround for `panic` occurring in monadic code. See issue #695.
The `panicCore` definition cannot be specialized since it is an extern.
When `panic` occurs in monadic code, the `Inhabited α` parameter depends on a
`[inst : Monad m]` instance. The `inst` parameter will not be eliminated during
specialization if it occurs inside of a binder (to avoid work duplication), and
will prevent the actual monad from being "copied" to the code being specialized.
When we reimplement the specializer, we may consider copying `inst` if it also
occurs outside binders or if it is an instance. |
@[noinline, never_extract]
panic {α : Sort u} [Inhabited α] (msg : String) : α :=
panicCore msg
-- TODO: this be applied directly to `Inhabited`'s definition when we remove the above workaround
attribute [nospecialize] Inhabited | def | Init.Prelude | [] | Init/Prelude.lean | panic | `(panic "msg" : α)` has a built-in implementation which prints `msg` to
the error buffer. It *does not* terminate execution, and because it is a safe
function, it still has to return an element of `α`, so it takes `[Inhabited α]`
and returns `default`. It is primarily intended for debugging in pure contexts,
and assertion failures.
Because this is a pure function with side effects, it is marked as
`@[never_extract]` so that the compiler will not perform common sub-expression
elimination and other optimizations that assume that the expression is pure. |
Bind (m : Type u → Type v) where
/--
Sequences two computations, allowing the second to depend on the value computed by the first.
If `x : m α` and `f : α → m β`, then `x >>= f : m β` represents the result of executing `x` to get
a value of type `α` and then passing it to `f`.
-/
bind : {α β : Type u} → m α → (α → m β) → m β
export Bind (bind) | class | Init.Prelude | [] | Init/Prelude.lean | Bind | The `>>=` operator is overloaded via instances of `bind`.
`Bind` is typically used via `Monad`, which extends it. |
Pure (f : Type u → Type v) where
/--
Given `a : α`, then `pure a : f α` represents an action that does nothing and returns `a`.
Examples:
* `(pure "hello" : Option String) = some "hello"`
* `(pure "hello" : Except (Array String) String) = Except.ok "hello"`
* `(pure "hello" : StateM Nat String).run 105 = ("hello", 105)`
-/
pure {α : Type u} : α → f α
export Pure (pure) | class | Init.Prelude | [] | Init/Prelude.lean | Pure | The `pure` function is overloaded via `Pure` instances.
`Pure` is typically accessed via `Monad` or `Applicative` instances. |
Functor (f : Type u → Type v) : Type (max (u+1) v) where
/--
Applies a function inside a functor. This is used to overload the `<$>` operator.
When mapping a constant function, use `Functor.mapConst` instead, because it may be more
efficient.
-/
map : {α β : Type u} → (α → β) → f α → f β
/--
Mapping a constant function.
Given `a : α` and `v : f α`, `mapConst a v` is equivalent to `Function.const _ a <$> v`. For some
functors, this can be implemented more efficiently; for all other functors, the default
implementation may be used.
-/
mapConst : {α β : Type u} → α → f β → f α := Function.comp map (Function.const _) | class | Init.Prelude | [] | Init/Prelude.lean | Functor | A functor in the sense used in functional programming, which means a function `f : Type u → Type v`
has a way of mapping a function over its contents. This `map` operator is written `<$>`, and
overloaded via `Functor` instances.
This `map` function should respect identity and function composition. In other words, for all terms
`v : f α`, it should be the case that:
* `id <$> v = v`
* For all functions `h : β → γ` and `g : α → β`, `(h ∘ g) <$> v = h <$> g <$> v`
While all `Functor` instances should live up to these requirements, they are not required to _prove_
that they do. Proofs may be required or provided via the `LawfulFunctor` class.
Assuming that instances are lawful, this definition corresponds to the category-theoretic notion of
[functor](https://en.wikipedia.org/wiki/Functor) in the special case where the category is the
category of types and functions between them. |
Seq (f : Type u → Type v) : Type (max (u+1) v) where
/--
The implementation of the `<*>` operator.
In a monad, `mf <*> mx` is the same as `do let f ← mf; x ← mx; pure (f x)`: it evaluates the
function first, then the argument, and applies one to the other.
To avoid surprising evaluation semantics, `mx` is taken "lazily", using a `Unit → f α` function.
-/
seq : {α β : Type u} → f (α → β) → (Unit → f α) → f β | class | Init.Prelude | [] | Init/Prelude.lean | Seq | The `<*>` operator is overloaded using the function `Seq.seq`.
While `<$>` from the class `Functor` allows an ordinary function to be mapped over its contents,
`<*>` allows a function that's “inside” the functor to be applied. When thinking about `f` as
possible side effects, this captures evaluation order: `seq` arranges for the effects that produce
the function to occur prior to those that produce the argument value.
For most applications, `Applicative` or `Monad` should be used rather than `Seq` itself. |
SeqLeft (f : Type u → Type v) : Type (max (u+1) v) where
/--
Sequences the effects of two terms, discarding the value of the second. This function is usually
invoked via the `<*` operator.
Given `x : f α` and `y : f β`, `x <* y` runs `x`, then runs `y`, and finally returns the result of
`x`.
The evaluation of the second argument is delayed by wrapping it in a function, enabling
“short-circuiting” behavior from `f`.
-/
seqLeft : {α β : Type u} → f α → (Unit → f β) → f α | class | Init.Prelude | [] | Init/Prelude.lean | SeqLeft | The `<*` operator is overloaded using `seqLeft`.
When thinking about `f` as potential side effects, `<*` evaluates first the left and then the right
argument for their side effects, discarding the value of the right argument and returning the value
of the left argument.
For most applications, `Applicative` or `Monad` should be used rather than `SeqLeft` itself. |
SeqRight (f : Type u → Type v) : Type (max (u+1) v) where
/--
Sequences the effects of two terms, discarding the value of the first. This function is usually
invoked via the `*>` operator.
Given `x : f α` and `y : f β`, `x *> y` runs `x`, then runs `y`, and finally returns the result of
`y`.
The evaluation of the second argument is delayed by wrapping it in a function, enabling
“short-circuiting” behavior from `f`.
-/
seqRight : {α β : Type u} → f α → (Unit → f β) → f β | class | Init.Prelude | [] | Init/Prelude.lean | SeqRight | The `*>` operator is overloaded using `seqRight`.
When thinking about `f` as potential side effects, `*>` evaluates first the left and then the right
argument for their side effects, discarding the value of the left argument and returning the value
of the right argument.
For most applications, `Applicative` or `Monad` should be used rather than `SeqRight` itself. |
Applicative (f : Type u → Type v) extends Functor f, Pure f, Seq f, SeqLeft f, SeqRight f where
map := fun x y => Seq.seq (pure x) fun _ => y
seqLeft := fun a b => Seq.seq (Functor.map (Function.const _) a) b
seqRight := fun a b => Seq.seq (Functor.map (Function.const _ id) a) b | class | Init.Prelude | [] | Init/Prelude.lean | Applicative | An [applicative functor](lean-manual://section/monads-and-do) is more powerful than a `Functor`, but
less powerful than a `Monad`.
Applicative functors capture sequencing of effects with the `<*>` operator, overloaded as `seq`, but
not data-dependent effects. The results of earlier computations cannot be used to control later
effects.
Applicative functors should satisfy four laws. Instances of `Applicative` are not required to prove
that they satisfy these laws, which are part of the `LawfulApplicative` class. |
Monad (m : Type u → Type v) : Type (max (u+1) v) extends Applicative m, Bind m where
map f x := bind x (Function.comp pure f)
seq f x := bind f fun y => Functor.map y (x ())
seqLeft x y := bind x fun a => bind (y ()) (fun _ => pure a)
seqRight x y := bind x fun _ => y () | class | Init.Prelude | [] | Init/Prelude.lean | Monad | [Monads](https://en.wikipedia.org/wiki/Monad_(functional_programming)) are an abstraction of
sequential control flow and side effects used in functional programming. Monads allow both
sequencing of effects and data-dependent effects: the values that result from an early step may
influence the effects carried out in a later step.
The `Monad` API may be used directly. However, it is most commonly accessed through
[`do`-notation](lean-manual://section/do-notation).
Most `Monad` instances provide implementations of `pure` and `bind`, and use default implementations
for the other methods inherited from `Applicative`. Monads should satisfy certain laws, but
instances are not required to prove this. An instance of `LawfulMonad` expresses that a given
monad's operations are lawful. |
MonadEval (m : semiOutParam (Type u → Type v)) (n : Type u → Type w) where
/-- Evaluates a value from monad `m` into monad `n`. -/
monadEval : {α : Type u} → m α → n α | class | Init.Prelude | [] | Init/Prelude.lean | MonadEval | Computations in the monad `m` can be run in the monad `n`. These translations are inserted
automatically by the compiler.
Usually, `n` consists of some number of monad transformers applied to `m`, but this is not
mandatory.
New instances should use this class, `MonadLift`. Clients that require one monad to be liftable into
another should instead request `MonadLiftT`, which is the reflexive, transitive closure of
`MonadLift`.
-/
-- Like Haskell's [`MonadTrans`], but `n` does not have to be a monad transformer.
-- Alternatively, an implementation of [`MonadLayer`] without `layerInvmap` (so far).
-- [`MonadTrans`]: https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Class.html
-- [`MonadLayer`]: https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLayer
class MonadLift (m : semiOutParam (Type u → Type v)) (n : Type u → Type w) where
/-- Translates an action from monad `m` into monad `n`. -/
monadLift : {α : Type u} → m α → n α
/--
Computations in the monad `m` can be run in the monad `n`. These translations are inserted
automatically by the compiler.
Usually, `n` consists of some number of monad transformers applied to `m`, but this is not
mandatory.
This is the reflexive, transitive closure of `MonadLift`. Clients that require one monad to be
liftable into another should request an instance of `MonadLiftT`. New instances should instead be
defined for `MonadLift` itself.
-/
-- Corresponds to Haskell's [`MonadLift`].
--
-- [`MonadLift`]: https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLift
class MonadLiftT (m : Type u → Type v) (n : Type u → Type w) where
/-- Translates an action from monad `m` into monad `n`. -/
monadLift : {α : Type u} → m α → n α
export MonadLiftT (monadLift)
@[inherit_doc monadLift]
abbrev liftM := @monadLift
@[always_inline]
instance (m n o) [MonadLift n o] [MonadLiftT m n] : MonadLiftT m o where
monadLift x := MonadLift.monadLift (m := n) (monadLift x)
instance (m) : MonadLiftT m m where
monadLift x := x
/--
Typeclass used for adapting monads. This is similar to `MonadLift`, but instances are allowed to
make use of default state for the purpose of synthesizing such an instance, if necessary.
Every `MonadLift` instance gives a `MonadEval` instance.
The purpose of this class is for the `#eval` command,
which looks for a `MonadEval m CommandElabM` or `MonadEval m IO` instance. |
MonadEvalT (m : Type u → Type v) (n : Type u → Type w) where
/-- Evaluates a value from monad `m` into monad `n`. -/
monadEval : {α : Type u} → m α → n α | class | Init.Prelude | [] | Init/Prelude.lean | MonadEvalT | The transitive closure of `MonadEval`. |
MonadFunctorT (m : Type u → Type v) (n : Type u → Type w) where
/--
Lifts a fully-polymorphic transformation of `m` into `n`.
-/
monadMap {α : Type u} : ({β : Type u} → m β → m β) → n α → n α
export MonadFunctorT (monadMap)
@[always_inline] | class | Init.Prelude | [] | Init/Prelude.lean | MonadFunctorT | A way to interpret a fully-polymorphic function in `m` into `n`. Such a function can be thought of
as one that may change the effects in `m`, but can't do so based on specific values that are
provided.
Clients of `MonadFunctor` should typically use `MonadFunctorT`, which is the reflexive, transitive
closure of `MonadFunctor`. New instances should be defined for `MonadFunctor.`
-/
-- Based on [`MFunctor`] from the `pipes` Haskell package, but not restricted to
-- monad transformers. Alternatively, an implementation of [`MonadTransFunctor`].
-- [`MFunctor`]: https://hackage.haskell.org/package/pipes-2.4.0/docs/Control-MFunctor.html
-- [`MonadTransFunctor`]: http://duairc.netsoc.ie/layers-docs/Control-Monad-Layer.html#t:MonadTransFunctor
class MonadFunctor (m : semiOutParam (Type u → Type v)) (n : Type u → Type w) where
/--
Lifts a fully-polymorphic transformation of `m` into `n`.
-/
monadMap {α : Type u} : ({β : Type u} → m β → m β) → n α → n α
/--
A way to interpret a fully-polymorphic function in `m` into `n`. Such a function can be thought of
as one that may change the effects in `m`, but can't do so based on specific values that are
provided.
This is the reflexive, transitive closure of `MonadFunctor`. It automatically chains together
`MonadFunctor` instances as needed. Clients of `MonadFunctor` should typically use `MonadFunctorT`,
but new instances should be defined for `MonadFunctor`. |
monadFunctorRefl (m) : MonadFunctorT m m where
monadMap f := f | instance | Init.Prelude | [] | Init/Prelude.lean | monadFunctorRefl | null |
@[suggest_for Result, suggest_for Exception, suggest_for Either]
Except (ε : Type u) (α : Type v) where
/-- A failure value of type `ε` -/
| error : ε → Except ε α
/-- A success value of type `α` -/
| ok : α → Except ε α
attribute [unbox] Except | inductive | Init.Prelude | [] | Init/Prelude.lean | Except | `Except ε α` is a type which represents either an error of type `ε` or a successful result with a
value of type `α`.
`Except ε : Type u → Type v` is a `Monad` that represents computations that may throw exceptions:
the `pure` operation is `Except.ok` and the `bind` operation returns the first encountered
`Except.error`. |
MonadExceptOf (ε : semiOutParam (Type u)) (m : Type v → Type w) where
/--
Throws an exception of type `ε` to the nearest enclosing `catch`.
-/
throw {α : Type v} : ε → m α
/--
Catches errors thrown in `body`, passing them to `handler`. Errors in `handler` are not caught.
-/
tryCatch {α : Type v} (body : m α) (handler : ε → m α) : m α | class | Init.Prelude | [] | Init/Prelude.lean | MonadExceptOf | Exception monads provide the ability to throw errors and handle errors.
In this class, `ε` is a `semiOutParam`, which means that it can influence the choice of instance.
`MonadExcept ε` provides the same operations, but requires that `ε` be inferable from `m`.
`tryCatchThe`, which takes an explicit exception type, is used to desugar `try ... catch ...` steps
inside `do`-blocks when the handlers have type annotations. |
throwThe (ε : Type u) {m : Type v → Type w} [MonadExceptOf ε m] {α : Type v} (e : ε) : m α :=
MonadExceptOf.throw e | abbrev | Init.Prelude | [] | Init/Prelude.lean | throwThe | Throws an exception, with the exception type specified explicitly. This is useful when a monad
supports throwing more than one type of exception.
Use `throw` for a version that expects the exception type to be inferred from `m`. |
tryCatchThe (ε : Type u) {m : Type v → Type w} [MonadExceptOf ε m] {α : Type v} (x : m α) (handle : ε → m α) : m α :=
MonadExceptOf.tryCatch x handle | abbrev | Init.Prelude | [] | Init/Prelude.lean | tryCatchThe | Catches errors, recovering using `handle`. The exception type is specified explicitly. This is useful when a monad
supports throwing or handling more than one type of exception.
Use `tryCatch`, for a version that expects the exception type to be inferred from `m`. |
MonadExcept (ε : outParam (Type u)) (m : Type v → Type w) where
/--
Throws an exception of type `ε` to the nearest enclosing handler.
-/
throw {α : Type v} : ε → m α
/--
Catches errors thrown in `body`, passing them to `handler`. Errors in `handler` are not caught.
-/
tryCatch {α : Type v} : (body : m α) → (handler : ε → m α) → m α | class | Init.Prelude | [] | Init/Prelude.lean | MonadExcept | Exception monads provide the ability to throw errors and handle errors.
In this class, `ε` is an `outParam`, which means that it is inferred from `m`. `MonadExceptOf ε`
provides the same operations, but allows `ε` to influence instance synthesis.
`MonadExcept.tryCatch` is used to desugar `try ... catch ...` steps inside `do`-blocks when the
handlers do not have exception type annotations. |
MonadExcept.ofExcept [Monad m] [MonadExcept ε m] : Except ε α → m α
| .ok a => pure a
| .error e => throw e
export MonadExcept (throw tryCatch ofExcept) | def | Init.Prelude | [] | Init/Prelude.lean | MonadExcept.ofExcept | Re-interprets an `Except ε` action in an exception monad `m`, succeeding if it succeeds and throwing
an exception if it throws an exception. |
@[inline] protected orElse [MonadExcept ε m] {α : Type v} (t₁ : m α) (t₂ : Unit → m α) : m α :=
tryCatch t₁ fun _ => t₂ () | def | Init.Prelude | [] | Init/Prelude.lean | orElse | Unconditional error recovery that ignores which exception was thrown. Usually used via the `<|>`
operator.
If both computations throw exceptions, then the result is the second exception. |
ReaderT (ρ : Type u) (m : Type u → Type v) (α : Type u) : Type (max u v) :=
ρ → m α | def | Init.Prelude | [] | Init/Prelude.lean | ReaderT | Adds the ability to access a read-only value of type `ρ` to a monad. The value can be locally
overridden by `withReader`, but it cannot be mutated.
Actions in the resulting monad are functions that take the local value as a parameter, returning
ordinary actions in `m`. |
@[always_inline, inline]
ReaderT.mk {ρ : Type u} {m : Type u → Type v} {α : Type u} (x : ρ → m α) : ReaderT ρ m α := x | def | Init.Prelude | [] | Init/Prelude.lean | ReaderT.mk | Interpret `ρ → m α` as an element of `ReaderT ρ m α`. |
@[always_inline, inline]
ReaderT.run {ρ : Type u} {m : Type u → Type v} {α : Type u} (x : ReaderT ρ m α) (r : ρ) : m α :=
x r | def | Init.Prelude | [] | Init/Prelude.lean | ReaderT.run | Executes an action from a monad with a read-only value in the underlying monad `m`. |
@[always_inline, inline]
protected read [Monad m] : ReaderT ρ m ρ :=
pure | def | Init.Prelude | [] | Init/Prelude.lean | read | Retrieves the reader monad's local value. Typically accessed via `read`, or via `readThe` when more
than one local value is available. |
@[always_inline, inline]
protected pure [Monad m] {α} (a : α) : ReaderT ρ m α :=
fun _ => pure a | def | Init.Prelude | [] | Init/Prelude.lean | pure | Returns the provided value `a`, ignoring the reader monad's local value. Typically used via
`Pure.pure`. |
@[always_inline, inline]
protected bind [Monad m] {α β} (x : ReaderT ρ m α) (f : α → ReaderT ρ m β) : ReaderT ρ m β :=
fun r => bind (x r) fun a => f a r
@[always_inline] | def | Init.Prelude | [] | Init/Prelude.lean | bind | Sequences two reader monad computations. Both are provided with the local value, and the second is
passed the value of the first. Typically used via the `>>=` operator. |
@[always_inline, inline]
protected adapt {ρ' α : Type u} (f : ρ' → ρ) : ReaderT ρ m α → ReaderT ρ' m α :=
fun x r => x (f r) | def | Init.Prelude | [] | Init/Prelude.lean | adapt | Modifies a reader monad's local value with `f`. The resulting computation applies `f` to the
incoming local value and passes the result to the inner computation. |
MonadReader (ρ : outParam (Type u)) (m : Type u → Type v) where
/--
Retrieves the local value.
Use `readThe` to explicitly specify a type when more than one value is available.
-/
read : m ρ
export MonadReader (read) | class | Init.Prelude | [] | Init/Prelude.lean | MonadReader | Reader monads provide the ability to implicitly thread a value through a computation. The value can
be read, but not written. A `MonadWithReader ρ` instance additionally allows the value to be locally
overridden for a sub-computation.
In this class, `ρ` is a `semiOutParam`, which means that it can influence the choice of instance.
`MonadReader ρ` provides the same operations, but requires that `ρ` be inferable from `m`.
-/
-- Note: This class can be seen as a simplification of the more "principled" definition
-- ```
-- class MonadReaderOf (ρ : Type u) (n : Type u → Type u) where
-- lift {α : Type u} : ({m : Type u → Type u} → [Monad m] → ReaderT ρ m α) → n α
-- ```
class MonadReaderOf (ρ : semiOutParam (Type u)) (m : Type u → Type v) where
/-- Retrieves the local value. -/
read : m ρ
/--
Reader monads provide the ability to implicitly thread a value through a computation. The value can
be read, but not written. A `MonadWithReader ρ` instance additionally allows the value to be locally
overridden for a sub-computation.
In this class, `ρ` is an `outParam`, which means that it is inferred from `m`. `MonadReaderOf ρ`
provides the same operations, but allows `ρ` to influence instance synthesis. |
@[always_inline, inline]
readThe (ρ : Type u) {m : Type u → Type v} [MonadReaderOf ρ m] : m ρ :=
MonadReaderOf.read | def | Init.Prelude | [] | Init/Prelude.lean | readThe | Retrieves the local value whose type is `ρ`. This is useful when a monad supports reading more than
one type of value.
Use `read` for a version that expects the type `ρ` to be inferred from `m`. |
MonadWithReaderOf (ρ : semiOutParam (Type u)) (m : Type u → Type v) where
/--
Locally modifies the reader monad's value while running an action.
During the inner action `x`, reading the value returns `f` applied to the original value. After
control returns from `x`, the reader monad's value is restored.
-/
withReader {α : Type u} (f : ρ → ρ) (x : m α) : m α | class | Init.Prelude | [] | Init/Prelude.lean | MonadWithReaderOf | A reader monad that additionally allows the value to be locally overridden.
In this class, `ρ` is a `semiOutParam`, which means that it can influence the choice of instance.
`MonadWithReader ρ` provides the same operations, but requires that `ρ` be inferable from `m`. |
@[always_inline, inline]
withTheReader (ρ : Type u) {m : Type u → Type v} [MonadWithReaderOf ρ m] {α : Type u} (f : ρ → ρ) (x : m α) : m α :=
MonadWithReaderOf.withReader f x | def | Init.Prelude | [] | Init/Prelude.lean | withTheReader | Locally modifies the reader monad's value while running an action, with the reader monad's local
value type specified explicitly. This is useful when a monad supports reading more than one type of
value.
During the inner action `x`, reading the value returns `f` applied to the original value. After
control returns from `x`, the reader monad's value is restored.
Use `withReader` for a version that expects the local value's type to be inferred from `m`. |
MonadWithReader (ρ : outParam (Type u)) (m : Type u → Type v) where
/--
Locally modifies the reader monad's value while running an action.
During the inner action `x`, reading the value returns `f` applied to the original value. After
control returns from `x`, the reader monad's value is restored.
-/
withReader {α : Type u} : (f : ρ → ρ) → (x : m α) → m α
export MonadWithReader (withReader) | class | Init.Prelude | [] | Init/Prelude.lean | MonadWithReader | A reader monad that additionally allows the value to be locally overridden.
In this class, `ρ` is an `outParam`, which means that it is inferred from `m`. `MonadWithReaderOf ρ`
provides the same operations, but allows `ρ` to influence instance synthesis. |
MonadStateOf (σ : semiOutParam (Type u)) (m : Type u → Type v) where
/--
Retrieves the current value of the monad's mutable state.
-/
get : m σ
/--
Replaces the current value of the mutable state with a new one.
-/
set : σ → m PUnit
/--
Applies a function to the current state that both computes a new state and a value. The new state
replaces the current state, and the value is returned.
It is equivalent to `do let (a, s) := f (← get); set s; pure a`. However, using `modifyGet` may
lead to higher performance because it doesn't add a new reference to the state value. Additional
references can inhibit in-place updates of data.
-/
modifyGet {α : Type u} : (σ → Prod α σ) → m α
export MonadStateOf (set) | class | Init.Prelude | [] | Init/Prelude.lean | MonadStateOf | State monads provide a value of a given type (the _state_) that can be retrieved or replaced.
Instances may implement these operations by passing state values around, by using a mutable
reference cell (e.g. `ST.Ref σ`), or in other ways.
In this class, `σ` is a `semiOutParam`, which means that it can influence the choice of instance.
`MonadState σ` provides the same operations, but requires that `σ` be inferable from `m`.
The mutable state of a state monad is visible between multiple `do`-blocks or functions, unlike
[local mutable state](lean-manual://section/do-notation-let-mut) in `do`-notation. |
getThe (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] : m σ :=
MonadStateOf.get | abbrev | Init.Prelude | [] | Init/Prelude.lean | getThe | Gets the current state that has the explicitly-provided type `σ`. When the current monad has
multiple state types available, this function selects one of them. |
@[always_inline, inline]
modifyThe (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] (f : σ → σ) : m PUnit :=
MonadStateOf.modifyGet fun s => (PUnit.unit, f s) | abbrev | Init.Prelude | [] | Init/Prelude.lean | modifyThe | Mutates the current state that has the explicitly-provided type `σ`, replacing its value with the
result of applying `f` to it. When the current monad has multiple state types available, this
function selects one of them.
It is equivalent to `do set (f (← get))`. However, using `modify` may lead to higher performance
because it doesn't add a new reference to the state value. Additional references can inhibit
in-place updates of data. |
@[always_inline, inline]
modifyGetThe {α : Type u} (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] (f : σ → Prod α σ) : m α :=
MonadStateOf.modifyGet f | abbrev | Init.Prelude | [] | Init/Prelude.lean | modifyGetThe | Applies a function to the current state that has the explicitly-provided type `σ`. The function both
computes a new state and a value. The new state replaces the current state, and the value is
returned.
It is equivalent to `do let (a, s) := f (← getThe σ); set s; pure a`. However, using `modifyGetThe`
may lead to higher performance because it doesn't add a new reference to the state value. Additional
references can inhibit in-place updates of data. |
MonadState (σ : outParam (Type u)) (m : Type u → Type v) where
/--
Retrieves the current value of the monad's mutable state.
-/
get : m σ
/--
Replaces the current value of the mutable state with a new one.
-/
set : σ → m PUnit
/--
Applies a function to the current state that both computes a new state and a value. The new state
replaces the current state, and the value is returned.
It is equivalent to `do let (a, s) := f (← get); set s; pure a`. However, using `modifyGet` may
lead to higher performance because it doesn't add a new reference to the state value. Additional
references can inhibit in-place updates of data.
-/
modifyGet {α : Type u} : (σ → Prod α σ) → m α
export MonadState (get modifyGet) | class | Init.Prelude | [] | Init/Prelude.lean | MonadState | State monads provide a value of a given type (the _state_) that can be retrieved or replaced.
Instances may implement these operations by passing state values around, by using a mutable
reference cell (e.g. `ST.Ref σ`), or in other ways.
In this class, `σ` is an `outParam`, which means that it is inferred from `m`. `MonadStateOf σ`
provides the same operations, but allows `σ` to influence instance synthesis.
The mutable state of a state monad is visible between multiple `do`-blocks or functions, unlike
[local mutable state](lean-manual://section/do-notation-let-mut) in `do`-notation. |
@[always_inline, inline]
modify {σ : Type u} {m : Type u → Type v} [MonadState σ m] (f : σ → σ) : m PUnit :=
modifyGet fun s => (PUnit.unit, f s) | def | Init.Prelude | [] | Init/Prelude.lean | modify | Mutates the current state, replacing its value with the result of applying `f` to it.
Use `modifyThe` to explicitly select a state type to modify.
It is equivalent to `do set (f (← get))`. However, using `modify` may lead to higher performance
because it doesn't add a new reference to the state value. Additional references can inhibit
in-place updates of data. |
@[always_inline, inline]
getModify {σ : Type u} {m : Type u → Type v} [MonadState σ m] (f : σ → σ) : m σ :=
modifyGet fun s => (s, f s)
-- NOTE: The Ordering of the following two instances determines that the top-most `StateT` Monad layer
-- will be picked first
@[always_inline] | def | Init.Prelude | [] | Init/Prelude.lean | getModify | Replaces the state with the result of applying `f` to it. Returns the old value of the state.
It is equivalent to `get <* modify f` but may be more efficient. |
Result (ε σ α : Type u) where
/-- A success value of type `α` and a new state `σ`. -/
| ok : α → σ → Result ε σ α
/-- An exception of type `ε` and a new state `σ`. -/
| error : ε → σ → Result ε σ α
variable {ε σ α : Type u} | inductive | Init.Prelude | [] | Init/Prelude.lean | Result | The value returned from a combined state and exception monad in which exceptions do not
automatically roll back the state.
`Result ε σ α` is equivalent to `Except ε α × σ`, but using a single combined inductive type yields
a more efficient data representation. |
EStateM (ε σ α : Type u) := σ → Result ε σ α | def | Init.Prelude | [] | Init/Prelude.lean | EStateM | A combined state and exception monad in which exceptions do not automatically roll back the state.
Instances of `EStateM.Backtrackable` provide a way to roll back some part of the state if needed.
`EStateM ε σ` is equivalent to `ExceptT ε (StateM σ)`, but it is more efficient. |
@[always_inline, inline]
protected pure (a : α) : EStateM ε σ α := fun s =>
Result.ok a s
@[always_inline, inline, inherit_doc MonadState.set] | def | Init.Prelude | [] | Init/Prelude.lean | pure | Returns a value without modifying the state or throwing an exception. |
protected set (s : σ) : EStateM ε σ PUnit := fun _ =>
Result.ok ⟨⟩ s
@[always_inline, inline, inherit_doc MonadState.get] | def | Init.Prelude | [] | Init/Prelude.lean | set | null |
protected get : EStateM ε σ σ := fun s =>
Result.ok s s
@[always_inline, inline, inherit_doc MonadState.modifyGet] | def | Init.Prelude | [] | Init/Prelude.lean | get | null |
protected modifyGet (f : σ → Prod α σ) : EStateM ε σ α := fun s =>
match f s with
| (a, s) => Result.ok a s
@[always_inline, inline, inherit_doc MonadExcept.throw] | def | Init.Prelude | [] | Init/Prelude.lean | modifyGet | null |
protected throw (e : ε) : EStateM ε σ α := fun s =>
Result.error e s | def | Init.Prelude | [] | Init/Prelude.lean | throw | null |
Backtrackable (δ : outParam (Type u)) (σ : Type u) where
/--
Extracts the information in the state that should be rolled back if an exception is handled.
-/
save : σ → δ
/--
Updates the current state with the saved information that should be rolled back. This updated
state becomes the current state when an exception is handled.
-/
restore : σ → δ → σ | class | Init.Prelude | [] | Init/Prelude.lean | Backtrackable | Exception handlers in `EStateM` save some part of the state, determined by `δ`, and restore it if an
exception is caught. By default, `δ` is `Unit`, and no information is saved. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.