noritsuguの日記

2006-07-12『入門 Haskell』 第1章

練習問題(p.31)

問題1

linesCount str = beginLine str
  where beginLine []    = 0
        beginLine (c:cs)
            | c == '\n' = beginLine cs
            | otherwise = inLine cs
        inLine []       = 0
        inLine (c:cs)
            | c == '\n' = 1 + beginLine cs
            | otherwise = inLine cs

実行結果

*Main> linesCount "foo\n"
1
*Main> linesCount "foo\nbar\n"
2
*Main> linesCount "\n"
0
*Main> linesCount "\n\n"
0
*Main> linesCount "\n\nfoo\n"
1
*Main> linesCount "\n\nfoo\n\nbar\n"
2
*Main> linesCount "foo\n\nbar\n\n"
2

問題2

import Char

wordsCount' str = outWords str
  where outWords []        = 0
        outWords (c:cs)
            | isAlphaNum c = 1 + inWords cs
            | c == '\''    = 1 + inQuote cs
            | otherwise    = outWords cs
        inWords []         = 0
        inWords (c:cs)
            | isAlphaNum c = inWords cs
            | c == '\''    = 1 + inQuote cs
            | otherwise    = outWords cs
        inQuote []         = 0
        inQuote (c:cs)
            | c == '\''    = outWords cs
            | otherwise    = inQuote cs

実行結果

*Main> wordsCount' "foo bar baz"
Loading package haskell98 ... linking ... done.
3
*Main> wordsCount' " foo bar baz "
3
*Main> wordsCount' "foo 'bar baz'"
2
*Main> wordsCount' "foo 'bar baz' hoge"
3
*Main> wordsCount' "foo 'bar baz'hoge"
3
*Main> wordsCount' "foo'bar baz'hoge"
3

練習問題(p.33)

import Char

wordsCount' str = outWords str
  where wordScan f [] = 0
        wordScan f (c:cs)
            | isAlphaNum c = f (inWords cs)
            | c == '\''    = 1 + inQuote cs
            | otherwise    = outWords cs
        outWords str = wordScan (\n -> 1 + n) str
        inWords str = wordScan id str
        inQuote []         = 0
        inQuote (c:cs)
            | c == '\''    = outWords cs
            | otherwise    = inQuote cs

実行結果

*Main> wordsCount' "foo bar baz"
Loading package haskell98 ... linking ... done.
3
*Main> wordsCount' " foo bar baz "
3
*Main> wordsCount' "foo 'bar baz'"
2
*Main> wordsCount' "foo 'bar baz' hoge"
3
*Main> wordsCount' "foo 'bar baz'hoge"
3
*Main> wordsCount' "foo'bar baz'hoge"
3
トラックバック - http://haskell.g.hatena.ne.jp/noritsugu/20060712