Why is the list annotated twice after the foldl in haskell?

66 Views Asked by At

I'm trying to understand haskell, I can't really be convinced about what this line of code does, can someone detail the line of code for me?

Why does the foldl need to loop through the xs list twice?

The code is for the bubble sort algorithm.

burbuja xs = foldl (\acc _ -> bsort acc) xs xs  
1

There are 1 best solutions below

0
willeM_ Van Onsem On

It doesn't run twice over the list, the foldl (\x -> f x) xs xs is a bit of a "sneaky" way to actually say that it should repeat the function on a value that many times as there are items in xs.

Indeed, foldl f ys (x:xs) is equivalent to foldl f (f ys x) xs, so it is a mechanism to apply f to the accumulator that starts with ys and uses the first item of the list x. But here the item of the list is ignoed.

It will thus, for a list xs with n items, work as:

bsort (bsort ((… (bsort xs) …))

where it thus applies the bsort function again on the result of the previous bsort that many times as there are elements in the list.