or1ko's diary

日々を書きます

19

言語処理100本ノック 2015

19. 各行の1コラム目の文字列の出現頻度を求め,出現頻度の高い順に並べる
各行の1列目の文字列の出現頻度を求め,その高い順に並べて表示せよ.確認にはcut, uniq, sortコマンドを用いよ.

19.hs

import System.Environment
import System.IO.UTF8 as I8
import qualified Data.Map as M
import Data.List 
import Data.Maybe

main = do
  filename <- getArgs >>= return . head
  body <- I8.readFile filename
  let cfs = M.fromList $ map (\x -> (head x, length x) ) $ group $ sort $ map (head . words) $ lines body
  I8.writeFile "19.out.txt" $ unlines $ sortBy (\x y -> compareByCf cfs (head $ words x) (head $ words y)) $ lines body

compareByCf cfs x y = fromMaybe EQ $ do
    xt <- M.lookup x cfs
    yt <- M.lookup y cfs
    return $ compare xt yt

実行結果が出現頻度順に並んでないと勘違いして、だいぶ悩んでしまった。
出現頻度順に並んでも、同じ単語が続けて現れるわけではないですね...。