[Haskell-beginners] Laziness to efficiently get one element from a set

Thomas Bach thbach at students.uni-mainz.de
Sat Mar 7 23:49:43 UTC 2015


Jeffrey Brown <jeffbrown.the at gmail.com> writes:

> head $ Data.Set.toList S. If I do that, am I correct that Haskell will
> not try to convert all of S to a list; instead it will only convert
> one element, and then return it, and leave the rest of the list
> unevaluated?

This is how toList from Data.Set.Base is defined in containers-0.5.0:

{--------------------------------------------------------------------
  Lists
--------------------------------------------------------------------}
-- | /O(n)/. Convert the set to a list of elements. Subject to list fusion.
toList :: Set a -> [a]
toList = toAscList

-- | /O(n)/. Convert the set to an ascending list of elements. Subject to list fusion.
toAscList :: Set a -> [a]
toAscList = foldr (:) []

The buzzword you are looking for is list fusion:

http://stackoverflow.com/questions/10945429/haskell-list-fusion-where-is-it-needed

Regards

        Thomas Bach.


More information about the Beginners mailing list