Cody

Problem 201. Mimic foldl in functional programming

Solution 105700

Submitted on 3 Jul 2012 by Mark
This solution is locked. To view this solution, you need to provide a solution of the same size or smaller.

Test Suite

Test Status Code Input and Output
1   Pass
%% summation assert(isequal(foldl(@plus, 0, 1:100), 5050));

yy = 1 y = 5050

2   Pass
%% summation 2 r = rand(1, 100); y = foldl(@plus, 0, r); yc = sum(r); assert(abs(y - yc)/abs(y) < 1e-6);

yy = 0.4505 y = 48.1198

3   Pass
%% factorial assert(isequal(foldl(@times, 1, 1:15), factorial(15)));

yy = 1 y = 1.3077e+12

4   Pass
%% find maximum r = rand(1, 1000); assert(isequal(foldl(@max, -Inf, r), max(r)));

yy = 0.2077 y = 0.9995

5   Pass
%% assert(isequal(foldl(@(x_, y_) 2*x_ + y_, 4, 1:3), 43));

yy = 9 y = 43

6   Pass
%% handle 1 sumplusfive = foldl(@plus, 5); assert(isequal(sumplusfive(1:100), 5055));

y = @(list1)fold(start,list1) yy = 6

7   Pass
%% handle 2 concat = foldl(@(x_, y_) [x_ y_]); r1 = rand(1, 10); r2 = rand(1, 10); assert(isequal(concat(r1, r2), [r1 r2]));

y = @(start1,list1)fold(start1,list1) yy = Columns 1 through 6 0.5864 0.6751 0.3610 0.6203 0.8112 0.0193 Columns 7 through 11 0.0839 0.9748 0.6513 0.2312 0.4035

Suggested Problems

More from this Author1

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!