如何替换现有的运算符而不在 Io 中调用它们?
我正在尝试完成《七天内七种语言》一书中 IO 第 2 天的第二个练习。在其中你问:“如果分母为零,你会如何改变 / 返回 0?”我已经确定可以使用以下方法向 Number 添加方法:
Number new_div := method(i, if(i != 0, self / i, 0))
我不确定如何替换运算符表中的“/”。我已经尝试过了:
Number / := Number new_div
Number / := self new_div
但是我得到了一个例外,因为它试图调用“/”。如何获取 Number / 的句柄,以便可以存储对旧方法的引用,然后根据自己的目的重新定义它?我这一切都错了吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于埃里克·霍格(Eric Hogue)(参见问题评论):
For Eric Hogue (see question comments):
你想做的是运行:
例如。
但是,应该注意的是,如果您使用
new_div
的定义,您将遇到无限循环,因为您在其中调用/
方法,并将/
运算符设置为使用new_div
将导致对6 / 2
的调用递归,直到内存耗尽。What you want to do is run:
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 usenew_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.