I'm trying to write a reduce
function of type [a -> a -> a] -> [a] -> a
which would fold a list of n
values with a list of n - 1
binary operators, as in the following example:
reduce [(+), (*), (-)] [2, 3, 5, 7]
Running this example should return 18, and be the equivalent of the following expression:
(((2 + 3) * 5) - 7)
Implementing this function with recursion turns out to be very simple:
reduce (f : fs) (x1 : x2 : xs) = reduce fs (f x1 x2 : xs)
The concept of this function being very close to left folding, with the only difference that it uses multiple operators instead of a single one, I thought it could also be implemented using foldl
or equivalent higher order functions, instead of using explicit recursion.
With this in mind, and using applicative functions, I came up with the following implementation:
reduce fs (x : xs) = foldl (flip id) x (getZipList $ ZipList fs <*> ZipList xs)
As relying on ZipList seems quite verbose and redundant, I'm now wondering if there are nicer implementations for this function, with the same approach of not using explicit recursion.