challenge 条件を満たす行を取り除く

ファイルから1行ずつ読み込み、"#"で始まる行だけを取り除いてファイルに出力するコードを書いてください。

サンプル入力

hello!
# remove this
 # don't remove this
bye!
サンプル出力
hello!
 # don't remove this
bye!

Posted feedbacks - Haskell

1
main = getContents >>= putStr . unlines . filter (('#' /=) . head) . lines

すでにほとんど同じものがありますが :)
1
2
3
4
5
6
module Main (main) where
main :: IO ()
main = putStr . unlines . filter (null ||| ('#'/=) . head) . lines =<< getContents
infixr 2 |||
(|||) :: (a -> Bool) -> (a -> Bool) -> (a -> Bool)
(p ||| q) x = if p x then True else q x

空行に対応していなかったので書き直し

1
2
3
4
main = getContents >>= mapM_ putStrLn' . lines

putStrLn' ('#':_) = return ()
putStrLn' xs = putStrLn xs

最初に書いたコードが 空白行があるとバグる事に気がついて あせりながら条件を加えました

1
main=let f[]=True;f(x:_)=x/='#'in do readFile"doukaku10.txt">>=writeFile "doukaku10.out".unlines.filter f.lines

Index

Feed

Other

Link

Pathtraq

loading...