<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-2584854963535200044</id><updated>2012-02-15T22:24:09.875-08:00</updated><title type='text'>Infinite mixtape</title><subtitle type='html'>Actor model, singer-songwriter, talk show host.</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://pmatiello.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2584854963535200044/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://pmatiello.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Pedro Matiello</name><uri>http://www.blogger.com/profile/03960374315127603066</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>2</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-2584854963535200044.post-4679902843739054404</id><published>2011-03-15T09:35:00.000-07:00</published><updated>2011-03-28T06:40:43.894-07:00</updated><title type='text'>Dependency Injection in Ruby as inspired by Scala</title><content type='html'>A recent &lt;a href="https://groups.google.com/d/topic/growing-object-oriented-software/7mVYbj1ZPzw/discussion"&gt;discussion&lt;/a&gt; in the &lt;a href="http://www.growing-object-oriented-software.com/"&gt;GOOS&lt;/a&gt;' group has lead me to consider different ways to compose objects in Ruby. Specifically, as module inclusion seems to be the favored approach for adding stuff to classes in Ruby, I've became interested in finding a more flexible idiom for this.&lt;br /&gt;&lt;br /&gt;The objective, therefore, is to define an instance variable in a module and be able to have it injected in instances of some class. Of course, as a Ruby noob, I'm forced to turn to other languages for inspiration. The solution in Scala, presented ahead, is kind of intuitive (I guess it can be considered a variation of the &lt;a href="http://jonasboner.com/2008/10/06/real-world-scala-dependency-injection-di.html"&gt;Cake pattern&lt;/a&gt;).&lt;br /&gt;&lt;br /&gt;Let's start defining a simple trait &lt;tt&gt;Lightsource&lt;/tt&gt;.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;&lt;br /&gt;trait Lightsource {&lt;br /&gt;  def on&lt;br /&gt;  def off&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The goal is to have a instance of a class implementing this trait injected in every instance of the class &lt;tt&gt;Room&lt;/tt&gt; below.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;&lt;br /&gt;abstract class Room {&lt;br /&gt;  val lightsource:Lightsource&lt;br /&gt;  def enter = lightsource.on&lt;br /&gt;  def leave = lightsource.off&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The injection can be performed by mixing-in the &lt;tt&gt;Room&lt;/tt&gt; class with traits designed to provide a &lt;tt&gt;Lightsource&lt;/tt&gt;. For example:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;&lt;br /&gt;trait FluorescentLamp {&lt;br /&gt;  val lightsource = new Lightsource {&lt;br /&gt;    def on = println("Sad light on")&lt;br /&gt;    def off = println("Sad light off")&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The actual composition reads nicely:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;&lt;br /&gt;val sadRoom = new Room with FluorescentLamp&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;If the fluorescent lamp is unsatisfactory, an alternative implementation can be provided:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;&lt;br /&gt;trait IncandescentLamp {&lt;br /&gt;  val lightsource = new Lightsource {&lt;br /&gt;    def on = println("Warm light on")&lt;br /&gt;    def off = println("Warm light off")&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;&lt;br /&gt;val warmRoom = new Room with IncandescentLamp&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;And I will stop at this point. Although there is opportunity for improvement, the implementation is satisfactory enough for me.&lt;br /&gt;&lt;br /&gt;Having succeeded at the Scala front, we can tackle the same issue using Ruby. Here, we find ourselves both unable and not required to declare interfaces, so we move directly to the definition of our &lt;tt&gt;Room&lt;/tt&gt; class.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: ruby"&gt;&lt;br /&gt;class Room&lt;br /&gt;  &lt;br /&gt;  def enter&lt;br /&gt;    @lightsource.on&lt;br /&gt;  end&lt;br /&gt;  &lt;br /&gt;  def leave&lt;br /&gt;    @lightsource.off&lt;br /&gt;  end&lt;br /&gt;  &lt;br /&gt;end&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The next step is to define a module responsible for providing an &lt;tt&gt;@lightsource&lt;/tt&gt; object to instances of the &lt;tt&gt;Room&lt;/tt&gt; class. For instance:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: ruby"&gt;&lt;br /&gt;module FluorescentLamp&lt;br /&gt;  class FluorescentLampImpl&lt;br /&gt;    def on&lt;br /&gt;      puts "Sad light on"&lt;br /&gt;    end&lt;br /&gt;  &lt;br /&gt;    def off&lt;br /&gt;      puts "Sad light off"&lt;br /&gt;    end&lt;br /&gt;  end&lt;br /&gt;  &lt;br /&gt;  def initialize(*args, &amp;b)&lt;br /&gt;    super&lt;br /&gt;    @lightsource = FluorescentLampImpl.new&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Alternatively:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: ruby"&gt;&lt;br /&gt;module IncandescentLamp&lt;br /&gt;  class IncandescentLampImpl&lt;br /&gt;    def on&lt;br /&gt;      puts "Warm light on"&lt;br /&gt;    end&lt;br /&gt;  &lt;br /&gt;    def off&lt;br /&gt;      puts "Warm light off"&lt;br /&gt;    end  &lt;br /&gt;  end&lt;br /&gt;  &lt;br /&gt;  def initialize(*args, &amp;b)&lt;br /&gt;    super&lt;br /&gt;    @lightsource = IncandescentLampImpl.new&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The actual composition does not read so nicely, but surely it can be improved by some sort of DSL. Being lazy, I'll skip that, though:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: ruby"&gt;&lt;br /&gt;sadRoom = Class.new(Room) do&lt;br /&gt;  include FluorescentLamp&lt;br /&gt;end.new&lt;br /&gt;&lt;br /&gt;warmRoom = Class.new(Room) do&lt;br /&gt;  include IncandescentLamp&lt;br /&gt;end.new&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Now, I'm suppose that this approach is not really within Ruby's orthodoxy, but I found it interesting nevertheless. Also, it surprised me that the Scala version is both cleaner and smaller than the Ruby version, while still providing the safety advantages of the static typing. Perhaps someone more skilled in Ruby might improve upon this.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2584854963535200044-4679902843739054404?l=pmatiello.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://pmatiello.blogspot.com/feeds/4679902843739054404/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://pmatiello.blogspot.com/2011/03/dependency-injection-in-ruby-as.html#comment-form' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2584854963535200044/posts/default/4679902843739054404'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2584854963535200044/posts/default/4679902843739054404'/><link rel='alternate' type='text/html' href='http://pmatiello.blogspot.com/2011/03/dependency-injection-in-ruby-as.html' title='Dependency Injection in Ruby as inspired by Scala'/><author><name>Pedro Matiello</name><uri>http://www.blogger.com/profile/03960374315127603066</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2584854963535200044.post-4494749071421162212</id><published>2010-08-22T11:06:00.001-07:00</published><updated>2010-08-23T05:14:24.923-07:00</updated><title type='text'>In which I give my own half-baked workaround to the lack of tail call optimization in Python</title><content type='html'>A &lt;span style="font-style:italic;"&gt;tail call&lt;/span&gt; is a function call such that it is the last action performed by a procedure. Therefore, the value returned by the caller procedure is the value returned by the called procedure. Many compilers and interpreters take advantage of this situation by using the caller's stack space to execute the called procedure, instead of allocating more space for it. Because no extra space is consumed by these calls, recursive tail calls can be nested at will without risk of overflowing the stack.&lt;br /&gt;&lt;br /&gt;Unfortunately, Python's interpreter does not perform this optimization trick. This can be easily learned from the example bellow:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&gt;&gt;&gt; def f(x):&lt;br /&gt;...     if (x&gt;0): return f(x-1)&lt;br /&gt;...     else: return 0&lt;br /&gt;... &lt;br /&gt;&gt;&gt;&gt; f(10)&lt;br /&gt;0&lt;br /&gt;&gt;&gt;&gt; f(1000)&lt;br /&gt;Traceback (most recent call last):&lt;br /&gt;  File "&lt;stdin&gt;", line 1, in &lt;module&gt;&lt;br /&gt;  File "&lt;stdin&gt;", line 2, in f&lt;br /&gt;  ...&lt;br /&gt;  File "&lt;stdin&gt;", line 2, in f&lt;br /&gt;RuntimeError: maximum recursion depth exceeded&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;This limitation in the interpreter is unlikely to disappear anytime soon, &lt;a href="http://neopythonic.blogspot.com/2009/04/tail-recursion-elimination.html"&gt;if at all&lt;/a&gt;. But, as tail call optimization is often very convenient, many &lt;a href="http://code.activestate.com/recipes/474088/"&gt;workarounds&lt;/a&gt; &lt;a href="http://code.activestate.com/recipes/496691/"&gt;were&lt;/a&gt; &lt;a href="http://lambda-the-ultimate.org/node/1331#comment-15165"&gt;written&lt;/a&gt;. These workarounds, with different levels of success, make use of &lt;a href="http://www.artima.com/weblogs/viewpost.jsp?thread=240808"&gt;decorators&lt;/a&gt; (which are functions that are executed before the decorated function) to control the execution of function calls.&lt;br /&gt;&lt;br /&gt;This post presents yet another solution, also based on decorators. The objective here is to avoid any limit on the number of recursive tail calls performed by a function by decorating it like bellow.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: python"&gt;&lt;br /&gt;@tail_recursive&lt;br /&gt;def f(x):&lt;br /&gt;    if (x&gt;0): return f(x-1)&lt;br /&gt;    else: return 0&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Every call to &lt;tt&gt;f&lt;/tt&gt;, then, will be intercepted by the decorator. Depending on the situation, it may continue and execute the function as usual, or return an object that may be used to perform the issued call later. The next listing presents the class for these objects (note that they store both a reference to a function and the arguments for a specific call).&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: python"&gt;&lt;br /&gt;class _continue(object):&lt;br /&gt;    &lt;br /&gt;    def __init__(self, func, *args, **kwargs):&lt;br /&gt;        self.func = func&lt;br /&gt;        self.args = args&lt;br /&gt;        self.kwargs = kwargs&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Each call to a decorated function &lt;tt&gt;f&lt;/tt&gt; implies on a independent run of the decorator code. On the first call, the decorator will allow &lt;tt&gt;f&lt;/tt&gt; to be executed, but instead of returning immediately, it will await for &lt;tt&gt;_continue&lt;/tt&gt; objects to execute them. Subsequent tail-recursive calls to &lt;tt&gt;f&lt;/tt&gt;, on the other hand, will just return an instance of &lt;tt&gt;_continue&lt;/tt&gt; filled with the call arguments without executing &lt;tt&gt;f&lt;/tt&gt;. Non tail-recursive are allowed to proceed unmolested.&lt;br /&gt;&lt;br /&gt;This approach keeps the stack from growing by avoiding nested calls whenever possible. Still, detecting recursion and tail recursion are tricky jobs. The former is performed by checking if penultimate frame in the stack refers to our decorator. The later is performed by &lt;a href="http://lambda-the-ultimate.org/node/1331#comment-15183"&gt;checking&lt;/a&gt; whether the &lt;a href="http://docs.python.org/release/2.7/library/dis.html#bytecodes"&gt;bytecode&lt;/a&gt; associated with the previous stack frame will return immediately after the completion of the call.&lt;br /&gt;&lt;br /&gt;The source code for the decorator follows. An instance of it is produced for each decorated function, and the method &lt;tt&gt;__call__&lt;/tt&gt; is executed on every invocation of them.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: python"&gt;&lt;br /&gt;OPCODES = [chr(opmap['RETURN_VALUE']), chr(opmap['POP_TOP'])]&lt;br /&gt;&lt;br /&gt;class tail_recursive(object):&lt;br /&gt;&lt;br /&gt;    def __init__(self, function):&lt;br /&gt;        self.function = function&lt;br /&gt;        &lt;br /&gt;    def _is_tailcall(self, frame):&lt;br /&gt;        caller_frame = frame.f_back&lt;br /&gt;        code = caller_frame.f_code.co_code&lt;br /&gt;        ip = caller_frame.f_lasti&lt;br /&gt;        return code[ip + 3] in OPCODES&lt;br /&gt;&lt;br /&gt;    def __call__(self, *args, **kwargs):&lt;br /&gt;        &lt;br /&gt;        frame = getframe()&lt;br /&gt;        &lt;br /&gt;        if frame.f_back and \&lt;br /&gt;            frame.f_back.f_back and \&lt;br /&gt;            frame.f_back.f_back.f_code == frame.f_code and \&lt;br /&gt;            self._is_tailcall(frame):&lt;br /&gt;            return _continue(self.function, *args, **kwargs)&lt;br /&gt;        &lt;br /&gt;        retval = self.function(*args, **kwargs)&lt;br /&gt;        while (True):&lt;br /&gt;            if (type(retval) == _continue):&lt;br /&gt;                retval = retval.func(*retval.args, **retval.kwargs)&lt;br /&gt;            else:&lt;br /&gt;                return retval&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;(The entire code, with tests, is available &lt;a href="http://bitbucket.org/pmatiello/tail-recursion"&gt;here&lt;/a&gt;.)&lt;br /&gt;&lt;br /&gt;Of course, this isn't true tail call optimization, but only a trick to achieve unlimited tail recursion. Properly implemented, the optimization should also provide increased performance by reducing the work needed to perform a function call; here, performance is actually harmed.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2584854963535200044-4494749071421162212?l=pmatiello.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://pmatiello.blogspot.com/feeds/4494749071421162212/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://pmatiello.blogspot.com/2010/08/in-which-i-give-my-own-half-baked_22.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2584854963535200044/posts/default/4494749071421162212'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2584854963535200044/posts/default/4494749071421162212'/><link rel='alternate' type='text/html' href='http://pmatiello.blogspot.com/2010/08/in-which-i-give-my-own-half-baked_22.html' title='In which I give my own half-baked workaround to the lack of tail call optimization in Python'/><author><name>Pedro Matiello</name><uri>http://www.blogger.com/profile/03960374315127603066</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>3</thr:total></entry></feed>
