feat: add ForM -> ForIn adapter

This commit is contained in:
Mario Carneiro 2022-09-21 15:27:27 -04:00 committed by Leonardo de Moura
parent 9550db0e3b
commit 97bcc7fd7c
2 changed files with 15 additions and 1 deletions

View file

@ -83,6 +83,17 @@ instance (ε) [MonadExceptOf ε m] : MonadExceptOf ε (StateT σ m) := {
end
end StateT
/-- Adapter to create a ForIn instance from a ForM instance -/
@[inline] def ForM.forIn [Monad m] [ForM (StateT β (ExceptT β m)) ρ α]
(x : ρ) (b : β) (f : α → β → m (ForInStep β)) : m β := do
let g a b := .mk do
match ← f a b with
| .yield b' => pure (.ok (⟨⟩, b'))
| .done b' => pure (.error b')
match ← forM (m := StateT β (ExceptT β m)) (α := α) x g |>.run b |>.run with
| .ok a => pure a.2
| .error a => pure a
section
variable {σ : Type u} {m : Type u → Type v}

View file

@ -47,7 +47,7 @@ def mkIdx {n : Nat} (h : n > 0) (u : USize) : { u : USize // u.toNat < n } :=
foldBuckets m.buckets d f
@[inline] def forBucketsM {m : Type w → Type w} [Monad m] (data : HashSetBucket α) (f : α → m PUnit) : m PUnit :=
data.val.forM fun as=> as.forM f
data.val.forM fun as => as.forM f
@[inline] def forM {m : Type w → Type w} [Monad m] (f : α → m PUnit) (h : HashSetImp α) : m PUnit :=
forBucketsM h.buckets f
@ -162,6 +162,9 @@ variable {α : Type u} {_ : BEq α} {_ : Hashable α}
instance : ForM m (HashSet α) α where
forM := HashSet.forM
instance : ForIn m (HashSet α) α where
forIn := ForM.forIn
@[inline] def size (m : HashSet α) : Nat :=
match m with
| ⟨ {size := sz, ..}, _ ⟩ => sz