入門 Haskell 練習問題 1.5

1. 空白行を数えない linesCount

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

2. バッククオートとシングルクオートで囲まれた部分を 1 単語として数える wordsCount

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