# How to efficiently check conditions inside a function?

Consider a function as

f[n_]:=Module[{x,y},
x=Table[Sin[i],{i,0,Pi,Pi/(n-1)}];
y=Table[Cos[i],{i,0,Pi,Pi/(n-1)}];
Transpose[{x,y}]
]


Now, this function will work for all the values of n>1. However, for n=1, I want the function to return {1,1}. If I use If-else inside the function, I get the result, but, it gives me the error message as well.

How can I resolve this issue?

• To be structurally consistent, f[1] should be {{1,1}}, i.e., a list of points. To be efficient, f[1]={{1,1}}; f[n_Integer]:={Sin[#], Cos[#]}& /@ Range[0, Pi, Pi/(n-1)] – Bob Hanlon Sep 19 '18 at 13:52
• What error? Share the code, which has the problem. – Johu Sep 19 '18 at 15:25

## 4 Answers

f[n_] := Module[{x, y},
If[n == 1, {1, 1},
x = Table[Sin[i], {i, 0, Pi, Pi/(n - 1)}];
y = Table[Cos[i], {i, 0, Pi, Pi/(n - 1)}];
Transpose[{x, y}]]]

f[1]
(* {1,1} *)

• Thanks. It's really a great way. Exactly the kind of solution I was looking for. – Majis Sep 19 '18 at 13:04

Mathematica is an expression rewriting language. Use that (and eliminate unnecessary code):

f[n_] := Transpose[{Table[Sin[i], {i, 0, Pi, Pi/(n - 1)}],
Table[Cos[i], {i, 0, Pi, Pi/(n - 1)}]}]
f[1] = {1, 1};


When more than one rewrite is possible, Mathematica prefers the one with the more specific trigger, f[1] in this case

ClearAll[f]
f[n_] := Transpose[{Table[Sin[i], {i, n /. {1 -> π / 2, _ :> 0}, π, π/(n - 1)}],
Table[Cos[i], {i, 0, π, π/(n - 1)}]}]

f[1]


{{1, 1}}

f[3]


{{0, 1}, {1, 0}, {0, -1}}

This is more efficient.

f[1] = {1, 1};
f[n_?IntegerQ] /; n > 1 := Table[{Sin[i], Cos[i]}, {i, 0, Pi, Pi/(n - 1)}]

Table[f[i], {i, 5}]

{{1, 1},
{{0, 1}, {0, -1}},
{{0, 1}, {1, 0}, {0, -1}},
{{0, 1}, {Sqrt[3]/2, 1/2}, {Sqrt[3]/2, -(1/2)}, {0, -1}},
{{0, 1}, {1/Sqrt[2], 1/Sqrt[2]}, {1, 0}, {1/Sqrt[2], -(1/Sqrt[2])}, {0, -1}}}