I'm currently trying to solve the following exercise:
Given a list of Ints, count the number of times, an element is greater than the element that comes after it. The exercise forces me not to use explicit recursions.
Here are some example outputs given function :: [Int] -> Int:
function [1, 2, 3, 4, 5] == 0 -- only increasing numbers
function [5, 4, 3, 2, 1] == 4 -- only decreasing numbers
function [2, 1, 3, 1, 0, 4] == 3
-- 2 > 1
-- 3 > 1
-- 1 > 0
function [1] == 0 -- no successor
function [ ] == 0 -- no numbers at all
I imagined to use in some way foldl but after many attempts and not working idea I had to give up.
How can I count the number of times an element is greater than its successor without using recursion?
First we need to pair up the consecutive elements,
then we can process each pair
and now we can count them,
All the nested names belong to the same, shared, nested scope.
resultmust make use of the value ofbiggers, andbiggersrefers to the value ofpairswhich refers to the value offoo's parameter,xs. Make sure to put these code lines into the same definition, all indented by the same amount as the first one, forpairs, one under the other.Actually using a left fold is also possible:
I think you'll agree though that this is much less self-apparent than the first definition. Also note that it uses a "bang pattern",
!, together withfoldl', notfoldl, to do the counting as soon as possible as we go along the input list, not delaying it until all the input list is traversed in full asfoldlwould do, needlessly, harming the overall efficiency.