I’m trying to do some abstraction in Haskell98 but doen’t know how to do it.
What I want to do is to define a class for types that may be converted into lists.
toList :: a -> [b]
But I don’t know how to define a class for this method. I brought up the following three ideas:
class ToList a b where toList :: a -> [b] class ToList a where toList :: a -> [b] class ToList a where toList :: a b -> [b]
The first one doesn’t work because Haskell98 doesn’t allow multiple parameter classes.
The second one doesn’t work because b depends on a and can’t be implemented for every b.
The third doesn’t work either because I don’t know how to instanciate the class with a type where ‘b’ isn’t the last type-parameter.
data HTree a b = Nil | Node a b (HTree a b) (HTree a b) toList Nil = [] toList Node x y l r = toList l ++ [(x,y)] ++ toList r
or
toList Nil = [] toList Node x y l r = toList l ++ [x] ++ toList r
How would I do something like that?
See also Data.Foldable in the standard library, which provides a
toListfunction for anyFoldableinstance.Foldabletakes a bit of sophistication to instantiate, but it would be good practice. As a bonus, yourHTreetype is almost exactly the same as the example instance in the documentation.Additionally, I recommend changing your
HTreeto:And then using
HTree (a,b)instead ofHTree a b. This single-parameter version will be more easily composable with standard types and instances, and it gets more to the point of what is going on since it depends on both parameters in the same way. It is also aFunctor, and defining such an instance will make this type really nice to work with.