@@ -183,12 +183,65 @@ reverseする
183183 レシピ8.6 ファイルから行をランダムに取り出す
184184---------------------------------------------
185185
186+ `Picking a Random Line from a File <http://docstore.mik.ua/orelly/perl/cookbook/ch08_07.htm >`_
187+
188+ 一行をランダムに取り出す。アルゴリズムはよく知られたやつ。
189+
190+ .. code-block :: haskell
191+
192+ import System.Environment
193+ import System.Random
194+ import Control.Applicative
195+
196+ randomNumGen :: Int -> IO Int
197+ randomNumGen n = getStdRandom (randomR (0, n))
198+
199+ choiceLine :: String -> [(Int, String)] -> IO String
200+ choiceLine s [] = return s
201+ choiceLine s ((n, line):cs) = do
202+ n' <- randomNumGen n
203+ if n' < 1 then choiceLine line cs
204+ else choiceLine s cs
205+
206+ main :: IO ()
207+ main = do
208+ args <- getArgs
209+ choiced <- choiceLine "" =<< zip [1..] <$> lines <$> readFile (args!!0)
210+ putStrLn choiced
211+
186212 レシピ8.7 ファイル内のすべての行をシャッフルしたい
187213---------------------------------------------------
188214
215+ `Randomizing All Lines <http://docstore.mik.ua/orelly/perl/cookbook/ch08_08.htm >`_
216+
217+ .. code-block :: haskell
218+
219+ import System.Environment
220+ import System.Random.Shuffle
221+ import Control.Applicative
222+
223+ main :: IO ()
224+ main = do
225+ args <- getArgs
226+ shuffled <- shuffleM =<< lines <$> readFile (args!!0)
227+ mapM_ putStrLn shuffled
228+
189229 レシピ8.8 ファイル内の特定の行を読み込む
190230-----------------------------------------
191231
232+ `Reading a Particular Line in a File <http://docstore.mik.ua/orelly/perl/cookbook/ch08_09.htm >`_
233+
234+ .. code-block :: haskell
235+
236+ import System.Environment
237+ import Control.Applicative
238+
239+ main :: IO ()
240+ main = do
241+ (file:lineNum:_) <- getArgs
242+ line <- flip (!!) (pred (read lineNum :: Int)) . lines <$> readFile file
243+ putStrLn line
244+
192245 レシピ8.9 可変長テキストフィールドを処理する
193246---------------------------------------------
194247
0 commit comments