Here's a hint: follow the same recursion scheme as before, but return an int at every step.
countPositivesRec :: [Int] -> Int
---
countPositivesRec [] = 0 -- no positives in the empty list
countPositivesRec (x:xs) | x >= 0 = ??
| otherwise = ??
where tl = countPositivesRec xs
One you solve this, it can be rewritten using foldr
, if you want.
If you really want to use foldl
instead, I would suggest you start by defining a function f
such that
f (f (f 0 x0) x1) x2
evaluates to the number of positives in x0,x1,x2
. Then you can use foldl f 0 inputList
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…