2014-06-23 64 views
1

说我有两个字符串,我怎样才能得到字符串B中每个字符串出现在字符串A中的总和?Haskell:字符串B中每个字符出现的总和B

例如,我怎么能知道,在字符串someString:数字a +数字b ... +数字f?

sumOccurrencesOfCharsInString :: String -> String -> Int 
sumOccurrencesOfCharsInString str1 str2 = ? 

-- evaluating sumOccurrencesOfCharsInString someString notes should return 3+0+3+0+5+0+1= 12 
someString = "Evaluating sumOccurrencesOfCharsInString someString notes would return 12" 

notes = "abcdefg" 

回答

3

这可以使用列表理解做:

length [ s | s <- someString, s `elem` notes] 
+0

我喜欢这个,很好的替代品! –

+5

并考虑使用一个集合而不是'notes'的列表来从'O(nm)'到'O(n lg m)'。 –

3

作为第一次尝试,这应该做的伎俩:

countChars    :: Char -> String -> Int 
countChars c   = length . filter (== c) 

sumOccurrences   :: String -> String -> Int 
sumOccurrences as bs = sum [countChars a bs | a <- as] 
相关问题