Maple 13: how to turn true to 1 and false to 0?

In general, I need type conversion instructions that can, for example, be multiplied by true, as 5 * truewell as receive 5, for example x * false, and receive 0.

How to do it?

+3
source share
2 answers

There are several ways to get this effect, and what you choose may depend on more details about what you intend to do with it.

The simplest is to use a 2 argument eval(or subs, since the evaluation should happen due to automatic simplification for a product with an exact 1 or 0).

> eval( 5*true, [true=1,false=0]);
                           5
> eval( x*false, [true=1,false=0]);
                           0

And of course, you can create a procedure to handle this assessment,

> T := expr -> eval(expr,[true=1,false=0]):

> T( 5*true );
                           5
> T( x*false );
                           0

(, , " " ) *.

. * "true" "false" , , . ( , "true" "false" , , . .)

> M:=module() option package; export `*`;
>  `*`:=proc(ee::seq(anything))
>         :-`*`(op(eval([ee],[true=1,false=0])));
>       end proc;
> end module:

> with(M):

> 5*true;
                           5
> x*false;
                           0

> a*b*c;
                         a b c

> eval( %, b=false ); # this doesn't play along
                       a false c

, "false" 0. , a * b * c ( a, b c) : - *, *. b = false *. , , ( , , "" - , ),

> M:=module() option package; export `*`;
>   `*`:=proc(ee::seq(anything))
>          local res;
>          res:=:-`*`(op(eval([ee],[true=1,false=0])));
>          if type(res,:-`*`) then
>            'procname'(op(res));
>          else
>            res;
>          end if;
>        end proc;
> end module:

> with(M):

> 5*true;
                           5
> x*false;
                           0

> a*b*c;
                     `*`(`*`(a, b), c)

> eval( %, b=false );
                           0

, * (* (a, b), c), *. , b = false , *, . (, , .)

+2

subs([false=0, true=1], expr);
+2

Source: https://habr.com/ru/post/1772563/


All Articles