breve/src/Breve/Generator.hs

37 lines
890 B
Haskell

module Breve.Generator
( nameHash
, intHash
, Name
, Url
) where
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 Name = 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 Name
word = replicateM 10 letter where
vowels = "aeiou"
consonants = "bcdfghjklmnpqrstvwxyz"
letter = choice [vowels, consonants] >>= choice
-- SHA256 hash to seed a generator
intHash :: Url -> Int
intHash = decode . fromStrict . hash . pack
-- Assign a unique name to the url
nameHash :: Url -> Name
nameHash = evalState word . mkStdGen . intHash