Joffrey Baratheon
Joffrey Baratheon

Reputation: 474

Using a Function Like foldl Recursively

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

Answers (1)

Shoe
Shoe

Reputation: 76240

There are a lot of issues with your code. For example:

  • you are pattern matchin as a first argument [] while the first argument should be a function
  • you are using only 1 argument as opposed to the 3 you are requiring
  • x (++) ... makes no sense; you probably meant to use x:...
  • in the first pattern match you are returning a list, while the return type of your function is not necessarily a list

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

Live demo

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

Related Questions