List comprehensions with Applicative Functors

Brian Lonsdorf
InstructorBrian Lonsdorf
Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 5 years ago

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

[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.

Guy
Guy
~ 6 years ago

YES! Good stuff here. Belated thanks for all of the knowledge, and of course, the painstaking stop motion work :-)

Markdown supported.
Become a member to join the discussionEnroll Today