0
$\begingroup$

I'm trying to define a simple function that will accept a symbol and an expression, set the symbol equal to the expression, and then print out info about the equation. Like so:

ClearAll[showValue];
Attributes[showValue] = {HoldAll};
Options[showValue] = {"N" -> False, "S" -> False};
showValue[sym_, value_, OptionsPattern[]] :=
  Module[{},
   sym = value;
   Print[
    HoldForm[sym], " = ",
    If[OptionValue["S"], ScientificForm] If[OptionValue["N"], 
      N] value
    ]
   ];

as you can see, I want to have some options that i can use to change the format of the output. What I would like is so that if the If evaluates to true, that it will return the function header in such a way as to apply the function to the arguments that are to the if statements' right. If effect, if the options given are:

showValue[k, 
  UnitConvert[Quantity[1, "BoltzmannConstant"], ("Electronvolts")/(
   "Kelvins")], "N" -> True, "S" -> True];

then the result will be:

k = ScientificForm@N@k = 8.61733*10^(-5)eV/K

The purpose of this is so I can avoid an extremely large and burdensome branching tree, once I put in more options. My understanding of Mathematica leads me to believe that something like this is possible because we have operator behavior and functions that can return operators, I just don't know what the syntax for that is suppose to be.

$\endgroup$
1
$\begingroup$

So I don't know if this is the best or most efficient way to perform this task, but here is the code I came up with:

ClearAll[Pass];
Pass[x_] := x;
ClearAll[showValue];
Attributes[showValue] = {HoldAll};
Options[showValue] = {"N" -> False, "S" -> False};
showValue[sym_, value_, OptionsPattern[]] :=
  Module[{},
   sym = value;
   Print[
    HoldForm[sym], " = ",
    Composition[If[OptionValue["S"], ScientificForm, Pass], 
      If[OptionValue["N"], N, Pass]][value]
    ]
   ];

I simply use a Pass function that just returns the argument, then use Composition to form the proper chain of functions. Again, I feel as though I am missing an easier path, so if anyone knows better, please let me know.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.