breve/Breve/Generator.hs
2015-04-08 22:13:02 +02:00

38 lines
907 B
Haskell

module Breve.Generator
( wordID
, hashID
, Word
, Url
) where
import Control.Applicative
import Control.Monad.State
import System.Random
import Crypto.Hash.SHA256 (hash)
import Data.Binary (decode)
import Data.ByteString.Char8 (pack)
import Data.ByteString.Lazy (fromStrict)
type Word = String
type Url = String
-- Choose a random element of a list
choice :: [a] -> State StdGen a
choice xs = (xs !!) <$> randomSt (0, length xs - 1)
where randomSt = state . randomR
-- Generate a random phonetic string
word :: State StdGen Word
word = replicateM 10 letter where
vowels = "aeiou"
consonants = "bcdfghjklmnpqrstvwxyz"
letter = choice [vowels, consonants] >>= choice
-- SHA256 hash to seed a generator
hashID :: Url -> Int
hashID = decode . fromStrict . hash . pack
-- Assing a unique word to the url
wordID :: Url -> Word
wordID = evalState word . mkStdGen . hashID