Skip to content

Instantly share code, notes, and snippets.

@meditans
Last active October 23, 2015 15:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save meditans/979a0e486f7839e3b2be to your computer and use it in GitHub Desktop.
Save meditans/979a0e486f7839e3b2be to your computer and use it in GitHub Desktop.
Enumerating BinTrees by depth
import qualified Control.Monad.WeightedSearch as W
import Data.List (sortBy)
import Data.Ord (comparing)
import Control.Applicative
data BTree = Leaf | Branch BTree BTree deriving (Show, Eq)
-- I can lazily list all the btrees
btrees :: W.T Integer BTree
btrees = pure Leaf <|> W.weight 1 (Branch <$> btrees <*> btrees)
-- Now, let's consider this function
depth :: BTree -> Integer
depth Leaf = 0
depth (Branch b1 b2) = 1 + max (depth b1) (depth b2)
-- I'd like to generate the btrees in an order such that
-- `test btrees == True`, where":
test :: W.T Integer BTree -> Bool
test ts = ls == sortBy (comparing depth) ls
where ls = take 1000 $ W.toList ts
-- that is, trees should be ordered by depth
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment