Problem 201. Mimic foldl in functional programming
Mimic the higher-order function foldl ( Wikipedia:Fold (higher-order function) ).
Arguments are a function with two arguments, start value, and a list. It takes the start value and the first item in the list and then applies the function to them, then feeds the function with this result and the second item in the list, and so on.
foldl(f, start, [x1, x2, ..., xn]) == f( (...f(f(f(s, x1), x2), x3), ...) , xn)
foldl(@plus, 0, 1:10) == ( ... (((0 + 1) + 2) + 3) + ... + 10) == 55
If the list is missing, it have to return the function handle which takes list. If both the start value and the list are missing, it have to return the function handle which takes two arguments, start value and list.
sumplusfive = foldl(@plus, 5);
=> sumplusfive(1:10) == 60 concat = foldl(@(x_, y_) [x_ y_]);
=> concat([1 2 3], [4 5 6]) == [1 2 3 4 5 6]
Solution Stats
Problem Comments
Solution Comments
Show commentsProblem Recent Solvers33
Suggested Problems
-
Make the vector [1 2 3 4 5 6 7 8 9 10]
52380 Solvers
-
Find all elements less than 0 or greater than 10 and replace them with NaN
15754 Solvers
-
125 Solvers
-
Back to basics 22 - Rotate a matrix
928 Solvers
-
Back to basics 23 - Triangular matrix
1107 Solvers
More from this Author1
Problem Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!