10

Is there a way to use Head to detect a symbolic fraction? In particular I find,

Head[a/b]
Head[1/5]

Times

Rational

where I would like to get Head[a/b] = Rational. I want to test if a symbolic expression is a fraction so I can use it in another function.

m_goldberg
  • 107,779
  • 16
  • 103
  • 257
JeffDror
  • 1,880
  • 1
  • 13
  • 29
  • 2
    Rational is for numbers. Since a and b can be anything, since they are just symbols, I do not think it makes sense to say a/b is rational. If all you want is to check for the form, may be you can look at FullForm[a/b] and check for this form in your function by pattern matching? – Nasser Feb 02 '15 at 10:20

2 Answers2

13

It seems to me that Denominator helps a lot:

fractionQ = Denominator@# =!= 1 &;

fractionQ /@ {a/b, 1/a, 1/5, b/2, a, .5}
(* {True, True, True, True, False, False} *)
ybeltukov
  • 43,673
  • 5
  • 108
  • 212
8

The goal is not so clear for me, but probably something like this can be useful:

test = MatchQ[#, HoldPattern[_. _^-1] | _Rational | HoldPattern[_ Rational[1, _]] ] &

test /@ {a/b, 1/a, 1/5, a, .5, b/2}
{True, True, True, False, False, True}

Notice the dot in _., it is crucial for detecting 1/a since there is no Times really.

Kuba
  • 136,707
  • 13
  • 279
  • 740