我是新的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"]
谢谢
答案 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]]
我们在此处看到words
和xs
的类型。首先,words
期望String
作为其参数。但是,xs
类型为[[Char]]
。由于[Char]
与String
相同,因此xs
类型也可以[String]
的形式提供。
现在我们看到了问题。您正在将[String]
(String
s列表)传递给期望单String
的函数。