# Defining $f(x)=mx+b$ with $m,b$ separate versus f[m_ ,b_ ,x_]:=mx+b

Suppose I want to define a function $$f(x)=mx+b$$. And suppose I might want to change $$m$$ or $$b$$ later.

Specifically, suppose I initially want $$m=-2,b=10$$, but maybe will change these values later

Two ways I can think of to do this are

slope=-2;
intercept=10;
f[x_]:= intercept+slope*x


or, I can define it as

f[intercept_,slope_,x_]:=intercept+slope*x
f[10,-2,x]


Does anyone have suggestions vs when to use one approach vs the other?

I usually do a hybrid kind of thing, when I use the latter way, but then define something like slopeCase1=-2; interceptCase1=10; and then call f[interceptCase1,slopeCase1,x], but this looks ugly is probably problematic in more ways than one.

The former way seems nicer to me, but I always worry that when I later go and change slope (say slope=-3), some definition somewhere will not be changed because of some technicality.

• (If I am only calling f[x_] once this is not really a worry, but if I use f in another function, which is used in another, etc, theres a lot of places where a mistake can happen

Consider defining the function family instead of the function:

f[b_, m_] := Function[{x}, m x + b];


Then:

fcase1 = f[10, -2];
fcase2 = f[10, -3];

{fcase1[x], fcase2[x]}

• Would fcase1 and fcase2 be "Listable", or would I need to be explicit and use something like Function[Null, m*#+b,Listable]? – user106860 Nov 12 '20 at 22:42
• @user106860 fcase1 and fcase2 are listable due to internal vectorization of Plus and Times and will be hundreds to thousands times more efficient than Function[..., Listable]. If you call fcase1 etc. on only a few thousand x, the difference in efficiency won't matter that much. – Michael E2 Nov 12 '20 at 23:36