条件を満たす行を取り除く
条件を満たす行を取り除く
via http://d.hatena.ne.jp/gan2/20070706/1183708048
'#'で始まる行を取り除く問題。すげーひさしぶりに Haskell で書いてみる。
module Main where
import System
f :: String -> Bool
f (h:tl) | h == '#' = False
| otherwise = True
main :: IO ()
main = do fileName <- getArgs
contents <- readFile (head fileName)
putStr $ unlines $ filter f $ lines contents
実行。
^o^ >type sample.txt
hello!
# remove this
# don't remove this
bye!
^o^ >runhaskell filterline.hs sample.txt
hello!
# don't remove this
bye!
ファイルを1行ずつ処理するやり方を忘れててあせった。
追記:id:jmkさんからもらったアドバイスを追記しておこう。ありがとうございます。
f ('#':_) = False
f _ = True
- 元のコードでは空行に対応できてない。
- パターンマッチにはリテラルを使える。
