Reputation: 474
As an exercise, I'm trying to write a function that behaves the same way as the foldl function and I'm trying to use recursion, as well.
My function will be called, "leftFolder" and the signature will look like a foldl function's:
leftFolder :: (a -> b -> a) -> a -> [b] -> a
I'm kinda stuck on what to do, but here's what I've tried:
leftFolder :: (a -> b -> a) -> a -> [b] -> a
leftFolder [] = []
leftFolder (x:xs) = x (++) (leftFolder xs)
In my mind, this makes sense. I'm saying that if the list is empty, return an empty list. If it's not, then take the head of the list and then keep appending it to the tail.
Upvotes: 0
Views: 127
Reputation: 76240
There are a lot of issues with your code. For example:
[]
while the first argument should be a functionx (++) ...
makes no sense; you probably meant to use x:...
I believe what you are looking for is this:
leftFolder :: (a -> b -> a) -> a -> [b] -> a
leftFolder _ c [] = c
leftFolder fn c (x:xs) = leftFolder fn (fn c x) xs
That is: if the list is empty then we return the accumulated value in the second position. Otherwise we calculate the new accumulated value (fn c x
) and then pass it as the second argument to our function while also forwarding fn
and passing the rest of the list.
Upvotes: 3