OctaviPascual / cis194-IntroductionToHaskell

🚀Solutions of CIS 194: Introduction to Haskell (Spring 2013) course
http://www.seas.upenn.edu/~cis194/spring13/
MIT License
12 stars 6 forks source link

A testcase make myFoldl in homework4 fail #2

Open akamayu-ouo opened 3 years ago

akamayu-ouo commented 3 years ago

Hi, I find a testcase that make the myFoldl function fail.

(foldr . flip) (++) "A" ["B","C","D"]    -- outputs "ADCB", rather than "ABCD"

What's wrong is after flipping the reduction function, the arguments are swapped, but the order of application is still from right to left.

More explicit,

(foldr . flip) f x0 [x1, x2, x3, x4, x5, ... , xn]
= (f ( ... (f (f x0 xn) xn-1) ... ) x1)

while

foldl f x x0 [x1, x2, x3, x4, x5, ... , xn]
= (f ( ... (f (f x0 x1) x2) ... ) xn)
bschnitz commented 3 months ago

Correct. If the operations commutate, then the myFoldl definition from the solution does work. Another noncommutative example would be (foldr . flip) (mod) 4 [3, 2] -- outputs 0 whilst 1 would be correct To mimic the correct behaviour, one has also to reverse the input list to have the function application in the correct order:

myFoldl :: (b -> a -> b) -> b -> [a] -> b
myFoldl f base xs = foldr (flip f) base (reverse xs)