Haskell:字符串B中字符串A中每个char出现的总和

时间:2014-06-23 19:45:11

标签: haskell functional-programming fold

假设我有两个字符串,如何获得字符串B中字符串A中每个字符串出现的总和?

例如,我怎么知道,在字符串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"

2 个答案:

答案 0 :(得分:3)

作为第一次尝试,这应该可以解决问题:

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

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

答案 1 :(得分:3)

您可以使用列表解析来执行此操作:

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