to2yの日記

 | 

2006-07-29ふつける勉強会 第七回目 第七章 「関数」

練習問題

1,2,3

import Char
lstrip ::[Char] -> [Char]
lstrip = dropWhile isSpace

rstrip ::[Char] -> [Char]
rstrip = reverse . lstrip . reverse

strip ::[Char] -> [Char]
strip = rstrip . lstrip

4

main = do cs <- getContents
          putStr $ lastNLines 5 cs

lastNLines n = unlines . takeLast n . lines 
takeLast n = reverse . take n . reverse 

以下はポイントフリーと呼ぶのか

takeLast = \n -> reverse . take n . reverse

5

import System
import List

main = do cs <- getContents
          args <- getArgs
          putStr $ fgrep (head args) cs

fgrep :: String -> String -> String
fgrep pattern = unlines . filter match . lines
 where
     match :: String -> Bool
     match = any (isPrefixOf pattern) . tails
 |