0
$\begingroup$

Suppose I have a known real constant $a$, and I want to calculate $f(n) = \prod_{k=1}^{n}(a-k)$. I know I could memoize this function

Clear[a, f];
a = 8;
f[0] = 1;
f[n_Integer] /; 1 <= n := f[n] = f[n - 1]*(a - n);
f[2]
?f

Results

42
Global`f 
f[0]=1 
f[1]=7 
f[2]=42
f[n_Integer]/;1<=n:=f[n]=f[n-1] (a-n)

But this function is not listable.

f[{1,2,3}]

f[{1,2,3}]

Alternatively, I know I could make the function listable without memoizing

Clear[f];
f[n_Integer] := Times @@@ (a - Range[n]);
f[{1,2,3}]

{7, 42, 210}

I've been trying to think of a good way of making it both memoized and listable, and I came up with the following

Clear[f]
f[0] = 1;
f[n_Integer] /; 1 <= n := f[n] = f[n - 1]*(a - n);
f[n_List] := f /@ n;

Is there a better (as in more efficient) way to do this?

$\endgroup$
  • $\begingroup$ SetAttributes[f, Listable] $\endgroup$ – Batracos Jul 13 '17 at 18:55
  • $\begingroup$ Are you looking for Pochhammer? Pochhammer[8 - #, #]&@Range@3 (* {7, 42, 210} *) $\endgroup$ – jkuczm Jul 13 '17 at 19:05
  • $\begingroup$ Thanks for the help with SetAttributes, @Batracos. And yes! I should be using Pochhammer instead of re-creating it. $\endgroup$ – FalafelPita Jul 13 '17 at 19:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.