being functional with ruby

Ola wrote about writting functional style accumulators in ruby. I knew there was a better solution to his using fold, which in ruby it's called inject, one of the commenters did mention this. The solution was this:

    [1,2,3,4,5].inject([]) {|a,b| [b] + a}

this is a one liner but it doesn't create the accumulator for us, so, to be really functional, would you do this?:
    reverse = lambda {|l| l.inject([]) {|a,b| [b] + a}}
at this point you have a proc object called reverse that performs the reverse. But the syntax for calling a proc is awkward =(. You can do either:
    reverse.call [1,2,3,4,5]
or, alternatively:
    reverse [[1,2,3,4,5]]
I am not making this up ;) Ack! This aspect of Ruby - that procs are not the same as methods - is annoying. I guess you COULD do this instead:
    Kernel.send(:define_method, :reverse) {|l| l.inject([]) {|a,b| [b] + a}}
this gives you a method at the Kernel level which would look just like a function. So you can now do:
    reverse [1, 2, 3, 4, 5]
But in the Rubyish OO paradigm you'd probably put it in the Array class:
    Array.send(:define_method, :reverse) { self.inject([]) {|a, b| [b] + a}}
so now you can do:
    [1, 2, 3, 4, 5].reverse
Actually, ruby already comes with an reverse method for the Array so this is only an exercise.

blog comments powered by Disqus