printfは便利

ビンゴの結果を整形表示です。乱数の扱いは難しいで書いた重複無し乱数の続き。

import Data.List
import System.Random
import Text.Printf

line = 10

main = bingo(30) >>= putStrLn >> bingo(35) >>= putStrLn

bingo :: Int -> IO String
bingo n = do xs <- randomGet [1..n]
             return $ resultStr 1 xs

resultStr :: Int -> [Int] -> String
resultStr _ [] = []
resultStr n xs = let (ys, zs) = splitAt line xs
                 in formatStr [n .. n + length(ys) - 1] ++ "\n"
                    ++ formatStr ys ++ "\n"
                    ++ "\n"
                    ++ resultStr (n + line) zs

formatStr :: [Int] -> String
formatStr = concatMap (\n->printf " %2d" n)

randomGet :: (Eq a) => [a] -> IO [a]
randomGet [] = return []
randomGet xs = do n <- randomRIO (0, (length xs) - 1)
                  let a = xs !! n
                  ys <- randomGet(delete a xs)
                  return (a : ys)