Skip to content

Top-level signatures - #148

Closed
goldfirere wants to merge 8 commits into
ghc-proposals:masterfrom
goldfirere:top-level-sigs
Closed

goldfirere wants to merge 8 commits into
ghc-proposals:masterfrom
goldfirere:top-level-sigs

Conversation

@goldfirere

Copy link
Copy Markdown
Contributor

@nomeata

nomeata commented Jun 20, 2018

Copy link
Copy Markdown
Contributor

The new types will probably also necessitate inventing new wrappers to swizzle the type.

It is not immediately clear what this means.

@goldfirere goldfirere mentioned this pull request Jun 20, 2018
@AntC2

AntC2 commented Jun 20, 2018 •

Copy link
Copy Markdown
Contributor

I like that the explicit forall tells the order of type @pplication.

The examples using type ... :: ... show kind constructors on rhs. Is there a need to also write kind variables foralled)? (Is that a different proposal? Hard to keep up! Yes, see #54.)

For any top-level signature with variables (type or datatype or data constructor, or method -- especially methods), might we want to refer to the variables in the body of its definition? Then are we going to run into the same awkwardness as with ScopedTypeVariables?

I'm struggling to make up an example, but say meth3 in class C has a default definition:

  • the variables in meth3's top-level signature do not have to be the same name as in its signature within the class decl, presumably(?)
  • then in the body of meth3's default decl, what type variables are in scope?

To check my understanding: that T1, MkT1 decl could be written today with GADT syntax and KindSignatures?

data T1 (a :: Type) where                              -- implicitly T1 :: Type -> Type
  MkT1 :: forall b a. b -> (b -> a) -> T1 a

The P, MkP example likewise.

@AntC2

AntC2 commented Jun 21, 2018 •

Copy link
Copy Markdown
Contributor

For methods, I'm keen on the idea of giving a full foralled type possibly changing the order of type vars. But I'm not keen on giving the signatures stand-alone at top level:

  • It's too easily confused with a regular function signature (just needs a small typo).
  • Possibly puts the top-level signature textually a long way from the class decl.
  • Doubles-up: why a signature within the class and stand-alone?

EDIT: a possibly-fatal problem

  • Suppose there's a method default in the class; and suppose it uses type @pplication in the lhs pattern for an equation, per Type applications in patterns #126: which ordering of type arguments is it using?
  • (also might @pply for method equations inside instances.
    Note also you can put method signatures inside instances.)

end of EDIT.

For example class C, none of those stand-alone signatures would currently be valid inside the class. Then I think we keep backwards compatibility if we do:

class C a where
  meth :: forall b a. C a => a -> b -> b               -- new: reorders type variables and constraint
  meth2 :: forall a. a -> a                            -- rejected: see below
  meth3 :: forall a {b}. C a => a -> b -> b            -- new: with proposal #99, makes b *inferred*
  meth4 :: forall b. a -> b -> b                       -- OK: per status quo

If a method signature has explicit forall, the rule is:

  • if the method signature has free vars, their names must correspond to the class head.
    (And there must not be a constraint that repeats the class name, but other constraints are OK.)
    i.e. status quo, prefix forall for the free vars with the class constraint;
  • otherwise all vars must be foralled, and there must be a constraint that repeats the class name.

Then

  • meth2 above is rejected because no free vars but no C constraint.
  • meth4 is equiv to meth4 :: forall a b. C a => a -> b -> b, per status quo.
    Or meth4 :: forall a. C a => (forall b. a -> b -> b) ?

EDIT2: since this PR is aiming to subsume #129 and #54 for top-level type/kind signatures, I prefer to continue grouping everything together under where:

class Num a where
  fromInteger :: Integer -> forall a. Num a => a

So my rule above re "a constraint that repeats the class name" is to be interpreted as: the constraint can appear anywhere in the signature; the constraint must appear immediately within scope of an explicit forall for the class's tyvars. I think this reduces some of the implementation costs in validating the "type equivalence check" in section 4 of the proposal. And avoids whatever @goldfirere means by "swizzle the type".

Or was it the idea for addressing #129 that the current Prelude Num class decl would be unchanged; with the signature for fromInteger being grafted on from a different module?

For class type/kind/CUSKs:

class C a b where
  type C :: (k -> Type) -> k -> Constraint
  f :: a b

I think no danger of that type C :: ... being confused with an associated type family decl: it's same-named as the class; it must end in -> Constraint.

(Suggestion for data to follow next message.)

@AntC2

AntC2 commented Jun 21, 2018

Copy link
Copy Markdown
Contributor

For data, in same vein I'm dismayed at the double-up of decls, with risk of them getting out of kilter. (Also the very small lexical distance of a data constructor from a regular function: merely the case of the first letter.)

I think it's acceptable that to do something heinous with data decls, use GADT syntax. Then

data T1 a where
  MkT1 :: forall b a. b -> (b -> a) -> T1 a            -- new: signature reorders the b and a variables
  type T1 :: Type -> Type                              -- new: signature gives a kind to T1

data T2 where
  MkT2 { unT2 :: Int } :: T2
  unT2 :: T2 -> Int                                    -- new: we can see the full type for unT2

data P a where 
  type P :: (Type -> Type) -> Type                     -- new: specifies kind of a phantom parameter
  MkP :: a -> P

BTW for record fields: if we have DuplicateRecordFields, that signature for unT2 is too specific, because it ties to T2. Perhaps then, 'global' record fields should have top-level signatures:

unT2 :: Has r "unT2" a => r -> a

Perhaps @adamgundry could comment.

There's a couple of leftover fishhooks:

  • newtype: does anybody want to put a type/kind signature on them?
    (They don't have where groupings.)
  • The title of this PR/proposed extension could be misleading, because the signatures are semantically but not lexically at top-level ;-)

@goldfirere

Copy link
Copy Markdown
Contributor Author

I've updated the proposal to answer several of your questions in the text itself.

Briefly, this proposal has no meaningful interaction with the keyword forall: forall is never required (any more than it ever is), and the top-level signatures do not bring type variables into scope beyond the signature itself.

Yes, the T1 and P examples could be written with GADT syntax today. GADT syntax is already expressive enough to get the types right; this proposal can interact only with Haskell98-syntax data declarations.

For class methods, we can't make a choice based on whether the user has written a forall: Users can write forall in class methods today, and so the change you suggest would not be backward compatible.

  • It's true that the new signature could have a typo and that this is regrettable, but it's exactly the same with type signatures today. The user would get an error if the type signature did not correspond to a definition.

  • These type signatures, like all others, can appear from the definition site. It's up to authors to avoid this.

  • We need separate signatures in-class and out-of-class because several aspects are always left implicit in-class (the class constraint and the quantification over class variables). These can be made explicit out-of-class.

As for -XDuplicateRecordFields: I've clarified in the proposal. -XDuplicateRecordFields doesn't work with HasField at all, and so this new proposed syntax would find the record label to be ambiguous.

I've clarified that Haskell98-syntax newtype constructors are available for use with the proposed feature. (Newtypes can use where syntax, though they cannot be proper GADTs.)

How are these signatures not lexically or semantically at top level? (I'm considering the body of the module ... where at the top to still be considered "top-level", following general convention.)

@adamgundry

Copy link
Copy Markdown
Contributor

On -XDuplicateRecordFields, in principle we could be more generous and resolve the ambiguity in top-level type signatures for duplicate record fields: when type-checking the selector signature we could examine the domain type to tell us which datatype is meant, much as we do for selectors in expressions. Perhaps this would be fiddly to implement, though. I wouldn't be too worried about the details of the interaction with DRF, and would happily defer to the implementer to decide whether to bother with this.

Overall, I like this idea, though it sounds like the benefits might be relatively modest in comparison to the implementation cost.

@AntC2

AntC2 commented Jun 22, 2018 •

Copy link
Copy Markdown
Contributor

Thanks @goldfirere then I continue to be dismayed that this proposal requires giving two signatures. There's always going to be a chance they're out of kilter and/or the top-level one is non-obvious to the reader.

To be clear: I like the objective for this proposal. I think there's too much new syntax; and it's too heavyweight.

Is the two-signatures what's giving rise to the "type-equivalence check" and "swizzle the type" in section 4? Can we really not try harder to find a way to give only one signature? (My comment about not lexically top-level was a throwaway, hence the winky. Yes all these are semantically top-level decls.)

this proposal has no meaningful interaction with the keyword forall: forall is never required

Hmm? The forall is essential for meth (to reorder the tyvars -- and therefore it must also bind the class's var to order it); and meth3 (to mark a tyvar inferred -- true in that case it doesn't need to bind the class's var). My guess would be that in most cases where forall is not required, the H98-inferred signature is right, so you wouldn't need a top-level sig. If not, please put a counter-example in the write-up. For fromInteger the forall I suppose is not required, :: Integer -> Num a => a is sufficient (with RankNTypes) so that type @pplication can appear after the Integer.

But OK: for methods, can we look at still having a single sig within the class where, and putting an explicit class constraint to trigger what you want? That is currently illegal syntax, so is backwards compatible. Yes this is a change to in-class sigs; I can't see the implementation effort would be worse than handling double-sigs.

this proposal can interact only with Haskell98-syntax data declarations.

I hardly never write H98-syntax data decls. (I do for newtype, because they're lightweight; but for the same reason I can't see why I'd want a standalone type/kind sig -- I can annotate the tyvars.) I don't see any merit in introducing new syntax and double-decls and risk of out-of-kilter when there's a perfectly workable existing approach: you can always use GADT syntax.

And for data-related or newtype-related type/kind and field labels, why not put them right where they'd be most visible inside the where? (Thanks for pointing out you can use GADT syntax with newtype.)

Then if data-related type/kind is inside where, why not also class-related type/kind?

@gbaz

gbaz commented Jun 22, 2018

Copy link
Copy Markdown

Could you spell out the class motivation in more detail, for clarity?

In particular, why can't, today, we write:

class C a where
  meth :: forall b a. a -> b -> b
  meth3 :: forall a {b}. a -> b -> b

Rather than using the "forall" as the signifier for the expanded meaning, we would use quantification over a class variable. Currently, trying to declare meth as above leads to

    • Could not deduce (C a0)
      from the context: C a
        bound by the type signature for:
                   meth :: forall a. C a => forall b a1. a1 -> b -> b
        at Class.hs:4:3-33
      The type variable ‘a0’ is ambiguous

I can write something like this today

class C a b | b -> a where
  meth :: forall a. a -> b -> b

And that I think gets a different meaning under this idea. But writing something that overloads the a like that is dumb and confusing and nobody should do that anyway :-)

@AntC2

AntC2 commented Jun 22, 2018

Copy link
Copy Markdown
Contributor

Could you spell out the class motivation in more detail

Heh, heh @gbaz : in a post-Hindley-Milner type @pplication/signatures everywhere world, that's a subtle question. First I'll give the Haskell 2010 story.

But writing something that overloads the a like that is dumb and confusing and nobody should do that anyway

Yes. Why it's dumb is revealed in your error message:

    the type signature for:
               meth :: forall a. C a => forall b a1. a1 -> b -> b

So the compiler has prefixed to the signature you gave in-class: forall tyvars-of-the-class . Class-name tyvars-of-the-class =>. Then realised it has a tyvar name clash and renamed your a to a1.

Now tyvars-of-the-class don't appear in the type body, only in the constraint. That means that at any usage site for meth, the compiler can't look at the types of the arguments or result to select which instance for class C.

So the rule is: in the method signature, at least one of the class parameters must appear free. Note it doesn't need all of the class parameters to appear, so your second example is OK. One of the class parameters does appear, one doesn't, and that's exactly why FunctionalDependencies were invented: any that don't appear must be the target of a FunDep.

To give a speculative answer in a post-Hindley-Milner world:

Perhaps it doesn't matter if none of the class parameters appear in the method's signature. We could always supply them via type @pplication or explicit signature, such as:

x = meth @Int True "blah"

This is kinda using the class's type paramater as a phantom. It's a trick currently worked by using proxy type parameters. And indeed the distant-future proposal for duplicate record names/field selectors is using such a phantom: see the HasField class.

Rather than using the "forall" as the signifier for the expanded meaning, we would use quantification over a class variable.

If I understand @goldfirere correctly, he doesn't want to force use of forall. So my counter-suggestion was to look for the class constraint within the signature:

  • if it doesn't appear, this is a standard Haskell 2010-style method sig;
    prefix the forall and class constraint as revealed in your error message;
    apply the rule I gave re (some) class parameters appearing.
  • If it does appear, this is using the new-fangled TopLevelSignatures;
    then it doesn't matter whether the class's parameters are quantified.
    • If not quantified, then they're free, then they must be same-named as in the class head
      (and appear in the same sequence)
      this sub-bullet assumes that the signature appears in-class, as I'm suggesting.

I'll defer to Richard if I've mis-represented any of this.

@AntC2

AntC2 commented Jun 22, 2018

Copy link
Copy Markdown
Contributor

On the naming of cats

How are these signatures not lexically or semantically at top level?

All names and their signatures introduced in class or data decls are semantically top level; whether the name appears under a where is by the by.

  • TopLevelSignatures then is something of a misnomer.

Are we bound to produce (and consume) all of this proposal in one lump? Could we parcel it out?

  • FlexibleMethods -- cp FlexibleInstances, FlexibleContexts
  • FlexibleClasses -- or ClassSignatures
  • DataSignatures -- DataKinds already taken

@gbaz

gbaz commented Jun 22, 2018

Copy link
Copy Markdown

Sorry for the confusion. When I wrote "Could you spell out the class motivation in more detail, for clarity?" the "you" in question that the remainder was directed to was @goldfirere , which is whom I would like an answer from.

@RyanGlScott

Copy link
Copy Markdown
Contributor

One other potential use case for this feature which I find intriguing is the ability to specify the visibility of class-bound type variables. Currently, when you declare a class such as:

class C a b where
  meth :: a -> b -> c -> d -> ...

Then you have full control of how the type variables bound in the type signature of meth should be quantified. You could say:

You currently don't have much flexibility at all when it comes to class-bound variables a and b however—they must always be quantified invisibly (i.e., forall a b. C a b => ...). With this proposal, however, you'd be able to override this.

In particular, one compelling use case for this is to work around a bit of an awkward design pattern that currently exists in Haskell. You often see type classes of the form:

class Size a where
  size :: proxy a -> Int

Where the type a is only used to retrieve metadata—no value of type a is ever used. The Haskell98 way to accomplish this is shown above, by using proxies, which add syntactic noise. A slightly more modern equivalent of this is:

{-# LANGUAGE AllowAmbiguousTypes #-}
class Size a where
  size :: Int

But this requires all end-users of size to remember to specify what a is using TypeApplications, and if they forget, the resulting error messages are often abysmal.

I think the best design for this would be to leverage this proposal and write:

class Size a where
  size :: Int
size :: forall a -> Size a => Int

Then folks could just write size Int or size Bool, and since the a is quantified visibly, folks will get a nice error message if they forget to supply an argument for it.

Am I correct in thinking that this proposal would enable such an example? Moreover, would writing a top-level signature for size as above obviate the need to enable AllowAmbiguousTypes (even though the underlying class signature for size is technically ambiguous)?

@int-index

Copy link
Copy Markdown
Contributor

I'm in favor of this proposal, it resolves so many issues at once:

  • getting rid of CUSKs
  • reordering type variables for visible type application
  • specifying visibility of class-bound variables (as @RyanGlScott describes above)

and it is a natural extension to the language.

Though I'd be happy to advise someone who wants to implement, I do not plan on implementing this myself. It would make a decent project for someone who wants to get into GHC and wants a challenge.

If no one else volunteers, I can make an attempt at implementation.

@simonpj

simonpj commented Jun 29, 2018

Copy link
Copy Markdown
Contributor

I'm a bit doubtful about the proposal. The signatures we already have for class methods and data constructors are so close to top-level type signatures (yes, I know, not quite because of all the tyvar ordering stuff) that it may be more confusing than helpful to have as second type signature.

What is the problem that this proposal solves. What goes wrong if we just don't do it?

@RyanGlScott

Copy link
Copy Markdown
Contributor

What is the problem that this proposal solves.

Did you read the proposal? I'm not asking to be snarky—the proposal literally answers this exact question in the motivation section. See also #148 (comment), which provides further motivation.

@simonpj

simonpj commented Jun 29, 2018

Copy link
Copy Markdown
Contributor

I did. I just was not convinced. The tyvar shuffling business is pretty specialised; and you can always do it anyway by defining a wrapper function of your own. The fromInteger thing is a very special case because it's to do with built-in syntax.

It's a cost/benefit tradeoff, and (so far) I'm not convinced that the benefits justify the costs.

@RyanGlScott

Copy link
Copy Markdown
Contributor

To be clear, is your particular objection to this proposal about the concept of top-level signatures in general, or just top-level signatures for class methods? I ask since top-level signatures have other compelling use cases for type-level declarations (as proposed in #54), so it seems quite natural to me to extend this idea to other entities in Haskell for which you cannot directly write a top-level type signature.

The tyvar shuffling business is pretty specialised; and you can always do it anyway by defining a wrapper function of your own.

And yet, type variable shuffling (or more generally, proper quantification, as shown in #148 (comment)) is proving to become more and more important now that our quantifier syntax is becoming richer (see #102). I'd argue that this is a compelling enough use case on its own.

And saying "you can always define a wrapper function" is punting the problem down the road, as now all users who define instances of your class with methods that lack the proper quantification will have to suffer. I'd rather treat the problem at its source by using a top-level type signature, which allows those writing instances to benefit from the proper quantification as well.

The fromInteger thing is a very special case because it's to do with built-in syntax.

Yes, but this proposal would be a very important step into making the treatment for numeric literals less ad hoc which seems like a mighty good thing to me. The alternative, as discussed in #129, seems to take things into even further ad hoc territory.

@andrewthad

Copy link
Copy Markdown
Contributor

The signatures we already have for class methods and data constructors are so close to top-level type signatures... it may be more confusing than helpful to have as second type signature.

I feel this too. It seems strange to have a nearly correct type signature for a class method listed inside the class and then a correct one outside the class. I do wish we could tweak the quantification of type variables inside class methods. This proposal suggests (omitting the rejected meth2 signature):

class C a where
  meth :: a -> b -> b
  meth2 :: a -> a
  meth3 :: a -> b -> b
  meth4 :: b -> a

meth :: forall b a. C a => a -> b -> b               -- new: reorders type variables and constraint
meth3 :: forall a {b}. C a => a -> b -> b            -- new: with proposal #99, makes b *inferred*
meth4 :: C a => b -> a                               -- new: no forall required; this is redundant but allowed

As others have suggested, I would rather write:

class C a where
  meth :: forall b a. C a => a -> b -> b
  meth2 :: a -> a
  meth3 :: forall a {b}. C a => a -> b -> b
  meth4 :: C a => b -> a

To me, this syntax is much more clear, and I haven't been convinced by this thread that this isn't possible. Richard offers:

For class methods, we can't make a choice based on whether the user has written a forall: Users can write forall in class methods today, and so the change you suggest would not be backward compatible.

Users can write forall in class methods today, but they cannot use bring into scope a type variable that shaddows the one in the instance head. For example, with GHC 8.4.3, the following fails to compile:

class Foo a where
  foo :: forall a. a -> a

Consequently, there should not be any code that compiles today that wouldn't compile with the fancier class method quantification mechanism.

The original goal of this proposal is to resolve the awfulness of cusks. This proposal describes a features that does this and provides four examples (T1,T2,P, and C) of additional things that could be done with this features. However:

  • T1 and P are already doable today with GADT syntax
  • It's isn't clear how valuable T2 really is. (I've never heard anyone ask for this).
  • C requires duplicating type signatures (but is useful)

Would it not be easier to solve the cusk problem with a simple keyword? Something like this:

data cusk P :: (Type -> Type) -> Type where
  P :: P f

The keyword cusk would tell the type signature that a cusk is expected (and required).

@gbaz

gbaz commented Jun 29, 2018

Copy link
Copy Markdown

@andrewthad, I generally agree, but I do have a caveat. You write "Consequently, there should not be any code that compiles today that wouldn't compile with the fancier class method quantification mechanism."

However, I gave a counterexample to this above:

class C a b | b -> a where
  meth :: forall a. a -> b -> b

I would guess that no useful code today would be changed by this, but the above, perverse, example, does show code that would be changed by this. The trick is that the a quantified over doesn't match the one in the instance head, but that is ok, because the a in the instance head gets pinned nonetheless, by the functional dependency.

Overall, I think we should treat the three components of this proposal individually.

  1. data constructor signatures. the counterargument is that if you want that, you can just write a GADT. I'm not sure if there's any loss of power or weird corner case if we just force that distinction?

  2. kind signatures. Here I think it is the same as proposal Top-level kind signatures (instead of CUSKs) #54 and makes good sense.

  3. class signatures. Here, I would very much like to see what Richard thinks of @andrewthad's argumentation above.

@goldfirere

Copy link
Copy Markdown
Contributor Author

I've updated the proposal with some of the alternatives suggested. I'll try to respond to several points above:

I like @gbaz's suggestion of considering features separately. I count 4, not 3:

  1. Data constructor signatures. These could reasonably be dropped from the proposal, as there is no real downside to forcing users to use GADT syntax. It's a little disappointing, as I like to think of Haskell98 and GADT syntax as equally expressive, but that's a weak argument.

  2. Record selector signatures. The workaround here is to make a wrapper. The proposal now includes the possibility of requiring the signature to be in a GADT-syntax where clause, which seems like a fine idea.

  3. Class method signatures. I'm generally opposed to the idea of using syntactic clues to distinguish a new-style signature (call these complete signatures, as opposed to Haskell98 incomplete signatures). That's how CUSKs were born. And the Foo example of Top-level signatures #148 (comment) is actually acceptable today, with -XAllowAmbiguousTypes. (This is expanded slightly in the proposal.) We could perhaps use a keyword to label complete signatures. However, I still think that the separate top-level signature is better: the class method signatures within the class (the incomplete signatures) are understood to be in some context (that brings the class variables and constraint into scope), whereas the complete signatures are fully top-level. Mixing them together seems to invite more confusion, not less.

  4. Signatures for datatypes, à la Top-level kind signatures (instead of CUSKs) #54. While this proposal dovetails nicely with Top-level kind signatures (instead of CUSKs) #54, I think arguments hinging on CUSKs are red herrings here. Let's focus our debate on the extensions to Top-level kind signatures (instead of CUSKs) #54, not CUSKs.

A few other points to respond to:

  • @RyanGlScott: The idea of allowing visible dependent quantification in these signatures is indeed interesting. The proposal as written does not accommodate this idea, as it requires that the new type be equivalent w.r.t. GHC's subtyping relation with the old one. Invisible and visible quantification are unrelated by the subtyping relation, and so your signatures do not meet this requirement. We could consider relaxing the equivalence requirement, but I'm deeply unsure of how that would work. For example, if a class method has a top-level signature that adds a visible argument, do instances that define the method need to account for this new parameter? Doing so is strange, but not doing so loses the pattern-matching quality of function definitions. I guess that problem doesn't arise for data constructors and record selectors, though.

  • @simonpj: I understand how the benefits from this proposal may seem marginal. To me, though, this proposal offers some of the same benefits as do normal type signatures in, say, Standard ML, where type signatures are always redundant: they are documentation and an extra check on programmers. But I won't argue that this is proposal is very strongly motivated -- I just think it would be a nice feature.

@goldfirere

Copy link
Copy Markdown
Contributor Author

I just added support for pattern synonyms, too. This allows a pattern synonym to list its existential variables before its universals, useful in concert with #126. The repetition of the type signature is particularly galling here, though -- suggests there can be improvement in the syntax for pattern synonym signatures.

@AntC2

AntC2 commented May 13, 2019 •

Copy link
Copy Markdown
Contributor

@goldfirere The types I have been writing are not higher-rank (though you need that extension, which may be slightly misnamed). A higher-rank type has the forall in a function argument. My foralls are in function results. GHC treats forall a. a -> forall b. b -> (a, b) ...

Yes there the b does appear in result position. (The User Guide calls this 'Rank 1' and agrees it's not really higher-ranked, despite needing the extension.) But the one I'm asking about (and that you quoted)

   class C a where
     toplevel meth :: C b => b -> forall a. C a => a -> b

a does not appear in result position/does appear only to the left of ->. To put the parens

meth :: C b => b -> ( (forall a. C a => a) -> b)                          -- (A)

So what makes it not really higher-ranked? Oh, you want me to put parens like this

meth :: C b => b -> ( forall a. C a => (a -> b) )                         -- (B)

What's the rule (in the absence of parens) that tells me you mean (B) not (A)?

Whatever. I agree with @int-index the scoping rules are weird.

That's why I suggested separating concerns: the forall is for scoping, and only that. Then

Using @ in a type would mean something else... this is a bit like confusing a lambda with an arrow.

My understanding is that using @ in a type is currently illegal. (Unless @int-index means something by "visibility override".) Then I'm using it to mean 'when you use this meth in a term, you put the @pplication here'. It's definitional, not invoking application; seems to me reasonable in a declaration. Perhaps it would be clearer if I showed the @ beside the arrow-head

class Num a  where
  ...
  fromInteger :: Integer ->@ a

As for "subtype":

I'm not going to argue about semantics. (There are huge debates on the interwebs already.) All I'm saying is that "subtype" is a skunked term in the industry. And already has a usage in FP which is different. Avoid it if you can. And you can: the operative term you use is "equivalent". Give a definition for that in terms of substitutability. Actually, I think you just want types "unifiable"? Later correction: unifiable without alpha-renaming the tyvars from the class head. (Or is there some reason that won't work? Then please explain.)

Or if you do want to argue about semantics, this:

wherever a ty2 is expected, a ty1 is allowed. This definition works for the OOP languages ...

Is incomplete in OOP languages, because OOP also has (destructive) assignment where it works the other way round. See 'Liskov Substitution Principle'. And in OOP, what's "allowed" (on RHS) is that ty1 is strictly more specific than ty2 -- i.e. there are substitution instances of ty2 that are apart from ty1. You don't want that.

@gridaphobe

gridaphobe commented May 13, 2019 •

Copy link
Copy Markdown
Contributor

I notice also that you don't have toplevel on your declarations (presumably, because you want all signatures in the file to be top-level).

Right, I'm thinking that the same rules should apply to all signatures in the module, though at this point it doesn't feel like "top-level" describes the behavior properly.

With -XTopLevelSignatures, the class variables do not scope over method declarations. Instead, GHC uses its normal rules for quantifying type variables that are not in scope. The only changes to these rules are: 1) Absent an explicit forall, the class variables come first (in the order the appear in the class head), and 2) If the class constraint is not implied by constraints in scope by the result, the class constraint is added directly after the class variables are brought into scope.

This sounds pretty much like what I had in mind. Though, I think we should still require that the class variables be used in the signature, i.e. no funny business like

class C a b where
  m :: forall c d. C c d => c -> d

(I'm not sure if you intended to relax that requirement.)

@AntC2

AntC2 commented May 13, 2019 •

Copy link
Copy Markdown
Contributor

What's the rule (in the absence of parens) that tells me [the scope of a forall] ?

Note the User Guide (neither for ExplicitForAll nor RankNTypes) says nothing on the scope of an embedded forall. I think it should say the scope extends as far to the right as possible (without crossing )); and that if that reaches the end of the signature, then it's not really RankN.

Here's an example of the scope weirdness I think we all are worried about. Today I write

class C2 a b  where
    meth2 :: C2 a c => b -> c -> a -> d                  -- note leftmost appearance of `a'

    -- inferred meth2 :: (C2 a b, C2 a c) => b -> c -> a -> d
    -- properly       :: forall {a} {b} {c} {d}. (C2 a b, C2 a c) => b -> c -> a -> d

instance C2 Int String  where meth2 = undefined
instance C2 Int Char    where meth2 = undefined

baz2 :: (C2 a String, C2 a Char) => a -> d
baz2 = meth2 'q' "hello"

*> :t baz2                @Int       -- accepted OK
*> :t (meth2 'q' "hello") @Int       -- rejected, so ref transparency broken

wat :: forall b c d. b -> c -> (forall a. (C2 a b, C2 a c) => (a -> d) )          -- accepted
wat = meth2

    -- GHCi :t wat :: (C2 a b, C2 a c) => b -> c -> a -> d                        -- and yet

*> :t (wat 'q' "hello")   @Int       -- accepted OK

[Falls off chair] So I can use @pplication how @goldfirere is trying to arrange it. Note GHCi shows

*> :set -fprint-explicit-foralls
*> :t +v wat
wat :: forall b c d. b -> c -> forall a. (C2 a b, C2 a c) => a -> d

(Note I do need RankNTypes for that signature for wat; ExplicitForAll is not enough.)

So I can get the @ ordering today with a wrapper function. I can do the same for record selectors. Furthermore with #160 NoTopLevelFieldSelectors I could make the 'wrapper' same name as the field. For numeric literals I could go (5 :: Int). Then I'm left thinking this proposal isn't adding much.

@simonpj

simonpj commented May 13, 2019

Copy link
Copy Markdown
Contributor

I have not been following the details of this discussion, but I have another possible idea to put forward:

  • Class and data type decls remain unchanged
  • But you can, in addition, supply a top level signature for any class method or record field; and if you do, that's the type it has at every occurrence. No additional syntax whatsoever.

Example:

class Num a where
  fromInteger :: Integer -> a

fromInteger :: Integer -> forall a. Num a => a
-- Can occur anywhere in the same module as class Num's definition

It's a bit like worker/wrapper: the top-level signature gives the type of a wrapper, whose definition is just a call (perhapas with swizzled arguments) to the underlying secretly-named class method.

Advantages

  • No messing with class and data decls, which are already complicated enough
  • No new syntax
  • People often do this in a comment anyhow; this makes the "comment" machine-checked.

Apologies if this has already been discussed.

@int-index

Copy link
Copy Markdown
Contributor

@simonpj This was the old version of the proposal, and I think it was great, but then we somehow converged on the idea that the top-level signature should be inside the class declaration, not actually top-level, and @goldfirere came up with cunning scoping rules to make it work.

Given this design constraint, I came up with a use of class / data keywords that I like vastly more than cunning scoping, but if we drop this requirement, the old proposal works just fine. I'd be happy if we could simply revert to it, and you seem to be in support. (And it would also be consistent with #227)

@simonpj

simonpj commented May 13, 2019

Copy link
Copy Markdown
Contributor

This was the old version of the proposal,

Ah, sillly me. I hadn't realised that in the "old version" the top-level signature was strictly in addition to otherwise-unmodified data/class decls, and affects only occurrences.

Old or not, I'd like to see it in our conversation. I don't know how we "somehow converged on the idea that the top-level signature should be inside the class declaration", and I'm frar from sure I like it.

@AntC2

AntC2 commented May 13, 2019

Copy link
Copy Markdown
Contributor

@simonpj I'd like to see it in our conversation. I don't know how we "somehow converged on the idea that the top-level signature should be inside the class declaration", and I'm frar from sure I like it.

It is in the conversation on @goldfirere's revised proposal. There's a difficulty. But the difficulty isn't exposed with the fromInteger example. (Because it has only one constraint the same as the class.) Here's one with the difficulty, in your proposed style:

class C a where
  meth :: C b => b -> a -> b                           -- conventional decl, note extra C b =>

meth :: forall c. C c => c -> forall d. C d => d -> c  -- toplevel (per your proposal)

meth :: forall c. c -> forall d. D c d => d -> c       -- or a different toplevel, in which

class (C c, C d) => D c d  where ...

I've alpha-renamed the toplevel decl, just so you can't see what's going on. OK: in the toplevel decl, which of those constraints C c, C d (possibly via D c d) is the one that corresponds to C a in the class decl? It is I guess reasonably obvious by inspection with this example, from the arg position to meth. Would you like to lay down an infallible general rule?

@simonpj

simonpj commented May 13, 2019

Copy link
Copy Markdown
Contributor

I don't undersatnd teh difficulty.

class C a where
  meth :: C b => b -> a -> b  

This defines a private function, the "real selector for meth". Let's call it $meth:

$meth :: forall a.  C a => forall b. C b => b -> a -> b

Now you give a top-level signature for meth:

meth :: <type>   -- Either of the decls you gave in the preceding comment

I say this is accepted if and only if this declartion would typecheck

meth :: <tpye>
meth = $meth

Job done. At least that's what I intended.

@int-index

int-index commented May 13, 2019 •

Copy link
Copy Markdown
Contributor

One more reason I don't think it's a good idea to put top-level signatures in classes is that today the signature that we have inside the class is the actual signature of the field in the dictionary.

So I agree with Simon's worker/wrapper view of this: specify both the internal signature (for the dictionary field, and this would be the type used to define instances), and a wrapper signature (appearing on the top-level, used to call the class method)

@goldfirere

Copy link
Copy Markdown
Contributor Author

The new proposal was in response to, e.g., #148 (comment). But, actually, on a second flip through, I don't see much else in support of this new style. @gbaz had made a few comments in that direction, but I don't see unequivocal support.

Here's a problem with worker/wrapper: what happens in instance declarations? This question becomes more poignant with consideration for VDQ:

class Sized a where
  sizeOf :: Integer
sizeOf :: forall a -> Sized a => Integer

instance Sized Word32 where
  sizeOf = 4   -- choice (a), or
  sizeOf type.Word32 = 4   -- choice (b)

What do we think here? Also, with VDQ, the meth = $meth approach breaks down. Yet I think this would be quite useful!

@AntC2

AntC2 commented May 15, 2019

Copy link
Copy Markdown
Contributor

Here's a problem with worker/wrapper: ... consideration for VDQ:

   class Sized a where
     sizeOf :: Integer

That class isn't accepted, because sizeOf's signature doesn't mention a. So don't we need to solve several things for VDQ before we worry about toplevel signatures or instance decls? Perhaps the worker has a more conventional definition/instances. And the wrapper is just a stand-alone top level function that calls it.

@goldfirere

Copy link
Copy Markdown
Contributor Author

The Sized class of #148 (comment) is accepted with -XAllowAmbiguousTypes. Though, if we could declare the type with VDQ, like

class Sized a where
  toplevel sizeOf :: forall a -> Sized a => Integer

then it wouldn't be ambiguous.

@AntC2

AntC2 commented May 15, 2019

Copy link
Copy Markdown
Contributor

... accepted with -XAllowAmbiguousTypes

Oh, yes that extension considered harmful. One of the things I dislike about AllowAmbiguousTypes is that it's a global blunderbuss/abandon hope all ye who enter. If I switch it on in a module, then it applies for all my classes/methods; whereas I want the compiler to tell me if I've failed to mention a class parameter. (Contrast that if a failure-to-mention is covered by a FunDep, I must give ample and specific annotation I know what I'm doing.)

The idea of worker/wrapper for top level signatures seems easy to explain, and not too big of a stretch from writing different-named worker-wrappers today. Also we avoid an extra and clunky reservedword.

Then if there is legitimate code (such as for VDQ or functions deliberately to be called with @pplication) which currently needs AllowAmbiguousTypes, lets tackle a more targeted way to express that. Maybe

class Sized a where
  sizeOf :: {-# VDQ #-} Integer

The VDQ pragma to be available for any signature. Or it could go on the class head, but I guess your class might have some methods needing VDQ, some not.

Could I for the time being tackle this VDQ example with type-trickery such as

class Sized a where
  $sizeOf :: a -> Integer                   -- worker

sizeOf :: forall a -> Sized a => Integer    -- wrapper
sizeOf = ... ($sizeOf @blah undefined)

@goldfirere

Copy link
Copy Markdown
Contributor Author

To my own surprise, I've lost enthusiasm for this proposal. It's just too easy to do this via hand-written wrapper functions, and the syntactic challenges here are genuine. This proposal also falls into the category of proposals that introduce a syntactic nicety without an increase in expressiveness. These niceties are nice -- and I would use the feature proposed here occasionally -- but we can't have everything.

Unless someone changes my mind, I'll close this in a few days. (Of course, someone is welcome to adopt and push this through.)

I feel compelled to make one further point, though:

[-XAllowAmbiguousTypes is] considered harmful.

I know not everyone agrees, but I don't consider -XAllowAmbiguousTypes harmful. It simply allows definitions that may be hard (impossible?) to use without -XTypeApplications. These definitions do not compromise type safety or class coherence. If you don't use -XTypeApplications, then they're just useless definitions. My point in saying this is only that comments on the internet live a long time, and I want to provide a counterpoint to @AntC2's opinion that -XAllowAmbiguousTypes is harmful. He's welcome to believe that (and I see how someone can dislike that extension), but it's not universal.

@AntC2

AntC2 commented May 19, 2019

Copy link
Copy Markdown
Contributor

Thank you @goldfirere, I think it's been a valuable debate. One difficulty with VDQ I think remains for me

the syntactic challenges here are genuine.

I find it entirely unacceptable that putting a dependently-quantified type in a method requires non-mention of the class parameter in the method signature. Failing to mention (all) class parameters in a method signature is almost certainly an error. If you're doing it consciously, you must signal it very clearly (with FunctionalDependencies). So if currently the only recourse for VDQ is AllowAmbiguousTypes switched on globally for the module, that's a wart. (I think requiring also TypeApplications is not a solution: the method's going to be used outside this module; and anyway you can usually achieve the same effect with explicit type annotations.)

I'll reply separately on your points about AllowAmbiguousTypes. I think it's a topic on which reasonable people might reasonably disagree. Needing to sprinkle code with explicit typing in a Hindley-Milner language strikes me as much low-level programming as using GOTO, so I couldn't resist the "considered harmful" meme.

@int-index

Copy link
Copy Markdown
Contributor

I happen to agree with @AntC2 that -XAllowAmbiguousTypes are harmful.

If a definition is unusable without -XTypeApplications, it means we always need a visibility override @, and if the user forgets it, they will face inscrutable error messages. All uses of -XAllowAmbiguousTypes should be replaced by term-level VDQ eventually, so I view this extension as a temporary crutch until we get VDQ.

I've lost enthusiasm for this proposal

After our last conversation about scoping issues of GADTs, I think I won't be writing a competing proposal either. I still want to have uniform scoping rules for classes and GADTs, but now I'm not sure what they should be.

@AntC2

AntC2 commented May 19, 2019

Copy link
Copy Markdown
Contributor

@goldfirere -XAllowAmbiguousTypes ... simply allows definitions that may be hard (impossible?) to use without -XTypeApplications.

Then what you should say is that TypeApplications is useful (I don't disagree) and there are some use-cases for TypeApplications that require (some) method/function decls/terms to have ambiguous types, which get disambiguated where they jive up with TypeApplications. That's a very different position to trying to defend -XAllowAmbiguousTypes getting switched on across the whole of a module and silently smashing all the type checking GHC would usually go through.

I agree with @int-index we should be aiming for some term- or decl-level level pragma (similar idea to {-# OVERLAPPABLE #-}) that in effect says: I know what I'm doing here; I acknowledge the onus is on me to inform all users of this particular function/method they must use TypeApplications or similar.

Is it ever legitimate to switch on -XAllowAmbiguousTypes without TypeApplications? What are those use cases? Well, the User Guide for AllowAmbiguousTypes goes through some examples. I suggest you peruse some StackOverflow questions around AllowAmbiguousTypes to see whether that bit of the User Guide makes any sense to anybody. In particular whether it makes any sense as a warning-off to the people it's not going to help.

Perhaps we need an aptitude test before anybody's allowed to use AllowAmbiguousTypes: do you know what this is talking about?

a type ty is ambiguous if and only if ((undefined :: ty) :: ty) would fail to typecheck.

Those StackOverflow questions are by no means all from newbies. The harm is done because GHC's error message (which talks impenetrably about rigid type variables) recklessly suggests switching on AllowAmbiguousTypes.

a) If we had a newbie-mode for GHC, it should not be suggesting that at all.
b) For non-newbie users it should only suggest that if TypeApplications is also switched on.

Or the message should say: you'll probably need -XTypeApplications. Do you know what that entails? Otherwise steer clear.

We might lament that the pressure is on learners to get to an answer rather than to get to an understanding. But GHC throws them a lifeline "AllowAmbiguousTypes might help."; then tows them out into deep water; then dunks them. Thusly:

  1. Switching on AllowAmbiguousTypes gets this module to compile.

  2. Then importing it into the next module also complains about ambiguous types.

    Only these messages are much harder to understand, because the error site is removed from the ambiguous declaration. Oh, why didn't fixing it in the first module actually fix it?

  3. Then switch on AllowAmbiguousTypes here too and ... you get exactly the same complaint about ambiguity, plus exactly the same suggestion to switch on AllowAmbiguousTypes which is already on because you told me to grr. Is GHC stupid? Is it malicious?

So you'll see in the StackOverflow answers, there's typically some comments to-and-fro trying to tease out whether the questioner understands TypeApplications; then a patient process of switching off AllowAmbiguousTypes; regressing to the first point the error appeared; examining the code to explain what is a 'rigid type variable'; then fixing it. Most of the time AllowAmbiguousTypes is not the answer, and GHC's suggesting it causes confusion and frustration.

Perhaps saying "AllowAmbiguousTypes considered harmful" is too provocative. The more nuanced position is "GHC suggesting AllowAmbiguousTypes for no good reason considered harmful".

@int-index

int-index commented May 19, 2019 •

Copy link
Copy Markdown
Contributor

I agree with @int-index we should be aiming for some term- or decl-level level pragma

That's not what I said at all, though. I said we needed VDQ in terms, so that one could write

sizeOf :: forall a -> Sized a => Integer

and the users of this interface would write sizeOf Bool rather than sizeOf @Bool.

@AntC2

AntC2 commented May 19, 2019 •

Copy link
Copy Markdown
Contributor

Heh heh. The global AllowAmbiguousTypes makes EKmett "cry a little".

Jeepers. And this is the guy who rammed length (1,2) == 1 down our throats.

And a StackOverflow q in which ambiguous types appeared because of irresolvable overlapping instances (combined with FunDeps); but GHC suggested To defer the ambiguity check to use sites, enable AllowAmbiguousTypes, which fixed utterly nothing, but made for much more confusion.

@AntC2

AntC2 commented May 19, 2019

Copy link
Copy Markdown
Contributor

@int-index That's not what I said at all, ...

Ah, apologies for misunderstanding and misrepresenting. Getting to full-blown VDQ is much bigger a job than a pragma at a point where GHC currently would complain about ambiguous types(?) I didn't think you were proposing that much of a drama.

Are you suggesting that signature for sizeOf should go inside a class? Then aren't we back to all the difficulties this proposal bumped into? That is, we're foralling the type variable from the class head, despite the class head being lexically outside the scope of the forall.

If sizeOf isn't a method of the class, what does Sized's decl look like?

@int-index

Copy link
Copy Markdown
Contributor

Then aren't we back to all the difficulties this proposal bumped into?

Indeed, so I don't have a concrete proposal yet.

@goldfirere

Copy link
Copy Markdown
Contributor Author

Thanks, @AntC2, for #148 (comment). It's insightful. What I've wanted for some time (but haven't ever gotten around to making a reality) is a way for GHC error messages to refer users to web pages. The suggestions that -XAllowAmbiguousTypes will allow compilation are, strictly, correct. But I agree that they are often unhelpful (and, indeed, harmful) to users. Better would be a link to a page, defining ambiguity as describing a type where there is a variable in a constraint (or type family argument) that is otherwise unfixed. Then the page could talk about ways of disambiguating (e.g. type applications). Then it can explain -XAllowAmbiguousTypes. We can't do this in an error message. Of course, we could just slap a URL in the error text, but I would want the URL to go to an official, stable target... which doesn't exist. (We would then make other pages for "rigid, skolem" type variables and untouchable type variables, etc.)

Separately, I strongly support an {-# AMBIGUOUS #-} pragma to localize the acceptance ambiguous types, and then phasing out -XAllowAmbiguousTypes. There are other proposals I am more excited about writing and seeing through this process, but if you (for any value of "you") wish to propose, etc., I'll support.

As to the relationship between -XAllowAmbiguousTypes and -XTypeApplications: the former is needed at the definition site, while the latter is at the usage site. The history is this: -XAllowAmbiguousTypes predates -XTypeApplications. Then, -XTypeApplications originally implied -XAllowAmbiguousTypes. But it was argued that, because different modules might define and use, there was no need for the implication, so it got dropped. I don't think this is worth revisiting.

And @int-index's point is also interesting: once we have VDQ in terms, there will be little reason for ambiguity..... except, perversely, in class methods where (without this proposal) we can't write the signature we want. Even so, I now close this ticket.

@goldfirere goldfirere closed this May 19, 2019
@AntC2

AntC2 commented May 21, 2019

Copy link
Copy Markdown
Contributor

Heh heh. In parallel with the discussion here about AllowAmbiguousTypes, @yav experienced

If we AllowAmbiguousTypes, then the definition ... is accepted, but ... fails with a similar error, complaining that GHC cannot match ... because it is "untouchable".

This seems confusing ...

To which the response from @RyanGlScott

enable AllowAmbiguousTypes and hope for the best.

I think this underlines my concern that it's not just newbies who struggle with it.

@goldfirere {-# AMBIGUOUS #-} pragma to localize the acceptance ambiguous types, ... if you (for any value of "you") wish to propose, etc.,

I'll volunteer to write up that proposal -- or at least put up a strawperson to be improved by discussion. It goes without saying that there's only two people fully accredited to implement it; and I'm neither of them.

Having probed about a bit, I notice there's lots of error conditions GHC complains about tyvars being ambiguous. But not always does it suggest enable AllowAmbiguousTypes. (This presumably is why you can have that switched on but still get error messages about ambiguity.) Is it too much weasly words for the proposal to say: at the point GHC would make that suggestion, check if the signature has the {-# AMBIGUOUS #-} pragma, and suppress that error.

I think also useful would be a flag -Wallowed-ambiguous-types that issues the error message as a warning, so if you've set the global -XAllowAmbiguousTypes or a local pragma, you can at least hunt through for unexpected ambiguity.

@goldfirere

Copy link
Copy Markdown
Contributor Author

There are two potential problems dealing with ambiguity: at definition sites and at usage sites. -XAllowAmbiguousTypes and the hypothetical {-# AMBIGUOUS #-} pragma check only definitions. But many errors (e.g. read . show) are at usage sites. GHC correctly suggests -XAllowAmbiguousTypes only for the former.

Implementation of an {-# AMBIGUOUS #-} pragma should be relatively easy -- we just skip the check there. (In other words, don't worry about implementation.)

@simonpj

simonpj commented May 23, 2019

Copy link
Copy Markdown
Contributor

To my own surprise, I've lost enthusiasm for this proposal. It's just too easy to do this via hand-written wrapper functions, and the syntactic challenges here are genuine.

I rather agree. I'm not dead-set against it but I think we have bigger fish to fry.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.