0:05Skip to 0 minutes and 5 secondsWIM: Hi. In this tutorial, I want to explain the relationship between maps and folds in Haskell and loops in an imperative language. For the imperative language, I will use the scripting language Ruby, but you can do this really in any imperative language. So suppose we want to perform a map on a list using function f.

2:59Skip to 2 minutes and 59 secondsSo to get a bit similar result in Ruby, we can move this. And now it looks a bit more like the Haskell we saw. Clearly, the for loop is a very straightforward implementation of the map. So, for every element in the list, we push a new element on to the new list lst_. So what about folds. Now, suppose we have operation g is (/).

4:03Skip to 4 minutes and 3 secondsSo, now, let's do the same thing in Ruby. We have to create the function g. And we can't do this neat thing like we do in Haskell, so we have to actually say def g(accumulator and element).

6:16Skip to 6 minutes and 16 secondsAnd indeed, we do get the same result. So, essentially, what we see is that the fold operations are actually loops that change updatable variable using a function that uses the same variable. So g uses acc and returns and a new value-based on acc and elt, and it sends this to acc. And g_ does the same thing. And you have to explicitly specify the order of the arguments, so that when you traverse the list from the right, you get the same result as in Haskell. For the map, it's much simpler. So you take a list, you apply the function on each element of the list, and this result is pushed onto the new list.

7:18Skip to 7 minutes and 18 secondsNote, again, how much neater all this is in Haskell, so each of these folds and maps are just single lines. In Ruby, we have to write explicit functions for each of them. But the main message is that if you are in some doubt of how a fold, left or a right fold, or a map works in Haskell, you can always try and think of this alternative-- how it works in an imperative language with for loops. And from there, you can easily reason about what your maps or folds should look like.

Functional Maps and Folds versus Imperative Loops

This tutorial explains the relationship between the higher-order list operations map, foldl and foldr and loops in an imperative language.