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
It doesn't run twice over the list, the
foldl (\x -> f x) xs xsis 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 inxs.Indeed,
foldl f ys (x:xs)is equivalent tofoldl f (f ys x) xs, so it is a mechanism to applyfto the accumulator that starts withysand uses the first item of the listx. But here the item of the list is ignoed.It will thus, for a list
xswith n items, work as:where it thus applies the
bsortfunction again on the result of the previousbsortthat many times as there are elements in the list.