Number of loops in recursion

recursive loop example
for loop in recursive function python
recursion vs loop time complexity
recursive function inside for loop java
convert nested loop to recursion
recursive for loop javascript
nested for loop recursion python
python recursion append to list

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

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

Is recursion faster than loops?, You have a loop, and it is not obvious what each iteration is doing. Replace Iteration Many people worry about performace when using recursion. As always  I know the usual approach for "variable number of for loops" is said to use a recursive method. But I wonder if I could solve that without recursion and instead with using Stack, since you can bypass recursion with the use of a stack. My example:

The function you've written is filter (>=0). As Paul pointed out, the only step remaining is to count and length does that. We can transform the function step by step:

countPositivesRec :: [Int] -> [Int]
countPositivesRec [] = []
countPositivesRec (x:xs) | x >= 0 = x : tl
                         | otherwise = tl
                           where tl = countPositivesRec xs

Observe that xs is only used in the transformed form tl. That's what makes this a right fold.

onlypos1 = foldr maybekeep []
  where maybekeep x tl | x >= 0    = x : tl
                       | otherwise = tl

This operation is known as a filter, keeping only some parts:

onlypos2 = filter dowekeep
  where dowekeep x = x >= 0
onlypos3 = filter (\x -> x >= 0)
onlypos4 = filter (>= 0)

But this is of course only one of many possible approaches. For instance, strictness analysis can lead to the conclusion that length is better implemented as foldl' (\a _ -> succ a) 0 than foldr (\_ a -> succ a) 0. Indeed, that is its basic form in the Prelude:

length = foldl' (\c _ -> c+1) 0

We see that the combining function of length ignores the value of one argument, merely requires it to be there. This can naturally be merged with our condition that only some elements count:

lengthFilter1 = length . filter
lengthFilter2 pred = foldl' predCount 0
  where predCount c x = if pred x then c+1 else c
countNonNegative = lengthFilter2 nonNegative
  where nonNegative x = x >= 0

Incidentally, 0 isn't positive. It's non-negative.

In the end, Haskell's lazy lists mean we can use them to fuse traversals; length . filter (>=0) will only read the input list once, because the only reason it's processing results from filter is that length consumes them. The filtered list never exists as a fully expanded structure, unlike e.g. Python or PHP. This form is likely one of the most readable, but others exist, e.g.:

countNonNegatives xs = sum [1 | x <- xs, x >= 0]

Difference Between Recursion and Iteration (with Comparison Chart , recursion (i.e. picking a possible position for queen number row ). After each iteration, a recursive call is made to build upon the configuration  The most common application of recursion is in mathematics and computer science, where a function being defined is applied within its own definition. While this apparently defines an infinite number of instances (function values), it is often done in such a way that no infinite loop or infinite chain of references can occur.

You have

filtering p cons x r = if | p x -> cons x r | otherwise -> r

countPositives = length 
                   . filter (> 0)
               = foldr (\x r -> r + 1) 0                              -- r++
                   . foldr (filtering (> 0) (:)            ) []
               =     foldr (filtering (> 0) (\x r -> r + 1))  0

(since folds fuse by composing their reducer transformers, a-la "fold replaces the cons with a reducer operation, so why create the cons in the first place if it gonna be replaced anyway"), and

filtering (> 0) (\x r -> r + 1) x r 
                     = if | (> 0) x -> (\x r -> r + 1) x r | otherwise -> r
                     = if | x > 0 -> r + 1 | otherwise -> r

and thus, a version with fold and increment that you wanted,

countPositives = foldr (\x r -> if | x > 0 -> r + 1 | otherwise -> r) 0  -- r++

You can take it from here.

What's the use of a stack in recursion?, by a good compiler, when the code is properly written. In the factorial example above, we have reached the end of our necessary recursive calls when we get to the number 0. The recursive call, as you may have suspected, is when the function calls

function and its argument(s). To divide a problem into smaller pieces until reaching to solvable pieces. Then, to solve the problem by solving these small pieces of problem and merging the solutions to eachother. Given a number N, print all numbers from 1 to N using recursion or without using any loop. Example if N = 20 then print 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

While there are many different types of loops, almost each type of loop has the same basic function: iterating over data to analyze or manipulate  The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called as recursive function. Using recursive algorithm, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc.

However, as my technical interview skills grew, I encountered many LeetCode and HackerRank problems that cried out for recursion with their  A nice implementation of the varying number of For Loops problem: def for_recursive(number_of_loops, range_list, execute_function, current_index=0, iter_list

Comments
  • Err, length . countPositivesRec ?
  • i++ is fundamentally not Haskell; that's the postincrement operator in C, implying both defined computation order and mutable variables. The closest equivalent might be succ, which increments, but the new value is a distinct value.
  • filter (>=0) would avoid recursion and use library functions.
  • Where do you want the count to appear? Do you want a function with a type signature like [Int] -> (Int, [Int])?