Skip to main content
Tweeted twitter.com/StackMma/status/713246088736714752
edited tags
Link
edited tags
Link
Ali Hashmi
  • 9.1k
  • 4
  • 22
  • 43
Source Link
Ali Hashmi
  • 9.1k
  • 4
  • 22
  • 43

How to use currying to write a tail recursive function for summing factorials given a certain bound

I am very confused about how can i use currying to write a tail recursive function for summing factorials within a certain bound or summing the bounds i.e. given [1,5] i should be getting 1!+2!+3!+4!+5! and for summing bounds 1+2+3+4+5. How can i construct two elegant functions using currying.

My code currently looks like this:

factorial[n_] := (loopfact[n, acc_] := If[n == 0, acc, loopfact[n - 1, acc*n]];
Return@loopfact[n, 1]);

sum[a_, b_, acc_] := Block[{x, ac}, x = a; ac = acc;
loop[x_, ac_] := If[x > b, ac, loop[x + 1, ac + factorial[x]]];
loop[x, ac]]

sum[0, 5, 0] (* using the function above *)
(* 154 *)

sum[a_, b_, acc_] := Module[{x, ac}, x = a; ac = acc;
loop[x_, ac_] := If[x > b, ac, loop[x + 1, ac + # &@x]];
loop[x, ac]]

sum[0, 50, 0] (* using the second function definition *)
(* 1275 *)

Also could someone kindly explain to me how currying works in Mathematica. Thanks !