[Haskell-cafe] DatatypeContexts / alternative

CASANOVA Juan Juan.Casanova at ed.ac.uk
Tue Feb 23 18:21:23 UTC 2021


Reply to myself:

I realized, with GADTs, it does assume Ord a, it's Ord b that fails. I can see how that cannot be derived from the context. Since Foo is only used for types with Ord, though, is there any way that I could let GHC know that this is going to be the case by definition.

(So basically, in a way that would make fmap not typecheck on Foo when trying to use a function (a -> b) where Ord b does not hold)

Sorry I did not realize this earlier.
________________________________
From: Haskell-Cafe <haskell-cafe-bounces at haskell.org> on behalf of CASANOVA Juan <Juan.Casanova at ed.ac.uk>
Sent: 23 February 2021 18:14
To: haskell-cafe at haskell.org <haskell-cafe at haskell.org>
Subject: [Haskell-cafe] DatatypeContexts / alternative

Hello again, Haskell Cafe,

Here again with another doubt on how am I supposed to. This one should be fairly easier, I believe.

In short, I would like to have a functor type that can only be applied to certain type parameters. Why? Well, something like this:

module DatatypeContextsExample where

import Data.Map
import Data.Bifunctor

data Foo t = Foo (Map t t)

instance Functor Foo where
    fmap f (Foo m) = Foo (fromList (fmap (bimap f f) (toList m)))

This does not compile, because I am using toList and fromList, which require (Ord t). But I cannot really have Foo be a functor in this way without it. The thing is, every time I am going to use it, t is actually going to be Ord. But how do I tell Haskell to have this constraint?

DatatypeContexts seems to be the extension that allows this:

data Ord t => Foo t = Foo (Map t t)

But this has two issues. First, DatatypeContexts is deprecated. Second, more importantly, it still does not type check! It produces the exact same error, saying that Ord t could not be inferred. It should be inferred from the very fact that I am using the type Foo, but GHC does not seem to want to understand this.

I could also try with GADTs:

data Foo t where
    Foo :: Ord t => Map t t -> Foo t

But this still gives the same error on the fmap definition, stating it cannot use Foo without Ord. But I am pattern-matching against it, shouldn't that be enough to know that (Ord t) is going to hold? I don't understand it.

Is there anything simple I am missing? Any other simple way to achieve this? Any fundamental problem with what I am trying to do?

Thanks as usual,
Juan.
The University of Edinburgh is a charitable body, registered in Scotland, with registration number SC005336. Is e buidheann carthannais a th’ ann an Oilthigh Dhùn Èideann, clàraichte an Alba, àireamh clàraidh SC005336.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/haskell-cafe/attachments/20210223/197efcc1/attachment.html>


More information about the Haskell-Cafe mailing list