[英]Haskell : how to count words
我是新的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]'相匹配•在表达式中:“ hello”在'countWords'的第一个参数中,即'[“ hello”,“ hello“,” world“]'在表达式中:countWords [” hello“,” hello“,” world“]
:101:22:错误:•无法将预期类型'Char'与实际类型'[Char]'相匹配•在表达式中:“ hello”在'countWords'的第一个参数中,即'[“ hello”,“ hello“,” world“]'在表达式中:countWords [” hello“,” hello“,” world“]
:101:31:错误:•无法将期望的类型'Char'与实际类型'[Char]'相匹配•在表达式中:“ world”在'countWords'的第一个参数中,即'[“ hello”,“ hello“,” world“]'在表达式中:countWords [” hello“,” hello“,” world“]
谢谢
正如@chi所说的-words words :: String -> [String]
String- words :: String -> [String]
这样,您可以将函数的输入类型更改为由空格分隔的单个单词字符串,或者省略words
part,即
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)]
让我们将其分解为一个更简单的示例:
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
的列表)传递给需要单个String
的函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.