Refactoring from nested loops to enumerators and lambda's

Open in a window
Article lobste.rs

Refactoring from nested loops to enumerators and lambda's

Being an Old School Programmer I tend to naturally to write ever more deeply nested loops.

I hate myself when I do this because it's hard to test especially if some of the loops have nasty external side effects, it's hard to reuse, it's hard to refactor.

So I'm trying a new pattern....

Walk with me this is going to be long.... the example is a teaching example / dojo exercise for myself, so excuse me it it slightly contrived.

Here is a typical chunk of my code...

def nested( a, b, c)

   stuff_a = func_a(a)
   stuff_b = func_b(b)
   stuff_c = func_c(c)
   result = {}
   func_1( stuff_a) do |a1|
      stuff_d = func_d( a1 + stuff_b)
      func_2( stuff_d) do |a2|
         stuff_e = func_e( a2 + stuff_c)

         func_3( stuff_e) do |a3|

            result[a3] = func_f( a3)
         end
      end
   end

   result
end

It's fairly clear but has a few gotchas.

  • It's unclear which part of the code actually depends on the parameters.
  • In this toy example, the function is small... but a Real Life nested loop function like this can quickly grow hideously large.
  • As a "premature optimization" I have factored out subexpressions that do not alter within the loops, resulting in large scopes for variables that are only used inside the loops.
  • func_1(), func_2(), func_3() yield a stream of things....but a stream of things should just be an enumerable!

Ok, so try 2... reduce the scope of the stuff_* variables, a pessimation..

def nested( a, b, c)

   result = {}
   stuff_a = func_a(a)
   func_1( stuff_a) do |a1|
      stuff_b = func_b(b)
      stuff_d = func_d( a1 + stuff_b)
      func_2( stuff_d) do |a2|
         stuff_c = func_c(c)
         stuff_e = func_e( a2 + stuff_c)

         func_3( stuff_e) do |a3|

            result[a3] = func_f( a3)
         end
      end
   end

   result
end

I can extract the inner loop as a function, but my parameter list balloons...

def inner_2( a2, c, result)
   stuff_c = func_c(c)
   stuff_e = func_e( a2 + stuff_c)

   func_3( stuff_e) do |a3|
      result[a3] = func_f( a3)
   end
end

def nested( a, b, c)

   result = {}
   stuff_a = func_a(a)
   func_1( stuff_a) do |a1|
      stuff_b = func_b(b)
      stuff_d = func_d( a1 + stuff_b)
      func_2( stuff_d) do |a2|
         inner_2( a2, c, result)
      end
   end

   result
end

and I still reevaluate func_c for every loop!

If I use a closure instead, my parameter list collapses again...

def nested( a, b, c)

   result = {}
   stuff_a = func_a(a)
   func_1( stuff_a) do |a1|
      stuff_b = func_b(b)
      stuff_d = func_d( a1 + stuff_b)
      inner_2 = ->( a2){
         stuff_c = func_c(c)
         stuff_e = func_e( a2 + stuff_c)

         func_3( stuff_e) do |a3|
            result[a3] = func_f( a3)
         end
      }
      func_2( stuff_d) do |a2|
         inner_2.call( a2)
      end
   end

   result
end

But I still have a pessimization, so if I could pass an enumerator around.... So lets try convert func_2 to an enumerator....

def func_2( j)
   return to_enum( __method__, j) unless block_given?
   .....lots of code and a...
       yield  a2
   ...lots more code
end

def nested( a, b, c)

   result = {}
   stuff_a = func_a(a)
   func_1( stuff_a) do |a1|
      stuff_b = func_b(b)
      stuff_d = func_d( a1 + stuff_b)
      inner_2 = ->( a2){
         stuff_c = func_c(c)
         stuff_e = func_e( a2 + stuff_c)

         func_3( stuff_e) do |a3|
            result[a3] = func_f( a3)
         end
      }
      func_2( stuff_d).each do |a2|
         inner_2.call( a2)
      end
   end

   result
end

Then pass the enumerator in, and then we can stop the silly re-evaluation of func_c on every loop...

def nested( a, b, c)

   result = {}
   stuff_a = func_a(a)
   func_1( stuff_a) do |a1|
      stuff_b = func_b(b)
      stuff_d = func_d( a1 + stuff_b)
      inner_2 = ->( e){
         stuff_c = func_c(c)

         e.each do |a2|
            stuff_e = func_e( a2 + stuff_c)

            func_3( stuff_e) do |a3|
               result[a3] = func_f( a3)
            end
         end
      }

      inner_2.call( func_2( stuff_d))
   end

   result
end

And I can keep going with func_1....

def nested( a, b, c)

   result = {}
   stuff_a = func_a(a)
   inner_1 = ->( e1, inner_2){
      stuff_b = func_b(b)
      e1.each do |a1|
         stuff_d = func_d( a1 + stuff_b)

         inner_2.call( func_2( stuff_d))
      end
   }

   inner_2 = ->( e2){
      stuff_c = func_c(c)

      e2.each do |a2|
         stuff_e = func_e( a2 + stuff_c)

         func_3( stuff_e) do |a3|
            result[a3] = func_f( a3)
         end
      end
   }


   inner_1.call( func_1( stuff_a), inner_2)


   result
end

I can reduce scope of result and move it to the outermost level....

def nested( a, b, c)

   stuff_a = func_a(a)

   inner_1 = ->( e1, inner_2, &block){
      stuff_b = func_b(b)
      e1.each do |a1|
         stuff_d = func_d( a1 + stuff_b)

         inner_2.call( func_2( stuff_d), &block)
      end
   }

   inner_2 = ->( e2,&block){
      stuff_c = func_c(c)

      e2.each do |a2|
         stuff_e = func_e( a2 + stuff_c)

         func_3( stuff_e,&block)
      end
   }


   result = {}
   inner_1.call( func_1( stuff_a), inner_2) do |a3|
      result[a3] = func_f( a3)
   end
   result
end

I can convert the inner_1 lambda to a vanilla method and convert that to an Enumerator...

def inner_1( b, e1, inner_2, &block)
   return to_enum( __method__, b, e1, inner_2) unless block_given?
   stuff_b = func_b(b)
   e1.each do |a1|
      stuff_d = func_d( a1 + stuff_b)

      inner_2.call( func_2( stuff_d), &block)
   end
end

def nested( a, b, c)

   stuff_a = func_a(a)


   inner_2 = ->( e2,&block){
      stuff_c = func_c(c)

      e2.each do |a2|
         stuff_e = func_e( a2 + stuff_c)

         func_3( stuff_e,&block)
      end
   }


   result = {}
   inner_1( b, func_1( stuff_a), inner_2).each do |a3|
      result[a3] = func_f( a3)
   end
   result
end

Since inner_1 is just a vanilla enum, I can use each_with_object

I can also extract inner_2 as a method that returns a lambda...

def inner_1( b, e1, inner_2, &block)
   return to_enum( __method__, b, e1, inner_2) unless block_given?
   stuff_b = func_b(b)
   e1.each do |a1|
      stuff_d = func_d( a1 + stuff_b)

      inner_2.call( func_2( stuff_d), &block)
   end
end

def inner_2( c)
   stuff_c = func_c(c)

   ->( e2,&block){

      e2.each do |a2|
         stuff_e = func_e( a2 + stuff_c)

         func_3( stuff_e,&block)
      end
   }
end

def nested( a, b, c)

   stuff_a = func_a(a)

   inner_1( b, func_1( stuff_a), inner_2( c)).each_with_object({}) do |a3, result|
      result[a3] = func_f( a3)
   end
end

Note func_c is now only evaluated once again, It's testable it, it's reusable in the vanilla "everything is just Enumerable" sense.

Discussion 2 comments · 3 points · JohnCarter · 2019-06-28
Open on Lobsters
Loading the discussion…

Domain filters

Stories from these domains are hidden from every list. Subdomains match too: blocking substack.com also hides danluu.substack.com. The list is kept in this browser only.

Help

Keyboard

j / k
Move down and up the story list. The arrow keys scroll whatever has focus.
Enter
Open the marked story in a window.
]
Open the next story in the list in place of the one in front. Back returns to it.
p
Pin or unpin the marked story, which keeps it in Pinned.
n / N
Move to the next or previous top-level comment in the window in front.
c
Collapse or expand that comment.
f
Hide or show the story list.
Esc
Close a menu or this help.
Access key m
Go to the menu bar. Most browsers take it with Alt on Windows and Linux, and Safari with Control and Option.
?
Show this help.

Windows

Each story opens in a window holding its article above its discussion; drag the bar between them to share the room differently. A window can be moved by its title bar, resized from any edge, snapped to a half or a corner by dragging it there, maximised, or minimised to the bar at the foot of the page. Open several stories to compare them, and switch between them from that bar. A window's Next story link reads on down the list in the same window.

A link in a comment or an article to another Hacker News or Lobsters thread opens that thread in a window too. A link to a single HN comment opens the comment above its replies.

While a story's window is in front, the Story and Discussion menus in the menu bar hold its commands: pinning, Next story, sorting, collapsing every thread, jumping to the first new comment. Each window also remembers where you were in its article and discussion, so a reload, or Back to a story that Next took you past, finds your place again. Closing a window forgets it.

The whole arrangement lives in the address, so a bookmark or a shared link brings it back, and Back undoes the last change. Moving between Hacker News, Lobsters, their lists, Pinned and Find changes only the list, and leaves the windows open.

The list

The pin at the start of a row keeps the story in Pinned, and the cross at its end hides it. Pinned can be narrowed by words in the title, site or author, by source, and to the stories you haven't opened yet, and ordered by when you pinned them, by points or by comments; the filters are part of the address, so a filtered view can be bookmarked. Scroll past the end of the list to load more. Domain filters, in the View menu, hide every story from a site.

Applets

The Applets menu in the menu bar holds three tools, each a window of its own. Replies to me takes your Hacker News user name and lists the replies to your last thirty comments and stories, checking again every three minutes while it is open, and marking what is new since you last marked them read. Look up a user opens a profile on Hacker News or Lobsters, with their submissions and recent comments, as a commenter's name in any discussion does; the bar at the top of a profile looks up someone else in the same window, and Back returns to the one before. Who is hiring? filters the posts of HN's monthly hiring threads by the words you type.

They read only what the sites publish to everyone, so none of them asks for a login, and your user name stays in this browser.

Find

Find takes any link and lists every time it was submitted to Hacker News and Lobsters, so you can read each discussion of it.

About

YAVCHN never sees your Hacker News or Lobsters login. The discussion is fetched from each site's public API; to vote or reply, follow the link above the discussion, or the arrow beside a comment, to the source's own site. Pins, hidden stories, filters and layout are kept in this browser only.

Open source: github.com/paulmooreparks/yavchn. Built with PUDL.