単語を羅列したファイルから『逆引き広辞苑』みたいにソートする.
import System.IO main :: IO () main = do hin <- openFile "test_words.txt" ReadMode -- 読みこむファイル:単語リスト hout <- openFile "reverse_idx.txt" WriteMode -- 書き込むファイル:逆引きソートした単語リスト contents <- hGetContents hin let rev_idx = reverseEachWords -- もう一度各単語を逆にする. [[String]] $unduplicate -- 単語リストをソートして↑ [[String]] $reverseEachWords -- 単語リストの各単語を逆にして↑ [[String]] $words -- 単語ごとにリストに分解して↑ [[String]] contents -- 単語リストの文字列contentsを↑ [String] mapM_ (hPutStrLn hout) rev_idx hClose hout hClose hin -- ソート,重複なくす unduplicate::Ord a => [a] -> [a] unduplicate []=[] unduplicate (xs:xss)=unduplicate smaller++[xs]++unduplicate larger where smaller = [a | a <- xss, a < xs] larger = [b | b <- xss, b > xs] -- 単語リストの各要素にreverseを適用する reverseEachWords :: [[a]] -> [[a]] -- [a]=String:1単語 reverseEachWords xs= map reverse xs
実行例
↓test_words.txt
alfabeta
alto
astrofisica
bistro
blanca
calimba
clasica
musica
temperatur
tenor
tradisional
traversa
上記プログラム実行後
↓reverse_idx.txt
calimba
clasica
astrofisica
musica
blanca
traversa
alfabeta
tradisional
bistro
alto
tenor
temperatur