Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are some Prelude functions defined in terms of foldl?

Generally, foldl is avoided in favor of foldl' or foldr. Quoting Real World Haskell:

Due to the thunking behavior of foldl, it is wise to avoid this function in real programs: even if it doesn't fail outright, it will be unnecessarily inefficient. Instead, import Data.List and use foldl'.

Yet some Prelude functions are defined in terms of it (e.g. (\\) and unionBy). Why is this? Is it to not introduce too much strictness to these functions?

like image 398
amindfv Avatar asked Nov 20 '12 14:11

amindfv


People also ask

What are the prelude functions?

These functions are: take, drop, !!, length, splitAt, and replicate.

What is Foldl in Haskell?

From HaskellWiki. In functional programming, fold (or reduce) is a family of higher order functions that process a data structure in some order and build a return value. This is as opposed to the family of unfold functions which take a starting value and apply it to a function to generate a data structure.

What is the prelude in Haskell?

Prelude is a module that contains a small set of standard definitions and is included automatically into all Haskell modules.

How does Foldr work in Haskell?

Haskell : foldr. Description: it takes the second argument and the last item of the list and applies the function, then it takes the penultimate item from the end and the result, and so on. See scanr for intermediate results.


3 Answers

The Prelude was designed before foldl' existed, and there's been pressure to maintain backwards compatibility (with regards to strictness, as you mentioned) since then.

like image 158
Daniel Wagner Avatar answered Sep 27 '22 03:09

Daniel Wagner


In the case of (\\) and unionBy, the folded function has type

foo :: [a] -> b -> [a]

and foo xs y removes at most one element from xs, so using foldl' would not buy anything there in general, the thunks would be built on the right of the topmost (:) instead of above it then.

It would not make a difference in terms of strictness, as far as I can see, both folds would only be evaluated when the result needs to be evaluated to weak head normal form, and whenever foldl' would produce a _|_, so would foldl.

like image 45
Daniel Fischer Avatar answered Sep 23 '22 03:09

Daniel Fischer


In both cases the accumulator is of type [a]. I can't see that forcing the list to weak-head normal form would make a huge difference, and introducing such partial strictness seems somewhat arbitrary.

like image 32
kosmikus Avatar answered Sep 27 '22 03:09

kosmikus