I’m struggling with Haskell, and the idea of using recursion to iterate over things.
For instance, how would
// this might seem silly but I need to do it
list1 = empty list
list2 = list of numbers
for i from 0 to N // N being a positive integer
for each number in list2
if number == i, add to list1
translate into the ‘functional paradigm’? Any guidance would be appreciated.
Going step by step:
We’ll take this as a given, so
list2is still just a list of numbers.The correct way to do this in Haskell is generally with a list. Laziness means that the values will be computed only when used, so traversing a list from 0 to N ends up being the same thing as the loop you have here. So, just
[0..n]will do the trick; we just need to figure out what to do with it.Given “for each” we can deduce that we’ll need to traverse the entirety of
list2here; what we do with it, we don’t know yet.We’re building
list1as we go, so ideally we want that to be the final result of the expression. That also means that at each recursive step, we want the result to be thelist1we have “so far”. To do that, we’ll need to make sure we pass each step’s result along as we go.So, getting down to the meat of it:
The
filterfunction finds all the elements in a list matching some predicate; we’ll usefilter (== i) list2here to find what we’re after, then append that to the previous step’s result. So each step will look like this:That handles the inner loop. Stepping back outwards, we need to run this for each value
ifrom the list[0..n], with thelist1value being passed along at each step. This is exactly what fold functions are for, and in this casestepis exactly what we need for a left fold:If you’re wondering where the recursion is, both
filterandfoldlare doing that for us. As a rule of thumb, it’s usually better to avoid direct recursion when there are higher-level functions to do it for you.That said, the algorithm here is silly in multiple ways, but I didn’t want to get into that because it seemed like it would distract from your actual question more than it would help.