citizen428.blog()

Try to learn something about everything

Ruby — Left Section for Infix Operators

Let me admit right away that this is yet another “because I can” type of post with little practical use. With that out of the way, today’s topic is sections of infix operators as known from e.g. Haskell. Here’s an example:

1
2
λ> map (2+) [1..3]
[3,4,5]

As you can see the function to be mapped is specified with the partially applied function (2+) (or (+2) for that matter).

Here’s how we would have to write the same code in Ruby:

1
(1..3).map { |i| i + 2 }

This could also be written in a pointfree way, but alas that would make the code rather hard to understand for less experienced Rubyists:

1
(1..3).map(&2.method(:+))

But because Ruby is as flexible as it is, adding partial application is actually really trivial:

1
2
3
4
5
6
7
class Fixnum
  alias :add :+

  def +(o=nil)
    o ? self.add(o) : lambda { |x| self + x }
  end
end

And now we can do this:

1
(1..3).map(&2.+) #=> [3, 4, 5]

Not too bad I think and rather consistent with Ruby’s overall style. Alas I don’t think we are likely to see partial application on a language level any time soon though…

Comments