计算haskell中的小写和大写字符

时间:2017-04-05 10:03:37

标签: haskell

我是haskell的初学者,我试图创建一个计算字符串中字符数的函数。我遇到的问题是我只能计算大写字母或小写字符的出现次数。我想要算上这两个。例如。对于字符串Mum,计数m的结果应为2。

我的功能现在看起来像这样:

import Data.Char
countList :: [Char] -> Char -> Int
countList str c = length $ filter (== c) str

您对解决此问题的建议是什么?

3 个答案:

答案 0 :(得分:1)

只需将全部转换为小写:

import Data.Char
countList :: [Char] -> Char -> Int
countList str c = length $ filter (== toLower c) $ map toLower str

你也可以使用fold,这里是一个例子:

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

答案 1 :(得分:1)

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',为大写字母匹配' char'的大写的任何字符过滤整个字符串。将新过滤的字符串输入“'长度'功能得到总数。

答案 2 :(得分:1)

获得toUpper c == toUpper char比较的一种巧妙方法是使用on组合器:

import Data.Function

countChar char = length . filter (on (==) toUpper char)
相关问题