# Why does not BarLegend accept user-defined color function?

I encountered a really strange problem with BarLegend. Say you have a user-defined color function:

cf[z_]:=RGBColor[RandomReal[z, 3]]


When you want to use it in BarLegend as below:

BarLegend[{cf, {1, 10}}]


Mathematica will generate a blank bar shown as below:

However, after I change the function head in BarLegend to a pure function:

BarLegend[{cf[#]&, {1, 10}}]


Mathematica can give desired result.

I cannot figure out why Mathematica doesn't accept user-defined color function. Could anyone please give a clue?

-
Does cf = Function[z, RGBColor[RandomReal[z, 3]]] work better? – cormullion Dec 12 '13 at 14:10

If you look into the source code

ClearAttributes[BarLegend, ReadProtected]
?? BarLegend


And into nested functions (BarLegend,ChartingiBarLegend $\to$ LegendingLegendDumpiColorBandLegend $\to$ LegendingLegendDumpparseColorBand) you can find the following code

Switch[LegendingLegendDumpcolorfunction,
_String, ColorData[LegendingLegendDumpcolorfunction]/@LegendingLegendDumpvalues,
_ColorDataFunction, LegendingLegendDumpcolorfunction/@LegendingLegendDumpvalues,
_List, Switch[LegendingLegendDumpfn, LegendingColorBandLegend,With[{LegendingLegendDumplist=LegendingLegendDumpcolorfunction},Blend[LegendingLegendDumplist,#1]&]/@LegendingLegendDumpvalues,
BarLegend|_, LegendingLegendDumpiter=Max[Length[LegendingLegendDumpcolorfunction]-Length[LegendingLegendDumpvalues],0];Do[LegendingLegendDumpcolorfunction=Reverse[ChartingpadList[LegendingLegendDumpcolorfunction,Length[LegendingLegendDumpcolorfunction]-1]],{LegendingLegendDumpiter}];If[OddQ[LegendingLegendDumpiter],Reverse[LegendingLegendDumpcolorfunction],LegendingLegendDumpcolorfunction]],
Hue|GrayLevel, (LegendingLegendDumpcolorfunction[#1]&)/@LegendingLegendDumpvalues,
_Function, LegendingLegendDumpcolorfunction/@LegendingLegendDumpvalues,
_, Return[{}]]


It shows that the function must have the Function` header.

-