hoodwink.d enhanced
RSS
2.0
XHTML
1.0

RedHanded

Wednesday

2005.11.23

Arity Makes Good Curry #

by why in inspect

kig just dropped this snip in the comments of the pipes discussion, which had morphed into a discussion about functional programming.

 class Fun < Proc
   def call(*args)
     if args.size < arity.abs and arity != -1
       Fun.new{|*a| call(*(args+a)) }
     else
       super
     end
   end
   alias_method :[], :call
 end

 def fun &block
   Fun.new &block
 end

 f = fun{|a, b, c| a * b / c }

 f[10, 20, 30] == f[10][20][30]
 #=> true

You can sort of curry methods with this, like so:

 class Turtle
   def draw *args
     fun { |x, y| ... }.call(*args)
   end
 end

But you will need to use the bracket syntax on the function returned by the method.

Someone's Growing an Annotator for Himself and Others #

by why in inspect

If you haven’t already subscribed, Mauricio Fernandez’ new blog at eigenclass.org is the most exciting blogride on the Ruby frontier. These hacks he’s posting are amazing. If there were a commercial for his blog, it’d show a kid chewing gum. Then a tidal wave. Then fruit syrup gushing through the kids mouth and jets of juice shooting out between his teeth like the dam’s gonna blow.

It does. Indigenous peoples die playing their bongos. Kids everywhere want their mouths to explode, too.

Take his xmp.rb, hacked in conspiracy with young and bright-futured and tumblicious and tumblelificent chris2. You feed this thing bunch of Ruby code and it annotates the code with output from the script, errors and warnings.

 RUBY_VERSION # => "1.8.3" 
 a = @a # !> instance variable @a not initialized
 class Foo
   def baz(n)
     (1..n).inject do |s,x|
       s + x   # => 3, 6, 10
     end
   end

   def bar(x)
     x.gsub(/foo/, "bar") # => "this is a bar", "this bar is bar" 
   end

   1+1 # => 2
 end

Look at the inject loop! It’ll print a joined list of values. Very tricky, Mauricio, you sly little man. I don’t know exactly how tall you are, Mauricio, but no one this conniving can be anyone other than the real Rumpelstiltzkin. Spinning code into gold. A gold purse for the rubies, how dare they glitter so brilliantly in mine eyes.

You know what would be wild? To use this as a way of writing test cases. You write the code that needs to be tested and annotate it with the asserts. (Also see Mauricio’s Changes in 1.9, a painstaking summary of what’s in Ruby’s HEAD right now.)

And now look what leprechaun has done just that with the unit testing idear. Blarney!