# How to use Fold with 3 variables [duplicate]

Suppose I define

f[x_,y_,z_]:=x+y+z


I wish to apply the Fold function to f along the lines of

Fold[f,1,2,Range[10]]


In other words, I want to fix x and y, while iterating over z. But this makes no sense as Fold will not accept more than 3 arguments. I realise that one solution to this is to redefine f as

f[{x_,y_},z_]:=x+y+z


Or something else along these lines, but I want to keep f as a function of 3 variables explicitly. Any suggestions?

-

## marked as duplicate by ciao, Öskå, RunnyKine, Jens, bobthechemistJun 28 '14 at 2:23

Is the answer to your example supposed to be 85, as in f[1, 2, #] & /@ Range[10] // Total? – bobthechemist Jun 27 '14 at 23:38
Exactly, but I need to do this for more general f also, not just linear. – Kieran Cooney Jun 27 '14 at 23:44
Treat the constants as prepended elements on the base list, within the function index into them and the "rest" of the list as needed. See here – ciao Jun 27 '14 at 23:58
@rasher In this case of two constants and one variable do the constants go into a List in the 2nd argument of Fold? – bobthechemist Jun 28 '14 at 0:10
@bobthechemist: Depends on what user wants, but based on OP, yeah, two constants and first z in base list, rest of z in iterator list, function replaces last entry each iter... – ciao Jun 28 '14 at 0:42

f[x_, y_, z_] := x + y + z

list = Range[10];

Fold[f[1, 2, #] &, 0, list]


30

This just adds 3 at each step as can be seen from FoldList

FoldList[f[1, 2, #] &, 0, list]


{0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30}

Fold[f[1, 2, #] &, 0, list] ==
FoldList[f[1, 2, #] &, 0, list][[-1]]


True

Or perhaps you intend

Fold[f[1, 2, #] &, First[list], Rest[list]]


28

This still adds 3 at each step but has a different initial value.

FoldList[f[1, 2, #] &, First[list], Rest[list]]


{1, 4, 7, 10, 13, 16, 19, 22, 25, 28}

-

Maybe an alternative:

f[x_, y_, z_] := x + Plus @@ {y, z} // Total

f[Range@10, 1, 2]


85

f[Sin@Range@10, 1., 2.]


31.4112

-