問題 : 任意のテキストファイルの各行に行番号をつけて画面に出すプログラムを作れ。
解答例
-- numberlines.hs
-- runghc numberlines.hs filename
import Data.List
import System.Environment
import Text.Printf
main :: IO ()
main = do
args <- getArgs
contents <- readFile $ head args
let lineslist = lines contents
let newlines = zipWith (\n str -> printf "%6.6d\t%s" n str) [1:: Int ..] lineslist
let newcontents = unlines newlines
putStr newcontents
出力例
runghc numberlines.hs sample.txt
000001 There was an Old Man of Nantucket
000002 Who kept all his cash in a bucket.
000003 His daughter, called Nan,
000004 Ran away with a man,
000005 And as for the bucket, Nantucket.
000006 anonymous