Created
June 26, 2014 12:09
-
-
Save lnicola/90d94d522ab2fa5863fe to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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