Hacker News new | past | comments | ask | show | jobs | submit login

Lua addresses this problem by having metamethods, with a special way of failing over when operators meet a type error:

https://www.lua.org/manual/5.3/manual.html#2.4

>If any operand for an addition is not a number (nor a string coercible to a number), Lua will try to call a metamethod. First, Lua will check the first operand (even if it is valid). If that operand does not define a metamethod for __add, then Lua will check the second operand. If Lua can find a metamethod, it calls the metamethod with the two operands as arguments, and the result of the call (adjusted to one value) is the result of the operation. Otherwise, it raises an error.




Thank you for the link, but I'm not sure this solves the problem. I mean, what if Abbie makes complex numbers, so she provides a metamethod to work with the builtin number type. Then Bobby wants to build on Abbie's work and add matrices. Lets say Abbie's complex type is on the left, but her metamethod doesn't know anything about matrices... Bobby is willing to support complex numbers multiplied with matrices, but the matrix metamethod never gets called:

    z = complex(1, 2)
    A = ident(3, 3)
    -- Won't this next line call the wrong metamethod?
    X = z*A
For a dynamicly typed language, I think you'd want something like multimethods to do this cleanly. (Or something like Python's dirtier approach)


If you want to allow unknown types to do your multiplying, you can write __mul like so:

    [...]
    elseif getmetatable(right).__mul and getmetatable(right) ~= complex then
       return getmetatable(right).__mul(left, right)
    [...]
Of course this requires a little forward thinking, but it doesn't require you to know what other metatables (classes) you'll be compatible with. It's not as clean as multiple dispatch, though.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: