How to create toList function using a foldable container and a functor in haskell

153 Views Asked by At

Was looking at some problems to improve my knwoledge on foldable and functors but cannot quite seem to get my head around how to create the toList function using foldable and a functor

This is what i have so far was unsure if i would need to create my own instance for foldable here

I want to create toList explicitly using the type definition below

instance Foldable [] where 
  fold = undefined

toList :: (Functor c, Foldable c) => c a -> [a]
toList f = undefined

Any help and explanation to what i have to do is appreciated

1

There are 1 best solutions below

7
Rein Henrichs On

To write toList, you actually only need the Foldable constraint. In fact, you only need foldr. The key insight is the following law. When xs is a list,

foldr (:) [] xs = xs

But the type of foldr (:) [] is

Foldable t => t a -> [a]

which means it turns any Foldable into a list. And sure enough, this is an acceptable definition of toList:

toList :: Foldable t => t a -> [a]
toList = foldr (:) []