【问题标题】:Count the instances of Char in a String in a recursive function在递归函数中计算字符串中 Char 的实例
【发布时间】:2017-02-08 07:27:28
【问题描述】:

我正在尝试用递归函数计算字符串中的字符数,但它似乎不起作用。

{- characterCounts s
   PRE:  True
POST: a table that maps each character that occurs in s to the number of
     times the character occurs in s
EXAMPLES:
 -}
characterCounts :: String -> Table Char Int
characterCounts [] = Table.empty
characterCounts s = characterCountsAux s Table.empty

characterCountsAux:: String -> Table Char Int -> Table Char Int
characterCountsAux [] table = table
characterCountsAux (x:xs) table = characterCountsAux xs (Table.insert (table) x (count x (x:xs) ))


count:: Char -> String -> Int
count c s = length $ filter (==c) s

如果我这样做:characterCounts "atraa" 我应该得到T [('a',3),('t',1),('r',1)],但我得到的是T [('a',1),('t',1),('r',1)]

我们将不胜感激。

【问题讨论】:

  • 只是为了确定:this 是您使用的 Table 类型吗?
  • 我记得 Table 来自之前发布的作业问题。我认为这只是一个关联列表,可能是以前的家庭作业来实现它。
  • 新类型表 a b = T [(a,b)]

标签: haskell recursion


【解决方案1】:

我似乎没有“表格”模块(在 GHC 中)。

您的代码看起来很奇怪:您似乎遍历了所有字符,然后在计数时再次尝试循环(但仅遍历列表的尾部)。

在其他评论中链接的表格模块中有一个“计数”功能。

你应该做类似的事情

Table.insert table x ((count table x) + 1)

并删除您的“计数”功能。

补充:你还需要处理表格中第一次出现的字符。

【讨论】:

    【解决方案2】:

    您的表格看起来很像地图。因此,如果您可以使用地图,您可以尝试以下方法:

    import qualified Data.Map as M
    
    characterCounts :: [Char] -> M.Map Char Int
    characterCounts = foldr ((flip $ M.insertWith (+)) 1) M.empty
    

    现在,characterCounts "atraa" 返回fromList [('a',3),('r',1),('t',1)],即类似于您要求的Table Char IntMap Char Int。如果需要,应该很容易实现转换。

    【讨论】:

      【解决方案3】:

      当您调用 characterCountsAux xs _ 时,您将向您的函数提供列表的其余部分。这意味着在第 4 次迭代中您正在调用

      characterCountsAux "aa" T [('a',3),('t',1),('r',1)]
      

      将表格更改为 T [('a',2),('t',1),('r',1)] 并且在下一次迭代中我们有

      characterCountsAux "a" T [('a',2),('t',1),('r',1)]
      

      这会给你最终的 T[('a',1),('t',1),('r',1)]。

      一个天真的解决方案是从 xs 中删除所有出现的 x,即

      characterCountsAux (x:xs) table = characterCountsAux (filter (/= x) xs) (Table.insert (table) x (count x (x:xs) ))
      

      当然看起来效率不是很高……

      【讨论】:

      • 宾果游戏!我在考虑向后递归!
      猜你喜欢
      • 1970-01-01
      • 2019-07-04
      • 2020-03-15
      • 2014-03-31
      • 2013-07-21
      • 2014-04-06
      • 2022-01-09
      • 2021-02-24
      • 2016-01-25
      相关资源
      最近更新 更多