@@ -50,8 +50,10 @@ structure Nondet (m : Type → Type) [MonadBacktrack σ m] (α : Type) : Type wh
5050 toMLList : MLList m (α × σ)
5151
5252namespace Nondet
53+ variable {m : Type → Type }
5354
54- variable {m : Type → Type } [Monad m] [MonadBacktrack σ m]
55+ section Monad
56+ variable [Monad m] [MonadBacktrack σ m]
5557
5658/-- The empty nondeterministic value. -/
5759def nil : Nondet m α := .mk .nil
@@ -87,13 +89,10 @@ def singletonM (x : m α) : Nondet m α :=
8789/-- Convert a value to the singleton nondeterministic value. -/
8890def singleton (x : α) : Nondet m α := singletonM (pure x)
8991
90- /-- `Nondet m` is a monad. -/
91- instance : Monad (Nondet m) where
92+ /-- `Nondet m` is an alternative monad. -/
93+ instance : AlternativeMonad (Nondet m) where
9294 pure a := singletonM (pure a)
9395 bind := bind
94-
95- /-- `Nondet m` is an alternative monad. -/
96- instance : Alternative (Nondet m) where
9796 failure := .nil
9897 orElse x y := .mk <| x.toMLList.append fun _ => (y ()).toMLList
9998
@@ -164,21 +163,6 @@ All iterations of a non-deterministic function on an initial value.
164163partial def iterate (f : α → Nondet m α) (a : α) : Nondet m α :=
165164 singleton a <|> (f a).bind (iterate f)
166165
167- /--
168- Find the first alternative in a nondeterministic value, as a monadic value.
169- -/
170- def head [Alternative m] (L : Nondet m α) : m α := do
171- let (x, s) ← L.toMLList.head
172- restoreState s
173- return x
174-
175- /--
176- Find the value of a monadic function on the first alternative in a nondeterministic value
177- where the function succeeds.
178- -/
179- def firstM [Alternative m] (L : Nondet m α) (f : α → m (Option β)) : m β :=
180- L.filterMapM f |>.head
181-
182166/--
183167Convert a non-deterministic value into a lazy list, by discarding the backtrackable state.
184168-/
@@ -194,6 +178,28 @@ Convert a non-deterministic value into a list in the monad, by discarding the ba
194178-/
195179def toList' (L : Nondet m α) : m (List α) := L.toMLList.map (·.1 ) |>.force
196180
181+ end Monad
182+
183+ section AlternativeMonad
184+ variable [AlternativeMonad m] [MonadBacktrack σ m]
185+
186+ /--
187+ Find the first alternative in a nondeterministic value, as a monadic value.
188+ -/
189+ def head (L : Nondet m α) : m α := do
190+ let (x, s) ← L.toMLList.head
191+ restoreState s
192+ return x
193+
194+ /--
195+ Find the value of a monadic function on the first alternative in a nondeterministic value
196+ where the function succeeds.
197+ -/
198+ def firstM (L : Nondet m α) (f : α → m (Option β)) : m β :=
199+ L.filterMapM f |>.head
200+
201+ end AlternativeMonad
202+
197203end Nondet
198204
199205/-- The `Id` monad is trivially backtrackable, with state `Unit`. -/
0 commit comments