Skip to content

Instantly share code, notes, and snippets.

@lnicola
Created June 26, 2014 12:09
Show Gist options
  • Save lnicola/90d94d522ab2fa5863fe to your computer and use it in GitHub Desktop.
Save lnicola/90d94d522ab2fa5863fe to your computer and use it in GitHub Desktop.
module Main (main) where
import Prelude hiding (lookup)
import Data.Map (empty, insertWith', keys, lookup, size)
import System.Random (getStdRandom, randomR)
import Control.Monad (liftM)
import System.Environment (getArgs)
parse (a : b : c : t) = insertWith' comb (a, b) ([c], 1) $ parse $ b : c : t
where comb (l, m) (r, n) = (l ++ r, m + n)
parse _ = empty
pick (a, len) = liftM ((!!) a) $ getStdRandom $ randomR (0, len - 1)
markov m (x, y)
| otherwise = case lookup (x, y) m of
Just e -> pick e >>= \z -> liftM ((++) [x]) $ markov m (y, z)
otherwise -> return $! [x, y]
main = liftM (parse . words) (liftM head getArgs >>= readFile) >>= \m -> pick (keys m, size m) >>= markov m >>= putStrLn . unwords
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment