哈斯克尔:如何计算单词

时间:2018-01-06 17:10:00

标签: haskell

我是新的Haskell学习者,并试图计算单词,但有错误。如何更改代码并显示结果

countWords ["friend","she","she"] 
 >[("friend",1),("she",2)

这是代码

Prelude Data.List> countWords xs = map(\w -> (head w, length w)) 
 $group $ sort $ words xs
Prelude Data.List> countWords ["hello", "hello", "world"]

:101:13:错误:     •无法将预期类型“Char”与实际类型“[Char]”匹配     •在表达式中:"你好"       在“countWords”的第一个论点中,即         '["你好","你好","世界"]'       在表达式中:countWords [" hello"," hello"," world"]

:101:22:错误:     •无法将预期类型“Char”与实际类型“[Char]”匹配     •在表达式中:"你好"       在“countWords”的第一个论点中,即         '["你好","你好","世界"]'       在表达式中:countWords [" hello"," hello"," world"]

:101:31:错误:     •无法将预期类型“Char”与实际类型“[Char]”匹配     •在表达式中:" world"       在“countWords”的第一个论点中,即         '["你好","你好","世界"]'       在表达式中:countWords [" hello"," hello"," world"]

谢谢

2 个答案:

答案 0 :(得分:3)

正如@chi所说 - words :: String -> [String]所以要么将函数的输入类型更改为由空格分隔的单个字符串,要么省略words部分,即

countWords :: [String] -> [(String,Int)]
countWords xs = map (\w -> (head w, length w)) $ group $ sort xs

此示例用法:

Prelude Data.List> countWords ["hello", "hello", "world"]
> [("hello",2),("world",1)]

countWords :: String -> [(String,Int)]
countWords xs = map (\w -> (head w, length w)) $ group $ sort $ words xs

示例用法:

Prelude Data.List> countWords "hello hello world"
> [("hello",2),("world",1)]

答案 1 :(得分:2)

让我们将其分解为一个更简单的例子:

Prelude> xs = ["hello", "hello", "world"]
Prelude> words xs

<interactive>:2:7: error:
    • Couldn't match type ‘[Char]’ with ‘Char’
      Expected type: String
        Actual type: [[Char]]
    • In the first argument of ‘words’, namely ‘xs’
      In the expression: words xs
      In an equation for ‘it’: it = words xs

如您所见,我们在words的应用程序中遇到类型错误。进一步调查显示了我们的问题:

Prelude> :t words
words :: String -> [String]
Prelude> :t xs
xs :: [[Char]]

我们在此处看到wordsxs的类型。首先,words期望String作为其参数。但是,xs类型为[[Char]]。由于[Char]String相同,因此xs类型也可以[String]的形式提供。

现在我们看到了问题。您正在将[String]String s列表)传递给期望单String的函数。