Fibers: a solution

August 15, 2008 – 11:24 am

Here I will post a solution to the Fibers exercise… Post your solutions as comments.

Your code should at least pass the following simple test:

require 'fiber_stack'
require 'test/unit'

class FiberStackTest < Test::Unit::TestCase
      
  def test_simple
    fs = FiberStack.new
    assert fs.empty?
    fs.push 'a'
    fs.push 'b'
    assert_equal 2, fs.size
    
    assert_equal 'b', fs.pop
    assert_equal 1, fs.size
    assert_equal 'a', fs.pop
    assert fs.empty?
    assert_equal 0, fs.size
    
    assert_nil fs.pop
    assert fs.empty?
    assert_equal 0, fs.size
    
    fs.push 'c'
    assert_equal false, fs.empty?
    assert_equal 1, fs.size
    
    assert_equal 'c', fs.pop
    assert fs.empty?
    assert_equal 0, fs.size
  end
end

require 'test/unit/ui/console/testrunner'
Test::Unit::UI::Console::TestRunner.run(FiberStackTest)

with the following result:

krukow:~/Projects/private/Fiber/lib$ ruby run_stack.rb
Loaded suite FiberStackTest
Started
.
Finished in 0.002572 seconds.

1 tests, 15 assertions, 0 failures, 0 errors
krukow:~/Projects/private/Fiber/lib$

Have fun ;-)

  1. 4 Responses to “Fibers: a solution”

  2. http://pastie.org/257599

    By Hongli Lai on Aug 21, 2008

  3. Exactly ;-)

    By admin on Aug 22, 2008

  4. Here is my own solution.

    class FiberStack
      def initialize 
        @f = Fiber.new {irb}
        @f.resume #start irb loop
      end
     
      def empty?
        size == 0
      end
     
      def size
        @f.resume(:size).tap {@f.resume}
      end
      
      def push o
        @f.resume :push, o
      end
      
      def pop
        @f.resume :pop unless empty?
      end
      
      private
      def irb o = nil, size = 0
        popped = nil #initially nothing has been popped
        loop do
          cmd, val = Fiber.yield popped
          return o if cmd == :pop #pop command, return one level on call stack
          if cmd == :size
            Fiber.yield size 
          else
            popped = irb val, size+1 #recursive call to put val on call stack
          end
        end
      end
    end
    

    By admin on Aug 22, 2008

  1. 1 Trackback(s)

  2. Aug 15, 2008: Higher-Order » Blog Archive » Fibers: an exercise

You must be logged in to post a comment.