What is the simplest way to constraint a built-in function's output in Mathematica? say let Sin returns only odd numbers?

ぐ巨炮叔叔 提交于 2019-12-04 03:21:07
Alexey Popkov

You can use the Villegas-Gayley trick for this.

For the Sin function:

Unprotect[Sin];
Sin[args___]/;!TrueQ[$insideSin]:=
   Block[{$insideSin=True,result},
      If[OddQ[result=Sin[args]],result]
   ];
Protect[Sin];
{Sin[Pi],Sin[Pi/2]}

==> {Null,1}

I prefer a method which is functional and reminds me of decorators in Python. http://wiki.python.org/moin/PythonDecorators

First we create the decorator:

OddOnly[x_] := If[OddQ[x], x, Null];

It can then be used as a prefix:

OddOnly@
 Sin[Pi]

Null (* Doesn't actually give a result *)

OddOnly@
 Sin[Pi/2]

1

A variation of Searke's method that I prefer is:

OddOnly[s_Symbol] := 
 Composition[If[OddQ@#, #, ##&[]] &, s]

This automatically removes results that are not odd, and it is applied to the function itself, which I find more convenient.

Examples:

OddOnly[Sin] /@ {2, Pi, Pi/2}

(*  Out[]= {1}  *)

Array[OddOnly[Binomial], {5, 5}]

(*  Out[]= {{1}, {1}, {3, 3, 1}, {1}, {5, 5, 1}}  *)

Could apply a rule of the form

whatever /. _Integer?EvenQ :>Sequence[]

Daniel Lichtblau

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!