Hacker News new | ask | show | jobs
by rkowalick 4398 days ago
Here's a Ruby solution that really does modify the + operation:

  class Fixnum
    alias_method :old_plus, :+
    def +(*args)
      old_plus(*args).old_plus(1)
    end
  end

  2 + 2 #=> 5
4 comments

As Flonk points out at http://codegolf.stackexchange.com/a/28794, nothing beats Haskell for casual re-definition of operators. (I seem to remember that this is even on the Haskell wiki somewhere, though I can't find it right now.)
Here's a ruby solution that only affects 2+2:

    class Fixnum
      alias_method :old_plus, :+
      def +(other)
        return 5 if (self == 2 && other == 2)
        old_plus(other)
      end
    end
Here's one in Ocaml that modifies the + operator

let (+) x y = match (x,y) with (2,2) -> 5 | (x,y) -> x+y;;

A shorter one:

let (+) 2 2 = 5 in 2+2;;

Here is a Nimrod version which does the same:

  proc `+`(x, y: int): int =
    result = x
    result.inc(y)
    result.inc

  echo(2 + 2) # => 5