PBP: 073 List Selections

The Best Practice is to use grep and first instead of for to refine or search lists.  Again, there are good reasons, but I find it difficult, and am only improving with deliberate practice.

Rather than searching your lists with a for loop, use the right tool for the job.  Use grep or first.  They’re written in optimized C, they’re going to be faster, and they again convey some information to the reader of what you’re doing.

It’s a great idea, and I wish I were better at it.  I find the blocks for these really difficult to read; I have a hard time piecing together what they’ll be operating on and what they’ll be matching.  In bad cases, I have to rewrite the thing as a for loop to understand it.

It’s worse if they’ve been chained together.

It’s worse if there’s map blocks dumped into that chain.

I struggle to comprehend these “apply this code to this set” functions.  It’s one reason I’m less fond of ruby than some – it can use this construct in a lot more places.

This is entirely a weakness of mine, and I need to overcome it.  It has been difficult, and remains so,

In addition, Mr. Conway suggests the heavy use of things in List::Utils.  I wish I knew how to get into my head what was there and what they did.  I think it’s a great idea, but never think of them.  They’re a module, in my mind, and not a builtin.  Worse, they’re a module with a generic name so I never seem to think of them.

At the end of the day, every time I think, “for loop!” I need to stop and make sure it’s the right tool for that job.

2 Responses to “PBP: 073 List Selections”

  1. Michael J says:

    It’s actually List::Util (not Utils)

    … but to List::MoreUtils to confuse matters.

Leave a Reply