Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

haskell - Number of loops in recursion

I would like to count the number of positive integers/elements in the list. This returns the elements with positive values, how can I count the elements? would like to construct something like count(array(...)).

I would like to see a version with i++ and foldl. That would be very helpful.

countPositivesRec :: [Int] -> [Int]
countPositivesRec [] = []
countPositivesRec (x:xs) | x >= 0 = x : tl
                         | otherwise = tl
                           where tl = countPositivesRec xs
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...