在尝试计算Haskell中每个段落的单词数时出错

时间:2013-12-29 17:33:57

标签: haskell functional-programming

我是Haskell和功能编程的新手。

我的目标是计算文本文档中的段落数量和每个段落中的单词数量。

我尝试通过以下步骤执行此操作:

  1. 我将段落转换为一行

    type Line      = String
    type Paragraph = [String]
    
    parify :: [Line] -> [Paragraph]
    parify [] = []
    parify ls 
      | null first = parify rest          
      | otherwise  = first : parify rest
      where first = takeWhile (/= "") ls  
        rest  = dropWhile (== "") . drop (length first) $ ls
    
  2. 然后我计算每行中的单词数

    lineWordCount :: Line -> Int
    lineWordCount = length . words
    
    singleParagraphCount :: Paragraph -> Int
    singleParagraphCount = sum . map lineWordCount
    
    
    
    wordsPerParagraph :: [String]-> [Int]
    wordsPerParagraph = map (singleParagraphCount) . parify . lines
    
  3. 我想要一个这样的结果:

    [12, 20, 8]
    

    分别与每个段落中的单词数量相同。

    我收到错误

    *** Term           : wordsPerParagraph
    *** Type           : [Char] -> [Int]
    *** Does not match : [String] -> [Int]
    

1 个答案:

答案 0 :(得分:3)

lines :: [Char] -> [String]使wordsPerParagraph成为wordsPerParagraph :: [Char] -> [Int],但您的签名为[String] -> [Int]

注意,String[Char]相同。所以也许你写的签名中有一个拼写错误,你想要String -> [Int]而不是[String] -> [Int]