使用递归在haskell中编写函数以确定字符列表中有多少个数字

我需要使用递归计算一个字符列表中的位数,因此对于此列表['a','b','c','1','2','3'],答案应为3

我已经设法使用此代码来做到这一点,但我正在努力使用递归来做到这一点

counta :: [Char] -> Int 
counta = length . filter isDigit

示例:

Main> counta ['a','3']

答案应为:3

aukle 回答:使用递归在haskell中编写函数以确定字符列表中有多少个数字

就像列表上的任何递归函数一样,首先要处理头部,然后在尾部递归。

counta :: [Char] -> Int
counta [] = _
counta (x:xs) = let this = _  -- something involving x
                    that = counta xs
                in _ -- something involving this and that

如果尝试对此进行编译,则编译器将准确告诉每个_应该是哪种类型,这将有助于您使用正确的表达式替换它们。

,

这是一种简单的方法-尝试使用它之前先了解它。

counta :: [Char] -> Int
counta [] = 0
counta (c:cs)
 | isDigit c = 1 + counta cs
 | otherwise = counta cs
本文链接:https://www.f2er.com/3156333.html

大家都在问