Skip to content

Instantly share code, notes, and snippets.

@hyone
Created August 3, 2012 11:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hyone/3246709 to your computer and use it in GitHub Desktop.
Save hyone/3246709 to your computer and use it in GitHub Desktop.
Number of binary trees have N leaves with logging by Writer Monad
import Control.Arrow (first)
import Control.Monad.List
import Control.Monad.Writer
liftList :: (Monad m) => [a] -> ListT m a
liftList = ListT . return
splites :: Int -> [(Int, Int)]
splites n = [ (x, n - x) | x <- [1..n-1] ]
countW :: Int -> (Int, [String])
countW 1 = (1, [])
countW n = first sum . runWriter . runListT $ do
-- ListT (Writer [String]) Int
(i, j) <- liftList (splites n)
let cnt = fst (countW i) * fst (countW j)
lift $ tell ["(" ++ show i ++ ", " ++ show j ++ ") = " ++ show cnt]
return cnt
{-
ghci> countW 5
(14,["(1, 4) = 5","(2, 3) = 2","(3, 2) = 2","(4, 1) = 5"])
ghci> mapM_ putStrLn . snd $ countW 5
(1, 4) = 5
(2, 3) = 2
(3, 2) = 2
(4, 1) = 5
-}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment