2006-08-25
■ [ふつケル] 7.9節 練習問題 fold
まずは自力で
num = 60
main = do cs <- getContents
putStr $ fold cs
fold :: String -> String
fold cs
| length cs <= num = cs
| otherwise = unlines $ concatMap wrapLine $ lines cs
where
wrapLine :: String -> [String]
wrapLine line = makeLines $ splitAt num line
makeLines :: (String, String) -> [String]
makeLines (fstString, sndString)
| length sndString > num = fstString : (makeLines $ splitAt num sndString)
| otherwise = fstString : sndString : []
wrapLine が激しく無駄な気がする。が消し方がわからん。
解答を写経
foldWith = 60
main = do cs <- getContents
putStr $ fold cs
fold cs = unlines $ concatMap foldLine $ lines cs
foldLine line = case splitAt foldWith line of
(s, []) -> [s]
(s, cont) -> s : foldLine cont
なるほどー、そこでcaseか。ガードと引数でのパターンマッチだと、splitAtの適応のために無駄な関数が一つ増えてしまうからなぁ。まだまだHaskellの感覚がつかめていない、ということだね。
■ [ふつケル] 8.4節 ポイントフリースタイル
やりすぎるとワケワカメになる予感。でも、変数が消えるというのはなかなか面白い。大抵のプログラミング言語の重要な要素である変数が、Haskellでは忌み嫌われている。言語の構成要素が少ないほうが、バグの原因が少ないから、その点でHaskellはプログラマをバグから解放してくれる可能性があるのかもしれない。でも、考え方になれないとなかなかきつい(´・ω・`)
■ [ふつケル] 8.6節 練習問題
まずは自力で
lstrip :: String -> String lstrip = dropWhile matchSpace matchSpace :: Char -> Bool matchSpace c = any (== c) [' ', '\t'] rstrip :: String -> String rstrip = reverse . lstrip . reverse strip :: String -> String strip = lstrip . rstrip
main = do cs <- getContents
putStrLn $ lastNLines 10 cs
lastNLines n = unlines . takeLast n . lines
takeLast n = reverse . take n . reverse
解答を写経
import Char lstrip :: String -> String lstrip = dropWhile isSpace rstrip :: String -> String rstrip = reverse . lstrip . reverse strip :: String -> String strip = rstrip . lstrip
main = do cs <- getContents
putStr $ lastNLines 10 cs
lastNLines n = unlines . takeLast n . lines
takeLast n = reverse . take n . reverse
isSpaceを自作しちゃった以外は上出来じゃない?matchSpaceは、簡単にスペース文字を追加できるようになってるから、あとからスペース文字を増やすこともできるし、セクションの勉強にもなったし、結果オーライってことで。
Mohammad2012/05/02 18:21I ltieallry jumped out of my chair and danced after reading this!
pavgsqfj2012/05/03 11:28xqgVIZ <a href="http://qjelzltbtkpo.com/">qjelzltbtkpo</a>
lyvvjyxlh2012/05/03 15:13K6fhGU , [url=http://ubxrucmfpltn.com/]ubxrucmfpltn[/url], [link=http://gughlccdruix.com/]gughlccdruix[/link], http://erinivqtnqns.com/
zqefrc2012/05/04 15:45jVpRsW <a href="http://egcyxsybgnsz.com/">egcyxsybgnsz</a>
jcisbfksmc2012/05/05 16:04pcPkE8 , [url=http://wjbzmimoanyc.com/]wjbzmimoanyc[/url], [link=http://rcfbqnmfncrw.com/]rcfbqnmfncrw[/link], http://saucybmfgegy.com/
jcisbfksmc2012/05/05 16:05pcPkE8 , [url=http://wjbzmimoanyc.com/]wjbzmimoanyc[/url], [link=http://rcfbqnmfncrw.com/]rcfbqnmfncrw[/link], http://saucybmfgegy.com/