Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

This question already has an answer here:

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?

share|improve this question

marked as duplicate by rasher, Öskå, RunnyKine, Jens, bobthechemist Jun 28 at 2:23

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
Is the answer to your example supposed to be 85, as in f[1, 2, #] & /@ Range[10] // Total? –  bobthechemist Jun 27 at 23:38
    
Exactly, but I need to do this for more general f also, not just linear. –  Kieran Cooney Jun 27 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 –  rasher Jun 27 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 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... –  rasher Jun 28 at 0:42

2 Answers 2

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}

share|improve this answer

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

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.