# Why the function cannot achieve the expected result?

Today, I write a toy code (Framed the prime in a list) to practice Mathematica programming ,which as shown below:

Trail 1:

(Framed@# /; PrimeQ@# &) /@ Range Trail 2:

(Framed@x_ /; PrimeQ@x) /@ Range Trail 3:

framedPrime[x_] := Framed@x /; PrimeQ@x;
framedPrime[x_] := x
framedPrime /@ Range


Achieving the ideal result

Trail 4:

If[PrimeQ@#, Framed[#], #] & /@ Range


Achieving the ideal result

Trail 5:

Range /. # :> Framed@# /; PrimeQ@# & Trial 6:

Range /. x_ :> Framed@x /; PrimeQ@x


Achieving the ideal result

So I'd like to know why trial 1,2,5,(what's the difference between trial 5 and 6?) were failed.(Although I used Mathematica for progrmming for a year)

• The syntax for /; is pattern /; test or something deferred /; test – Dr. belisarius Oct 22 '14 at 14:50

Overall, I think your main confusion stems from mixing up different the programming paradigms and syntax in Mathematica. The way Functional and Rule & Patterns based programming works is different.

To quote the Documentation:

The Wolfram Language stands out from traditional computer languages in supporting many programming paradigms.

In particular:
Trials 1 and 2 are using Condition (patt/;test) in the wrong way. Condition is used to conditionally apply a replacement rule by further restricting a pattern, while you are using it in a purely functional setting. You correctly used the functional syntax in Trial 4.
In Trial 5 you are also mixing functional and pattern matching / replacement rule structures. In that code, you are trying to match expressions to Slot (#). It also has the problem that & is very loosely binding, so the whole expression is interpreted as a pure function. You correctly used the replacement syntax and patterns in Trial 6.
Trial 3 is essentially like Trial 6 since it uses rules and patterns, but it uses SetDelayed to an assignment that tries to apply that rule to all expressions.

Appendix A of Leonid Shifrin's book: Mathematica Programming: An advanced introduction; and
Programming Paradigms via Mathematica (A First Course).

I post this to illustrate some of the ways you could do this task. I have voted for Simon's answer, however, as it addresses the 'why' (the point of the question and the most important point).

f[x_?PrimeQ] := Framed[x];
f[x_] := x;
g[x_] := Framed[x] /; PrimeQ@x;
g[x_] := x;
h[x_] := Piecewise[{{Framed[x], PrimeQ@x}, {x, True}}];
j[x_] := Which[PrimeQ@x, Framed@x, ! PrimeQ@x, x];
k[x_] := If[PrimeQ@x, Framed[x], x];
m[x_] := x /. {a_?PrimeQ -> Framed[a]};
n[x_] := Switch[PrimeQ@x, True, Framed[x], False, x];


or the ugly

p[x_] := With[{pos = Position[x, _?PrimeQ]},
ReplacePart[x, Thread[pos -> Framed /@ Extract[x, pos]]]]


Then:

f /@ Range
g /@ Range
h /@ Range
j /@ Range
k /@ Range
m@Range
n /@ Range
p@Range 