From: Johann Hibschman Date: 2001-04-17T04:40:08+09:00 Subject: [ruby-talk:13713] Re: operator + Luigi Ballabio writes: > Hmm. Looks like I kept my example too simple. > The real picture is, I have a TridiagonalOperator class written in C++ and > exported to Ruby through SWIG. Not easy to coerce to a Float :) I export > the operator * (a matrix times a scalar) and I hoped I could get > scalar*matrix for free. Oh well... This is exactly the sort of thing that multimethods solve well. Is there any chance that Ruby could grow something like that, or is it just too different? Hm. Actually, with a bit more thought I could probably write a multi- method object in Ruby, but it would take a bit of effort. The only concrete example I can think of is from Common Lisp. There, you can define (defun add ((s number) (op TridiagonalOperator)) ..) (defun add ((op TridiagonalOperator) (s number)) ..) (defun add ((op TridiagonalOperator) (v Vector)) ..) (defun add ((v Vector) (op TridiagonalOperator)) ..) etc., and the compiler will automatically dispatch to the right method. Since methods here aren't part of a class, they can dispatch equally well on either operator, which is very useful for matrix math, since matrices are noncommutative. Ideally, you could do something like class TridiagonalOperator < MultiMethods multi_def + (x : TridiagonalOperator, y : Scalar) ..something.. end end But I think that's a bit much for Ruby to handle. It's in the really ugly things like this that the Lisp-variants really shine. I could do it with Lisp macros. :-) Ruby wizards, is there any way to do this automatically? --J -- Johann Hibschman johann@physics.berkeley.edu