2

I have a type data A a = B (a (A a)). How can I put a constraint on the type var a in function something :: Eq (a b) => A a -> SomeType?

1
  • 2
    Presumably you actually use Eq (a (A a)) (not Eq (a b) for some arbitrary b) in the implementation of something, no? Commented Aug 17, 2019 at 17:05

1 Answer 1

6

It's not completely clear to me what you want to achieve, but this compiles:

{-# LANGUAGE QuantifiedConstraints, StandaloneDeriving, UndecidableInstances #-}

data A a = B (a (A a))

deriving instance (forall t. Eq t => Eq (a t)) => Eq (A a)

something :: (forall t. Eq t => Eq (a t)) => A a -> String
something x 
   | x==x      = "hello"
   | otherwise = "world"

The trick here is to require that Eq (a t) holds for any possible t. That requires QuantifiedConstraints.

Of course, you can also use a more modest approach and require instead

something :: Eq (a Bool) => A a -> String

but that won't allow you to use == on the argument.

Alternatively,

something :: Eq (A a) => A a -> String

should work, even if it triggers a warning.

Sign up to request clarification or add additional context in comments.

2 Comments

I have not seen QuantifiedConstraints before, so thanks. That works for me
@WilliamRusnack It was only introduced about a year ago, in GHC 8.6.1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.