Maple 13:如何将 true 变为 1,将 false 变为 0?
一般来说,我需要的是类型转换指令,例如能够在 true 上相乘,如 5 * true
和 get5
或 x * false
并得到0
。
这样的事该怎么办呢?
generaly what I need is type transformation instructions to be capable of for example multipliiing on true like 5 * true
and get5
of say x * false
and get 0
.
How to do such thing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有多种方法可以实现这种效果,您选择哪种方法可能取决于您打算用它做什么的更多细节。
最简单的是使用 2 参数
eval
(或subs
,因为评估应该是由于涉及精确 1 或 0 的乘积的自动简化而发生)。当然,您可以创建一个过程来处理该评估,
您还可以尝试使用模块来导出(从而在交互使用的“顶层”重新定义)增强的
*
。注意。下面这个导出过程
*
的更仔细的版本只会在作为整个被乘数出现时替换“true”和“false”,而不是在整个表达式中进行替换。 (标量表达式中可以包含未计算的函数调用,例如可选参数中会出现“true”和“false”。理想情况下,应将它们单独保留。)请注意最后一个结果中的“false”替换是如何发生的不会产生 0。这是因为 a*b*c(对于未知的 a、b 和 c)的结果是全局 :-
*
而不是新的*
。因此,当 b=false 被替换时,不会调用新的*
。也可以解决这个问题,尽管结果显示不太好(并且解决方法可能会“破坏”您可能想要实现的其他东西),在上面的最后一个示例中,对象看起来像 < code>*(
*
(a, b), c) 实际上是对新*
的未计算函数调用。因此,当 b=false 被替换时,就会调用新的*
并且可以获得所需的结果。 (希望这不会导致我忽略的情况下的无限递归。)There are several ways to get such an effect,and which you choose may depend on more particulars of what you intend on doing with it.
The simplest is to use 2-argument
eval
(orsubs
, since evaluation should occur due to automatic simplification for a product involving exact 1 or 0).And of course you can create a procedure to handle that evaluation,
You could also try using a module to export (and thus redefine at the "top-level" of interactive use) an enhanced
*
.nb. A more careful version of this exported procedure
*
below would only replace 'true' and 'false' if occurring as entire multiplicands, and not do replacement throughout all of the expression. (A scalar expression can have unevaluated function calls in it, with 'true' and 'false' appearing in, say, optional arguments. Ideally, these should be left alone.)Notice how the substitution of 'false' in that last result didn't produce 0. It's because the result of the a*b*c (for unknown a,b, and c) is in terms of the global :-
*
and not the new*
. So when b=false is substituted there's no call to the new*
. It may be possible to work around that too, although the resulting display is not so nice (and the work-around likely "breaks" something else you might intend for all this),In that last example above, the object that looks like
*
(*
(a, b), c) is actually in terms of the unevaluated function calls to the new*
. Hence when b=false is substituted there is a call to the new*
and the desired result can obtain. (Hopefully this doesn't lead to an infinite recursion in a case I've overlooked.)你可以这样做:
You can do it with: