2017-02-07 50 views
1

我想計算字符串中的字符數與遞歸函數相結合,但它似乎沒有工作。在遞歸函數中計算字符串中Char的實例

{- 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)]

建議將不勝感激。

+0

只是可以肯定:在[這裏](HTTPS ://hackage.haskell.org/package/tables-0.4.1.1/docs/Data-Table.html)你正在使用的'Table'類型? – duplode

+0

我記得上一次作業問題中的'Table'。我認爲這只是一個關聯列表,也許是以前的作業分配來實現它。 – jberryman

+0

newtype表a b = T [(a,b)] –

回答

1

我似乎沒有「Table」模塊(在GHC中)。

您的代碼看起來很奇怪:您似乎遍歷所有字符,然後在計數時嘗試再次循環(但僅在列表的尾部)。

在另一個註釋中鏈接的Table模塊中有一個「count」函數。

你或許應該這樣做

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

,並刪除你的 「計數」 功能。

此外:您還需要處理表中第一次出現的字符。

1

您的表格看起來很像地圖。所以,如果你可以使用地圖,你可以嘗試以下方法:現在

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)],即一個Map Char Int類似Table Char Int你所要求的。如果需要,應該很容易實現轉換。

1

當您調用characterCountsAux xs _時,您將爲函數提供列表的其餘部分。這意味着,在第四次迭代您呼叫

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

這改變了表T [( '一個',2),( 'T',1),( 'R',1)]和上下一次迭代,我們有

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

它給你的最後T [( '一個',1),( 'T',1),( 'R',1)]。

一個天真的解決辦法是從XS去除x的所有出現即

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

當然它看起來並不十分有效......

+0

賓果!我正在考慮向後遞歸! –