3
$\begingroup$

I am trying to use functional programming in place of imperative programming. One of the things I would like to do is iteration. As an example, to try to convert the following loop

x0 = [1,2];

for i = 1:4
y1 = [x0(1)*x0(2),x0(2)/x0(1)];
y2 = [y1(1)/y2(2),5];
y3 = [(y2(1)+y2(2))^2, 1 + y2(1)];
y4 = [y3(1)/4, y3(2)/6];
x0 = y4;
end 

The analogous functional approach is

step4 = Function[{#[[1]]/4, #[[2]]/6}];
step3 = Function[{(#[[1]] + #[[2]])^2, 1 + #[[1]]}];
step2 = Function[{#[[1]]/#[[2]], 5}];
step1 = Function[{#[[1]]*#[[2]], #[[2]]/#[[1]]}];
total = Composition[step4, step3, step2, step1];
(* alternatively, Function[step4[step3[step2[step1[#]]]]] *)
NestList[total, {2., 3.}, 4]

For the purpose of debugging, I would like to use ComposeList to know, giving an initial starting value, what the value at a given step would be. However, while Composition can be used to generate a pure function, ComposeList must be given a formal parameter. For the use above, with functions defined with list inputs, I have to put in a list of formal parameters like {x,y}, which prevents subsequent use with functions like NestList. For example,

all = ComposeList[{step1, step2, step3, step4}, {x, y}]
uptostep2 = all[[2]];

Is there a way to create pure functions using ComposeList or another method to achieve the same thing?

$\endgroup$
3
$\begingroup$

What about FoldList[Composition, {step1, step2, step3, step4}]?

$\endgroup$

Your Answer

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

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