Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Have you looked at Chris Okasaki's <a href="http://www.cs.tufts.edu/~nr/cs257/archive/chris-okasaki/breadth-first.pdf" rel="nofollow noreferrer">"Breadth-First Numbering: Lessons from a Small Exercise in Algorithm Design"</a>? The <code>Data.Tree</code> module includes a monadic tree builder named <code>unfoldTreeM_BF</code> that uses an algorithm adapted from that paper.</p> <p>Here's an example that I think corresponds to what you're doing:</p> <p>Suppose I want to search an infinite binary tree of strings where all the left children are the parent string plus "a", and the right children are the parent plus "bb". I could use <code>unfoldTreeM_BF</code> to search the tree breadth-first and return the searched tree up to the solution:</p> <pre><code>import Control.Monad.State import Data.Tree children :: String -&gt; [String] children x = [x ++ "a", x ++ "bb"] expand query x = do found &lt;- get if found then return (x, []) else do let (before, after) = break (==query) $ children x if null after then return (x, before) else do put True return (x, before ++ [head after]) searchBF query = (evalState $ unfoldTreeM_BF (expand query) []) False printSearchBF = drawTree . searchBF </code></pre> <p>This isn't terribly pretty, but it works. If I search for "aabb" I get exactly what I want:</p> <pre><code>| +- a | | | +- aa | | | | | +- aaa | | | | | `- aabb | | | `- abb | `- bb | +- bba | `- bbbb </code></pre> <p>If this is the kind of thing you're describing, it shouldn't be hard to adapt for your tree type.</p> <p>UPDATE: Here's a do-free version of <code>expand</code>, in case you're into this kind of thing:</p> <pre><code>expand q x = liftM ((,) x) $ get &gt;&gt;= expandChildren where checkChildren (before, []) = return before checkChildren (before, t:_) = put True &gt;&gt; return (before ++ [t]) expandChildren True = return [] expandChildren _ = checkChildren $ break (==q) $ children x </code></pre> <p>(Thanks to camccann for prodding me away from old control structure habits. I hope this version is more acceptable.)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload