|
| 1 | +/- |
| 2 | +Copyright (c) 2025 Lean FRO, LLC. All rights reserved. |
| 3 | +Released under Apache 2.0 license as described in the file LICENSE. |
| 4 | +Authors: Paul Reichert |
| 5 | +-/ |
| 6 | +module |
| 7 | + |
| 8 | +prelude |
| 9 | +public import Init.Data.Iterators.Combinators.FilterMap |
| 10 | +public import Init.Data.Iterators.Combinators.Monadic.FlatMap |
| 11 | + |
| 12 | +set_option doc.verso true |
| 13 | + |
| 14 | +/-! |
| 15 | +# {lit}`flatMap` combinator |
| 16 | +
|
| 17 | +This file provides the {lit}`flatMap` iterator combinator and variants of it. |
| 18 | +
|
| 19 | +If {lit}`it` is any iterator, {lit}`it.flatMap f` maps each output of {lit}`it` to an iterator using |
| 20 | +{lit}`f`. |
| 21 | +
|
| 22 | +{lit}`it.flatMap f` first emits all outputs of the first obtained iterator, then of the second, |
| 23 | +and so on. In other words, {lit}`it` flattens the iterator of iterators obtained by mapping with |
| 24 | +{lit}`f`. |
| 25 | +-/ |
| 26 | + |
| 27 | +namespace Std.Iterators |
| 28 | + |
| 29 | +@[always_inline, inherit_doc IterM.flatMapAfterM] |
| 30 | +public def Iter.flatMapAfterM {α : Type w} {β : Type w} {α₂ : Type w} |
| 31 | + {γ : Type w} {m : Type w → Type w'} [Monad m] [Iterator α Id β] [Iterator α₂ m γ] |
| 32 | + (f : β → m (IterM (α := α₂) m γ)) (it₁ : Iter (α := α) β) (it₂ : Option (IterM (α := α₂) m γ)) := |
| 33 | + ((it₁.mapM pure).flatMapAfterM f it₂ : IterM m γ) |
| 34 | + |
| 35 | +@[always_inline, expose, inherit_doc IterM.flatMapM] |
| 36 | +public def Iter.flatMapM {α : Type w} {β : Type w} {α₂ : Type w} |
| 37 | + {γ : Type w} {m : Type w → Type w'} [Monad m] [Iterator α Id β] [Iterator α₂ m γ] |
| 38 | + (f : β → m (IterM (α := α₂) m γ)) (it : Iter (α := α) β) := |
| 39 | + (it.flatMapAfterM f none : IterM m γ) |
| 40 | + |
| 41 | +@[always_inline, inherit_doc IterM.flatMapAfter] |
| 42 | +public def Iter.flatMapAfter {α : Type w} {β : Type w} {α₂ : Type w} |
| 43 | + {γ : Type w} [Iterator α Id β] [Iterator α₂ Id γ] |
| 44 | + (f : β → Iter (α := α₂) γ) (it₁ : Iter (α := α) β) (it₂ : Option (Iter (α := α₂) γ)) := |
| 45 | + ((it₁.toIterM.flatMapAfter (fun b => (f b).toIterM) (Iter.toIterM <$> it₂)).toIter : Iter γ) |
| 46 | + |
| 47 | +@[always_inline, expose, inherit_doc IterM.flatMap] |
| 48 | +public def Iter.flatMap {α : Type w} {β : Type w} {α₂ : Type w} |
| 49 | + {γ : Type w} [Iterator α Id β] [Iterator α₂ Id γ] |
| 50 | + (f : β → Iter (α := α₂) γ) (it : Iter (α := α) β) := |
| 51 | + (it.flatMapAfter f none : Iter γ) |
| 52 | + |
| 53 | +end Std.Iterators |
0 commit comments