List comprehensions with Applicative Functors

    Brian LonsdorfBrian Lonsdorf

    We annihilate the need for the ol' nested for loop using Applicatives.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson


    00:00 Let's see this pattern in your daily code where you have this loop here, within a loop, within a loop. Each loop runs faster, if you will, as it gets more nested. We can actually capture this immensely imperative code with a nice applicative factor here. We will use this to do so.

    00:19 We now have a list of X, let's just pretend X here. We apply that to 1,2,3. We have to apply to a list of 1,2,3 here. Let's just look at these results. We'll get our ,2,3 back. What if we apply this to another list? Let's go ahead and do X-Y here.

    00:42 Let me put this in a little template. Let's make this little function. Let's call this Merch. Merch will just generate a list of our merchandise here. Where we say we have a list of, who knows? T-shirt and sweater.

    01:00 From there, what you want to do is apply that to a list of large and medium and maybe small area. What this will do is run t-shirt with large, medium, small, then sweater with large, medium, small. This is a loop within a loop. We run this. We forgot to assign...actually call this area.

    01:25 There. We have t-shirt large, t-shirt medium, t-shirt small. Sweater large, sweater medium, sweater small. This will capture that pattern of nested loops. We can actually add a third nested loop if we want, with a Z here. X, Y, Z. We'll just go ahead and maybe we'll add one last thing here. We'll call it color. We only have the color black. That's it.

    01:45 This will run through everything. If we add another color later it will add another color for each size and shirt combinations. Now, we have t-shirt large, black, all the way down to sweater small, white and everything in between.

    01:58 This captures a pattern of a list comprehension. You may have seen in other languages like Python, or CoffeeScripts or Haskell. It's very useful in declarative nature and easy to add another case without actually cracking open loops within loops, within loops.

    02:11 It could be quite efficient and easy to optimize.