Howto further restricts an existing type class in Haskell

Is there a way to further limit the context of an existing type class?

For example, the class type Functor class:

 class Functor f where fmap :: (a -> b) -> fa -> fb 

This class definition does not cause a or b be a Show element. Also, this type of class is the class that is included by me, so I cannot influence the definition of classes. Is it still possible to later only allow a and what b , which are members of the Show ?

+4
source share
2 answers

Not directly. The class definition cannot be changed without changing the source and recompiling. In the case of classes defined in standard libraries, this will cause multiple code violations, therefore it is not a realistic option.

However, you can wrap the class and add the necessary restrictions,

 class Functor f => ShowFunctor f where smap :: (Show a, Show b) => (a -> b) -> fa -> fb smap f = fmap f 

and then use this class instead of the original.

But maybe you don’t need an extra class, and for your applications it’s enough to define smap at the top level and just use this instead of fmap ,

 smap :: (Functor f, Show a, Show b) => (a -> b) -> fa -> fb smap = fmap 
+10
source

You cannot do this without breaking things (currently).

You have a couple of options

  • define your own limited Functor class
  • Don't worry about class definition and just define a function that does what you want.
  • use RMonad package
  • cheats

In fact, we now know how to allow instances to add restrictions, so maybe one day it will not be so bad, see Haskell's subcategories for a document that deals with almost this particular problem. The syntax in this article is slightly different from what is currently running in GHC, but basically we would like to redefine the Functor class to look like

 class Functor f where type SubCat f :: * -> Constraint -- associated constraint type SubCat f = () -- default definition fmap :: (SubCat fa, SubCat fb) => (a -> b) -> fa -> fb 
+2
source

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


All Articles