开发者

How do you replace existing operators without invoking them in Io?

I’m trying to complete the开发者_开发百科 second exercise on IO day 2 in the book Seven Languages in Seven Days. In it your asked, “How would you change / to return 0 if the denominator is zero?” I've determined that I can add a method to Number using:

Number new_div := method(i, if(i != 0, self / i, 0))

What I’m not sure is how to replace the ”/” in the operator table. I’ve tried:

Number / := Number new_div
Number / := self new_div

But I get an exception to both as it’s trying to invoke ”/”. How do I get a handle on Number / so I can store a reference to the old method and then redefine it for my own purposes? Am I going about this all wrong?


For Eric Hogue (see question comments):

origDiv := Number getSlot("/")

10 origDiv(5) println   # => 2
10 origDiv(0) println   # => inf

Number / := method (i, 
    if (i != 0, self origDiv(i), 0)
)

(10 / 5) println        # => 2
(10 / 0) println        # => 0


What you want to do is run:

Number setSlot("/", Number getSlot("new_div")

For example.

However, it should be noted, you'll have an infinite loop on your hands if you use that definition of new_div, since you're calling the / method within it, and setting the / operator to use new_div will cause the call to, 6 / 2 to recurse until you run out of memory.


What if you used the power operator inside your redefinition, then you don't have to keep a reference to the old division operator.

Number / := method(i, if(i==0, 0, self*i**(-1)))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜