I was doing the exercises from YAHT's Recursive Datatype section, and found writing the listFoldr
function a bit challenging (mainly because I didn't really understand the difference between foldl
and foldr
at first). When I finally realized exactly how the foldr
function worked, I decided that a simple swap of function arguments would be all that'd be needed to change my listFoldl
function to a listFoldr
function:
listFoldl f i [] = i
listFoldl f i (x:xs) = listFoldl f (f i x) xs
listFoldr f i [] = i
listFoldr f i (x:xs) = listFoldr f (f x i) xs
This appears to work (I did more tests than this):
Main> foldr (-) 4 [1, 2, 3]
-2
Main> listFoldr (-) 4 [1, 2, 3]
-2
But the solution given for the exercise is much different than mine. Their listFoldl
is exactly the same as mine, but look at their listFoldr
:
listFoldr f i [] = i
listFoldr f i (x:xs) = f x (listFoldr f i xs)
Which solution is better, mine or theirs? Is one of them incorrect? (In my tests, they both end up with the exact same result...)