Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: ScopedTypeVariables needed in pattern matching type annotations

Why does this code require the ScopedTypeVariables extension?

{-# LANGUAGE ScopedTypeVariables #-}

char = case Just '3' of 
    Just (x :: Char) -> x
    Nothing          -> '?'

When I read the documentation on ScopedTypeVariables, it seems to mean unifying type variables in the function body with the parent function signature. This code snippet isn't unifying any type variables though!

Also what is the effect of loading ScopedTypeVariables without also loading ExplicitForAll? All the other usecases of ScopedTypeVariables seem to require ExplicitForAll to actually work. But in the above snippet, there's no ExplicitForAll.

like image 374
CMCDragonkai Avatar asked Apr 19 '26 16:04

CMCDragonkai


1 Answers

ScopedTypeVariables enables ExplicitForAll automatically For the sake of your sanity I would suggest always using ScopedTypeVariables when using any other type system extensions (except possibly the ones dealing only with classes/instances/contexts) and never using ExplicitForAll directly.

The reason ScopedTypeVariables is required for pattern variable signatures is just that such signatures are part of the extension. Among other uses, they give you a way to bring a type variable into scope. For example:

f (Just (x::a)) = bob
  where
    bob::[a]
    bob = [x]

I do not know why the pattern signatures are part of ScopedTypeVariables, per se; most likely they were created for this purpose, and all the code was written in one go. Teasing them apart to make orthogonal extensions was almost certainly considered more trouble than it was worth.

Edit

Actually, there's a pretty good reason. With the exception of pattern bindings, a type variable in a pattern signature is generalized, bringing that variable into scope. So in the above example, you don't need to know if there is an a in the outer type environment. If you could enable pattern signatures without scoped type variables, then the variable could be generalized or not depending on whether scoped type variables were turned on or not. The same sort of confusion happens for ExplicitForAll without ScopedTypeVariables, which is why I'd like to kill that extension and make ScopedTypeVariables the default, or at least turn it on automatically with the extensions that currently enable ExplicitForAll.

like image 59
dfeuer Avatar answered Apr 23 '26 16:04

dfeuer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!