diff --git a/src/Alea/Diceware.hs b/src/Alea/Diceware.hs index 1f3fa7e..3b8a9bf 100644 --- a/src/Alea/Diceware.hs +++ b/src/Alea/Diceware.hs @@ -1,28 +1,42 @@ +{-# LANGUAGE OverloadedStrings #-} + module Alea.Diceware where -import Data.List (intersect, elemIndex) -import Alea.List +import Data.Monoid ((<>)) +import Data.List (intersect, elemIndex) +import Data.Text (Text, pack) +import System.Random +import qualified Data.Text as T --- Diceware dictionary type -type Diceware = [String] --- Parse file content to a Diceware -parseDiceware :: String -> Diceware -parseDiceware x = map (last . split ' ') $ lines x +-- | Diceware dictionary alias +type Diceware = [Text] --- Lookup word with dice index -readDiceware :: Diceware -> Int -> String -readDiceware d n = show n ++ " -> " ++ - case (undice n) of - Just x -> d !! x - Nothing -> "Does not exist" --- Lookup word with linear index -readDiceware' :: Diceware -> Int -> String +-- | Produces k random indices to be extracted +randIndices :: Int -> Int -> IO [Int] +randIndices n k = take k <$> randomRs (0, n-1) <$> newStdGen + + +-- | Parse file content to a Diceware +parseDiceware :: Text -> Diceware +parseDiceware = map (last . T.splitOn " ") . T.lines + + +-- | Lookup word with dice index +readDiceware :: Diceware -> Int -> Text +readDiceware d n = + pack (show n) <> " -> " <> + maybe "Does not exists" (d !!) (fromDice n) + + +-- | Lookup word with linear index +readDiceware' :: Diceware -> Int -> Text readDiceware' d n = d !! n --- Dice numbers to numbers --- Ex. undice 11121 == Just 6 -undice :: Int -> Maybe Int -undice n = elemIndex n . filter - (null . (intersect "0789") . show) $ [11111..66666] + +-- | Dice numbers to numbers +-- > fromDice 11121 == Just 6 +fromDice :: Int -> Maybe Int +fromDice n = elemIndex n (filter isDice [11111..66666]) + where isDice = null . (intersect "0789") . show diff --git a/src/Alea/List.hs b/src/Alea/List.hs deleted file mode 100644 index f1c35dd..0000000 --- a/src/Alea/List.hs +++ /dev/null @@ -1,10 +0,0 @@ -module Alea.List where - --- Split a list into a list of lists --- ex. split ',' "ab,cd,ef" == ["ab","cd","ef"] -split :: (Eq a) => a -> [a] -> [[a]] -split _ [] = [[]] -split delim (c:cs) - | c == delim = [] : rest - | otherwise = (c : head rest) : tail rest - where rest = split delim cs diff --git a/src/Main.hs b/src/Main.hs index 6bca93e..f360e14 100644 --- a/src/Main.hs +++ b/src/Main.hs @@ -61,7 +61,7 @@ diceware args@ProgArgs{..} = do if interactive then forever (fmap dice I.getLine >>= I.putStrLn) else do - indices <- genIndex size phraseLength + indices <- randIndices size phraseLength I.putStrLn $ T.unwords (map dice' indices) when (phrases > 1) $ diceware args {phrases = phrases - 1}