Skip to content

Instantly share code, notes, and snippets.

@jooyunghan
Created July 18, 2014 15:39
Show Gist options
  • Save jooyunghan/0109d209cd75ef2d6ed1 to your computer and use it in GitHub Desktop.
Save jooyunghan/0109d209cd75ef2d6ed1 to your computer and use it in GitHub Desktop.
Random text generation (The Practice of Programming)
import Data.Map
import System.Random
group assoc = fromListWith (++) [(k,[v]) | (k,v) <- assoc]
mapChooseRandom g = zipWith chooseRandom (randoms g)
chooseRandom r list = list !! (r `mod` (length list))
learn str = group $ zip prefices suffices
where prefices = zip w (tail w)
suffices = tail (tail w)
w = ["",""] ++ (words str) ++ [""]
generate g prefixMap = takeWhile (/= "") suffices
where suffices = mapChooseRandom g $ fmap (prefixMap !) prefices
w = "" : "" : suffices
prefices = zip w (tail w)
main = do
contents <- getContents
g <- getStdGen
putStrLn $ unwords $ take 100 $ generate g $ learn contents
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment