Why is there a class like Measured for Data.FingerTree instead of a function?

I do not understand why FingerTree is implemented with the class type Measured .

I am trying to implement a monoid sequence, which by default is measured in the same way as a monoid, so I wrote the following.

 instance Monoid a => Measured (Sum Int, a) a where measure x = (Sum 1, x) 

Of course, since FingerTree itself is Measured , this is not possible, since we get a type overlap.

At what point was this single function abstracted into the type class? Why can't we just define FingerTree so that we can combine the measurement function with the constructor?

It would be nice to know if there are ways to overcome this problem. I could just determine a new instance for my particular use case every time, but maybe there is a better way.

+6
source share
1 answer

This is an example of the common friction between typeclass function resolution and "direct" function resolution. There are many times to support the direct, as you pointed out here, but often, when you can specify the specific laws that an instance of typeclass must support, people find it worthwhile to have class permission.

I don’t think it’s possible to have a β€œcorrect” answer, which is better, but there are big arguments for using the direct method more often.

In this case, more specific specifications are required to help the compiler understand which instance should be allowed. Although the case where any Monoid can have an instance of "count and comb" Measured , it is not clear that this is a canonical instance. Since the class for Measured requires Measured va | a -> v Measured va | a -> v we canonically chose v .

The most likely way to do this is to create a newtype wrapper

 newtype Counted a = Counted a instance Monoid a => Measured (Sum Int, a) (Counted a) where measure (Counted x) = (Sum 1, x) 

which gives us the required canonicity. This may be more convenient in some cases than directly passing the dictionary of Monoid functions.

+4
source

Source: https://habr.com/ru/post/951448/


All Articles