【问题标题】:Haskell : how to count wordsHaskell:如何计算单词
【发布时间】:2018-06-16 05:17:51
【问题描述】:

我是新的 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]”匹配 • 在表达式中:“世界” 在‘countWords’的第一个参数中,即 '[“你好”,“你好”,“世界”]' 在表达式中:countWords ["hello", "hello", "world"]

谢谢

【问题讨论】:

  • words 需要一个字符串,而不是字符串列表。你确定你需要words吗?输入似乎已经被拆分成单词。

标签: haskell


【解决方案1】:

正如@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)]

【讨论】:

    【解决方案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]Strings 列表)传递给需要单个 String 的函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-06
      • 2018-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多