Skip to content

toList

We used the conversion of a foldable container into a list as an example to illustrate the use of foldMap. This conversion from foldable containers to lists is useful in general. We may have some set of elements in some container, and we want to apply to it a function that expects a list as argument. The conversion from container to list is a useful adapter for such list-specific functions. We have

toList :: t a -> [a]
toList = foldMap singleton

as the default implementation.

GHCi
>>> toList Nothing
[]
>>> toList (Just 5)
[5]
>>> tree = Node Empty 5 (Node (Node Empty 3 Empty) 1 (Node Empty 2 Empty))
>>> toList tree
[5,3,1,2]