Message Boards Message Boards

0
|
3536 Views
|
4 Replies
|
2 Total Likes
View groups...
Share
Share this post:

Display power 1 always in the output?

Posted 7 years ago

(*how to make mathematica recognize x as x^1?? I want f[x]to output {x,1}

In[44]:= f[a_^n_] := {a, n};

In[43]:= f[x]


Out[43]= f[x]

In[45]:= f[x^2]

Out[45]= {x, 2}
POSTED BY: Vamsi Meesala
4 Replies
f[a_^(n_: 1)] := {a, n};

This will also work. Makes n optional with a default of 1.

POSTED BY: Neil Singer

Perfect!

POSTED BY: Vamsi Meesala
f[a_^n_] := {a, n}
f[a_] := {a, 1}

Now f[x^2] returns {x,2} and f[x] returns {x,1}

Functions can be "overloaded" -- you create different patterns to match for the same function.

Regards

POSTED BY: Neil Singer

Appreciate your reply! I was wondering if there is any other way apart from overloading the function. Cause in my application, this small issue doubles my number of test cases that I have to hard code.

Thanks

POSTED BY: Vamsi Meesala
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract