I implement the monad transformer MaybeT.
newtype MaybeT m a =
MaybeT { runMaybeT :: m (Maybe a) }
Then, I write a monad for backtracking.
newtype BackT m a =
BackT { unBackT :: MaybeT m (a, BackT m a) }
Here,Back m a has recursion definition.
In my mind, there are isomorphisms.
unBackT
BackT m a <-------------------> MaybeT m (a, BackT m a)
BackT(constructor)
runMaybeT
MaybeT m (a, BackT m a) <------------------> m (Maybe (a, BackT m a))
MaybeT(constructor)
Thus, I actually get something like
m (Just(1, m (Just(2, m (Just(3, m (Just(4, Nothing))))))))
In the example given above, there are 4 computations(Monad is computation?). I need something called runBackT to collect them using [].
Thanks for the answer from @rampion , and I remove some meaningless questions.
What is the type of results? It should be something depending on(Answer: The type of results should bem.m a.)How to collect all results? Is it possible?(Answer: Monadm adoes not guarantee to have a way to get an "unwrapped" type.)- How to collect all arguments like 1, 2, 3, 4 in example. It's type should be
[a]. Does such aBackT m a -> [a]function exist? Or, can we only getm [a]? (Answer:OnlyBackT m a -> m [a]might exist.)
Update
Monad can be divided into two classes: "opened monads" (like [], Maybe) and "closed monads" (like IO). The "opened monads" have functions with type m a -> b to open them. e.g.
showMaybe :: (Show a) => Maybe a -> String
showMaybe mx = case mx of
Nothing -> "Nothing"
Just x -> show x
- How to implement
(Monad m, Show m) => BackT m a -> [String]? - More generally,
Monad m => (m a -> b) -> BackT m a -> [b]? - Under what conditions, does
Monad m => BackT m a -> [m a]exist?BackT m asequences computationsm arecursive by cross-recursive definition. How to change it into iteration[m a]? If it exists, how to implement it? We can mapm a -> bto[m a], and question (2) will be solved. Monad m => (m a -> a) -> BackT m a -> m [a]? Just wrap the result of question(2) by constructorm.
Therefore, the key point is question (3).
The most difficult part for me is recursion definition of BackT m a. I'd appreciate it if you could show the implement or share some advice.
Answers only for question (3) is OK.
Update
Thanks for comments from @rampion, the ListT from list-t package answered my questions.
BackTis isomorphic toListTfrom thelist-tpackage - rampionm Maybe (a, BackT m a)should bem (Maybe (a, BackT m a))andm Just(1, m Just(2, m Just(3, m Just(4, Nothing))))should bem (Just(1, m (Just(2, m (Just(3, m (Just(4, Nothing))))))))- rampionListT. It solved the problem completely. - Da Li