3
讓特里數據結構,並添加一個字符串的函數定義如下:加字特里數據結構
data Trie = Trie { commonness :: Maybe Int
, children :: [(Char, Trie)]
} deriving (Show, Read, Eq)
-- trie returns an "empty" Trie
trie :: Trie
trie = Trie { commonness = Nothing, children = [] }
-- Add inserts a word to a Trie with a given frequency
-- stored after the last character
add :: String -> Int -> Trie -> Trie
add [] freq tree = tree { commonness = Just freq }
add (x:xs) freq tree = case lookup x (children tree) of
Nothing -> tree { children = (x, add xs freq trie):(children tree) }
Just subtree -> tree { children = (x, add xs freq subtree):(mydrop x (children tree)) }
where
mydrop :: Char -> [(Char, Trie)] -> [(Char, Trie)]
mydrop _ [] = []
mydrop elm (x:xs)
| (fst x) == elm = mydrop elm xs
| otherwise = x:(mydrop elm xs)
的問題是有關的情況下,更好的算法性格已經不當前存在水平。我想避免使用mydrop函數和重建兒童列表。
你能選擇一個答案,請。 – pat 2011-10-04 16:14:48