Quantcast
Viewing all articles
Browse latest Browse all 7

Ruby Functor

Dan Yoder has been messing with something that looks very interesting indeed::

fib = Functor.new do
  given( 0 ) { 0 }
  given( 1 ) { 1 }
  given( lambda { |n| n > 1 } ) { |n| self.call( n - 1 ) + self.call( n - 2 ) }
end

I'm not clear just how close to a pattern matching style Functor's given gets us but guarded evaluation with lambda's is a pretty neat trick. Here it is used in Dan's framework Waves:

class View
  include Functor::Method
  def initialize( response ) ; @response = response ; end
  functor( :render, String ) { |s| @response.write(s) }
  functor( :render, Proc ) { |p| render( p.call ) }
  functor( :render, Object ) { |k| render( k.to_s ) }
  functor( :render, Object, Hash ) { |k,h| @response.headers.merge!( h ); render(k) }
end

# these two lines do more or less the same thing ...
view.render( "hello" )
View.functors[:render].apply( view, "hello" )

# The big difference is that the render method will actually call super for
# you if nothing matches, just in     case render is also implemented in
# base class. If no match is found (either in the derived or base class) an
# ArgumentError will be raised. So you wouldn

Viewing all articles
Browse latest Browse all 7

Trending Articles