仅使用递归和模式匹配计算字符串中 'a' 和 'A' 字符的数量

Count the number of 'a' and 'A' characters in a string using only recursion and pattern matching

Implement the countA :: [Char] -> Int function that counts the number of occurrences of the characters a and A in a string.

Hint: Whether an item is a or A or some other element can be checked by using pattern matching.


例如:

countA "Appleapplet" == 2

countA "Nietzsche" == 0

我是学习 Haskell 的初学者,首先想到的是做一个 if-then-else 语句,但这可以' 是答案,因为我必须通过模式匹配来做到这一点。我什至不知道从哪里开始,我也不完全理解模式匹配是如何在列表上工作的。我无法在此练习中使用任何导入函数。

可以使用if-then-else来检查列表的第一个字符是否为'a''A',尽管模式匹配可能更优雅。

你需要的是一个递归函数,其基本情况是空列表 (1),在这种情况下,aA 出现的总次数是 0 .对于递归情况,我们使用非空列表,第一个字符为 x,列表尾部为 xs(可能为空)。在这种情况下,我们可以检查第一个字符 x 是否等于 'a''A' 并且在这种情况下增加递归调用的结果。因此我们可以将其实现为:

countA :: String -> Int
countA [] = …  -- (1)
contaA (x:xs) = if x == 'a' || x == 'A' then … else …  -- (2)

您还需要填写 部分。第二种情况(2)中的那些将需要进行递归调用。