我是一个初学者来haskell,我试着创建一个函数来计算字符串中的字符数。我遇到的问题是,我只能计算大写或小写字符的出现次数。我想统计他们两个。例如。对于字符串妈妈计数米的结果应该是2计算haskell中的大写字母和小写字符
我的功能,现在看起来是这样的:
import Data.Char
countList :: [Char] -> Char -> Int
countList str c = length $ filter (== c) str
你会有什么解决这是建议?
我是一个初学者来haskell,我试着创建一个函数来计算字符串中的字符数。我遇到的问题是,我只能计算大写或小写字符的出现次数。我想统计他们两个。例如。对于字符串妈妈计数米的结果应该是2计算haskell中的大写字母和小写字符
我的功能,现在看起来是这样的:
import Data.Char
countList :: [Char] -> Char -> Int
countList str c = length $ filter (== c) str
你会有什么解决这是建议?
import Data.Char (toUpper)
countChar :: Char -> [Char] -> Int
countChar char = length . filter (\c -> toUpper c == toUpper char)
countChar 's' "Stdudents" => 2
countChar 'S' "Sstudents" => 3
countChar 'S' "$tudent$$" => 0
给出一个字符 '炭',过滤整个字符串,用于任何大写字母与'char'大写匹配的字符。将新过滤的字符串提供给'length'函数以获得总计数。
只是变换大家小写:
import Data.Char
countList :: [Char] -> Char -> Int
countList str c = length $ filter (== toLower c) $ map toLower str
你也可以使用只使用fold
,这里ghci的例子:
Prelude Data.Char> let countList = \str c -> foldl (\x y -> x + if ((toLower y) == (toLower c)) then 1 else 0) 0 str
Prelude Data.Char> countList "AAaabCC" 'a'
4
一个巧妙的办法来获得toUpper c == toUpper char
比较是使用on
组合子:
import Data.Function
countChar char = length . filter (on (==) toUpper char)
爱用“上”。 –