简单问题。
给定一个字符串,我想输入一个字母,并让我的函数计算出该字母在字符串中出现的次数。
countLetters :: String -> Char -> Int
怎么做到这一点呢?
随着
countLetters :: String -> Char -> Int
countLetters str c = length $ filter (== c) str
这将获取str
中与c
相等的字符,然后计算其长度。
fold
。countLetters xs x = foldl (\count char -> if char == x then (count + 1) else count) 0 xs
然而,如果您想进行多个查询,构建查找表(即排序)就更有意义了。然后,您可以在O(1)
的时间内获取任意字符的重复次数(整个算法仍然是O(n)
)。
O(1)
。可以想象原始内存访问和指针算术运算,例如。 - Bartek Banachewicz
length
和filter
都是惰性函数,不是吗?我想 GHC 可以优化这样一个简单的情况,以产生一个单一的循环。 - bheklilr