練習問題

また間があいてしまった。たまには触らないと鈍る−−ってほどなれてるわけでもないけど−−ので,練習問題をやってみる。

「ISBN:4797336021:title」,p.191 から。

標準入力から読み込んだ各行を幅60バイトに納まるように折り返すコマンド,
foldを書きなさい。単語境界やマルチバイト文字は考えなくて構いません。

問題は60バイトだけど30バイトでやってみた。

 module Main (main) where
 
 import System
 
 
 fold :: Int -> String -> String
 fold n cs = let (h, t) = splitAt n cs
             in  if null t  then h  else h ++ "\n" ++ fold n t
 
 
 main :: IO ()
 main = do cs <- getContents
           putStr $ unlines $ map (fold 30) $ lines cs

結果

 >runghc fold.hs < fold.hs
 module Main (main) where
 
 import System
 
 
 fold :: Int -> String -> Strin
 g
 fold n cs = let (h, t) = split
 At n cs
             in  if null t  the
 n h  else h ++ "\n" ++ fold n
 t
 
 
 main :: IO ()
 main = do cs <- getContents
           putStr $ unlines $ m
 ap (fold 30) $ lines cs