Suppose I'm writing a function that takes a color as a parameter; for example:
drawShape[color_] := Graphics[{Style[Disk[], color]}];
But if the caller inputs an invalid color, bad things happen:
So I want to use a pattern to define drawShape
only for values that are actually colors. Conceptually,
drawShape[color_Color] := ...
The problem is that unlike (say) List
s, Integer
s, Real
s, Complex
es, or Graphics
es, color objects do not share a Color
head. That is,
In[1]:= Red // Head
Out[1]= RGBColor
In[2]:= Hue[0.5] // Head
Out[2]= Hue
In[3]:= GrayLevel[0.5] // Head
Out[3]= GrayLevel
In[4]:= CMYKColor[0, 1, 1, 1/2] // Head
Out[4]= CMYKColor
In[4]:= Opacity[0.5, Purple] // Head
Out[4]= Opacity
In[5]:= Transparent // Head
Out[5]= GrayLevel
So that won't work. I also don't see any ColorQ
function, with which I could write drawShape[color_ ? ColorQ] := ...
.
How can I write a pattern that matches any valid color object? Is there a more robust way than just testing for each of these heads?