[Haskell-beginners] Nested folds
Pietro Grandinetti
pietro.gra at hotmail.it
Sun Dec 13 10:39:36 UTC 2020
Hello,
I have a piece of code to represents Sentences, Paragraphs and the Content of an article. I added functions to count the words, code below. My questions:
1- Are these functions idiomatic?
2- Is this an efficient way to do the computation?
3- In different languages, I could (and would) give the same name `wordCount` to the three functions, because the type of the input would clarify the usage. But here GHC throws an error. What's the most idiomatic way to do this in Haskell?
type Sentence = String
type Paragraph = [Sentence]
type Content = [Paragraph]
sentWordCount :: Sentence -> Int
sentWordCount = length . words
parWordCount :: Paragraph -> Int
parWordCount = foldr ((+) . sentWordCount) 0
contWordCount :: Content -> Int
contWordCount = foldr ((+) . parWordCount) 0
I also have two more practical questions on the following two functions:
makeSentence :: String -> Sentence
makeSentence x = x::Sentence
sentCharCount :: Sentence -> Int
sentCharCount x = length $ filter (/= ' ') x
4- About `makeSentence` -- does it make sense to write a function like that just to encapsulate the String type?
5- About `sentCharCount` -- I cannot take the argument x off, the compilator complains. What's the reason?
Thanks,
-P
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20201213/96dbb0a4/attachment.html>
More information about the Beginners
mailing list