「入門Haskell」のp.31から二つ目。
② 単語のカウント方法として,`Theory of Everything’のようにバッククォートとシングルクォートで囲まれたパートを,1つの単語として表現するように wordsCount を拡張しなさい。
オリジナルの wordsCount。
wordsCount str = outWords str
where outWords [] = 0
outWords (c:cs)
| isAlphaNum c = 1 + inWords cs
| otherwise = outWords cs
inWords [] = 0
inWords (c:cs)
| isAlphaNum c = inWords cs
| otherwise = outWords cs
拡張版。
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)
| c == '`' = 1 + inQuote cs
| isAlphaNum c = inWords cs
| otherwise = outWords cs
inQuote [] = 0
inQuote (c:cs)
| c == '\'' = outWords cs
| otherwise = inQuote cs
結果。
*Main> wordsCount "`Theory of Everything' by Greg Egan" 4