Reputation:
I'm trying to write a function that counts all numbers from a String in Haskell that have more than 1 digit.
Example 1: "Test1 Test12"
This should return 1 because only "Test12" has more than 1 digit.
Example 2: "Test1 Test12 Test123"
This should return 2 because only "Test12" and "Test123" have more than 1 digit.
This is how my code currently looks like:
import Data.Char
import Data.List
import Data.Function
digits = any ((1<) . length) . groupBy ((&&) `on` isDigit)
count :: String -> Int
count n = length (filter digits n)
Can anyone help me here?
Upvotes: 1
Views: 906
Reputation: 54058
Your problem can be broken down into
So the most basic thing that you want to do is count the number of digits in a word. Since a word is a string, that can be easily done by
count :: String -> Int
count word = length $ filter isDigit n
Then you want to determine if a word has more than one digit, which means it should return a Bool
:
hasManyDigits :: String -> Bool
hasManyDigits word = count word > 1
Then you want to find the number of words in a sentence with many digits:
wordsWithManyDigits :: String -> [String]
wordsWithManyDigits sentence = filter hasManyDigits $ words sentence
Then you want to count them
countWordsWithManyDigits :: String -> Int
countWordsWithManyDigits sentence = length $ wordsWithManyDigits sentence
The words
function splits a string on spaces, and the Data.Char.isDigit
function I think is pretty self-explanatory.
You could could combine these into a single function as
count :: String -> Int
count = length . filter ((> 1) . length . filter isDigit) . words
But I think that makes it lose its readability, even though it displays Haskell's ability to compose functions quite well.
Upvotes: 1