Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a Constraint to a Monad Result Type

Tags:

haskell

monads

I would like to create a type that is an instance of Monad such that the result type can only be an instance of a specific typeclass. I would like to be able to write something like

data T a = T a
class C a where
    ...

instance Monad T where
    return :: (C a) => a -> m a
    return x = ...
    (>>=) :: (C a, C b) => m a -> (a -> m b) -> m b
    p >>= f = ...

In the actual code that I'm working on, I need a typeclass constraint on the result type so that a specific function from the typeclass is available in the definitions for return and (>>=). Is there any way to do this?

like image 983
Ryan Farmer Avatar asked Sep 16 '25 14:09

Ryan Farmer


1 Answers

As per @chi's comment, the best solution is probably to use either constrained monads or indexed monads. Both solutions have the caveat of having to work around the standard library, but it can be done with workarounds such as rebinding syntax using the RebindableSyntax extension for example. The best example of constrained monads I was able to find was the constrained-monads package available on Hackage, while the best example I was able to find of indexed monads was a post at Kwang's Haskell Blog.

like image 58
Ryan Farmer Avatar answered Sep 18 '25 08:09

Ryan Farmer