Haskellでランダムな文字列を得る
先日のお題を、今度は Haskell でやってみた。Haskell はだいぶ忘れてるな。
乱数の使い方は↓ここを参考にした。
module Main where
import System.Environment ( getArgs )
import System.Random
import Control.Monad
strPool :: String
strPool = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
lenPool :: Int
lenPool = length strPool - 1
randomStr :: Int -> IO String
randomStr n = do
lis <- replicateM n $ (getStdRandom $ randomR (0, lenPool) :: IO Int)
return $ map (\ x -> strPool !! x) lis
main :: IO ()
main = do
argv <- getArgs
let n = read $ head argv
randStr <- randomStr n
putStrLn randStr
実行結果:
^o^ > runhaskell randomString.hs 20
GhDADFMuNNxrUBbpMXw3
